input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
|---|---|---|
#vulnerable code
public void clear() {
while (previousMove());
history.clear();
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void clear() {
initialize();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void drawWoodenBoard(Graphics2D g) {
if (uiConfig.getBoolean("fancy-board")) {
// fancy version
int shadowRadius = (int) (boardLength * MARGIN / 6);
BufferedImage boardImage = theme.getBoard();
// Support seamless texture
drawTextureImage(g, boardImage == null ? theme.getBoard() : boardImage, x - 2 * shadowRadius, y - 2 * shadowRadius, boardLength + 4 * shadowRadius, boardLength + 4 * shadowRadius);
g.setStroke(new BasicStroke(shadowRadius * 2));
// draw border
g.setColor(new Color(0, 0, 0, 50));
g.drawRect(x - shadowRadius, y - shadowRadius, boardLength + 2 * shadowRadius, boardLength + 2 * shadowRadius);
g.setStroke(new BasicStroke(1));
} else {
// simple version
JSONArray boardColor = uiConfig.getJSONArray("board-color");
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g.setColor(new Color(boardColor.getInt(0), boardColor.getInt(1), boardColor.getInt(2)));
g.fillRect(x, y, boardLength, boardLength);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void drawWoodenBoard(Graphics2D g) {
if (uiConfig.getBoolean("fancy-board")) {
if (cachedBoardImage == null) {
try {
cachedBoardImage = ImageIO.read(getClass().getResourceAsStream("/assets/board.png"));
} catch (IOException e) {
e.printStackTrace();
}
}
int shadowRadius = (int) (boardLength * MARGIN / 6);
drawTextureImage(g, cachedBoardImage, x - 2 * shadowRadius, y - 2 * shadowRadius, boardLength + 4 * shadowRadius, boardLength + 4 * shadowRadius);
g.setStroke(new BasicStroke(shadowRadius * 2));
// draw border
g.setColor(new Color(0, 0, 0, 50));
g.drawRect(x - shadowRadius, y - shadowRadius, boardLength + 2 * shadowRadius, boardLength + 2 * shadowRadius);
g.setStroke(new BasicStroke(1));
} else {
JSONArray boardColor = uiConfig.getJSONArray("board-color");
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g.setColor(new Color(boardColor.getInt(0), boardColor.getInt(1), boardColor.getInt(2)));
g.fillRect(x, y, boardLength, boardLength);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static boolean save(String filename) throws IOException {
FileOutputStream fp = new FileOutputStream(filename);
OutputStreamWriter writer = new OutputStreamWriter(fp);
StringBuilder builder = new StringBuilder(String.format("(;KM[7.5]AP[Lizzie: %s]", Lizzie.lizzieVersion));
BoardHistoryList history = Lizzie.board.getHistory();
while (history.previous() != null) ;
BoardData data = null;
while ((data = history.next()) != null) {
StringBuilder tag = new StringBuilder(";");
if (data.lastMoveColor.equals(Stone.BLACK)) {
tag.append("B");
} else if (data.lastMoveColor.equals(Stone.WHITE)) {
tag.append("W");
} else {
return false;
}
char x = (char) data.lastMove[0], y = (char) data.lastMove[1];
x += 'a';
y += 'a';
tag.append(String.format("[%c%c]", x, y));
builder.append(tag);
}
builder.append(')');
writer.append(builder.toString());
writer.close();
fp.close();
return true;
}
#location 15
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static boolean save(String filename) throws IOException {
FileOutputStream fp = new FileOutputStream(filename);
OutputStreamWriter writer = new OutputStreamWriter(fp);
try
{
// add SGF header
StringBuilder builder = new StringBuilder(String.format("(;KM[7.5]AP[Lizzie: %s]", Lizzie.lizzieVersion));
// move to the first move
BoardHistoryList history = Lizzie.board.getHistory();
while (history.previous() != null);
// replay moves, and convert them to tags.
// * format: ";B[xy]" or ";W[xy]"
// * with 'xy' = coordinates ; or 'tt' for pass.
BoardData data;
while ((data = history.next()) != null) {
String stone;
if (Stone.BLACK.equals(data.lastMoveColor)) stone = "B";
else if (Stone.WHITE.equals(data.lastMoveColor)) stone = "W";
else continue;
char x = data.lastMove == null ? 't' : (char) (data.lastMove[0] + 'a');
char y = data.lastMove == null ? 't' : (char) (data.lastMove[1] + 'a');
builder.append(String.format(";%s[%c%c]", stone, x, y));
}
// close file
builder.append(')');
writer.append(builder.toString());
}
finally
{
writer.close();
fp.close();
}
return true;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void ponder() {
isPondering = true;
startPonderTime = System.currentTimeMillis();
if (Lizzie.board.isAvoding && Lizzie.board.isKeepingAvoid && !isKataGo)
analyzeAvoid(
"avoid",
Lizzie.board.getHistory().isBlacksTurn() ? "w" : "b",
Lizzie.board.avoidCoords,
+Lizzie.config.config.getJSONObject("leelaz").getInt("avoid-keep-variations"));
else
sendCommand(
(this.isKataGo ? "kata-analyze " : "lz-analyze ")
+ Lizzie.config
.config
.getJSONObject("leelaz")
.getInt("analyze-update-interval-centisec")
+ (this.isKataGo && Lizzie.config.showKataGoEstimate ? " ownership true" : ""));
// until it responds to this, incoming
// ponder results are obsolete
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void ponder() {
isPondering = true;
startPonderTime = System.currentTimeMillis();
if (Lizzie.board.isAvoding && Lizzie.board.isKeepingAvoid && !isKataGo)
analyzeAvoid(
"avoid b "
+ Lizzie.board.avoidCoords
+ " "
+ Lizzie.config.config.getJSONObject("leelaz").getInt("avoid-keep-variations")
+ " avoid w "
+ Lizzie.board.avoidCoords
+ " "
+ Lizzie.config.config.getJSONObject("leelaz").getInt("avoid-keep-variations"));
else
sendCommand(
(this.isKataGo ? "kata-analyze " : "lz-analyze ")
+ Lizzie.config
.config
.getJSONObject("leelaz")
.getInt("analyze-update-interval-centisec")
+ (this.isKataGo && Lizzie.config.showKataGoEstimate ? " ownership true" : ""));
// until it responds to this, incoming
// ponder results are obsolete
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void sendCommand(String command) {
if (printCommunication) {
System.out.printf("> %s\n", command);
}
if (command.startsWith("fixed_handicap"))
isSettingHandicap = true;
if (command.startsWith("genmove"))
isThinking = true;
try {
outputStream.write((command + "\n").getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void sendCommand(String command) {
command = cmdNumber + " " + command;
cmdNumber++;
if (printCommunication) {
System.out.printf("> %s\n", command);
}
if (command.startsWith("fixed_handicap"))
isSettingHandicap = true;
try {
outputStream.write((command + "\n").getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private static boolean parse(String value) {
// Drop anything outside "(;...)"
final Pattern SGF_PATTERN = Pattern.compile("(?s).*?(\\(\\s*;.*\\)).*?");
Matcher sgfMatcher = SGF_PATTERN.matcher(value);
if (sgfMatcher.matches()) {
value = sgfMatcher.group(1);
} else {
return false;
}
// Determine the SZ property
Pattern szPattern = Pattern.compile("(?s).*?SZ\\[([\\d:]+)\\](?s).*");
Matcher szMatcher = szPattern.matcher(value);
if (szMatcher.matches()) {
String sizeStr = szMatcher.group(1);
Pattern sizePattern = Pattern.compile("([\\d]+):([\\d]+)");
Matcher sizeMatcher = sizePattern.matcher(sizeStr);
if (sizeMatcher.matches()) {
Lizzie.board.reopen(
Integer.parseInt(sizeMatcher.group(1)), Integer.parseInt(sizeMatcher.group(2)));
} else {
int boardSize = Integer.parseInt(sizeStr);
Lizzie.board.reopen(boardSize, boardSize);
}
} else {
Lizzie.board.reopen(19, 19);
}
int subTreeDepth = 0;
// Save the variation step count
Map<Integer, Integer> subTreeStepMap = new HashMap<Integer, Integer>();
// Comment of the game head
String headComment = "";
// Game properties
Map<String, String> gameProperties = new HashMap<String, String>();
Map<String, String> pendingProps = new HashMap<String, String>();
boolean inTag = false,
isMultiGo = false,
escaping = false,
moveStart = false,
addPassForMove = true;
boolean inProp = false;
String tag = "";
StringBuilder tagBuilder = new StringBuilder();
StringBuilder tagContentBuilder = new StringBuilder();
// MultiGo 's branch: (Main Branch (Main Branch) (Branch) )
// Other 's branch: (Main Branch (Branch) Main Branch)
if (value.matches("(?s).*\\)\\s*\\)")) {
isMultiGo = true;
}
String blackPlayer = "", whitePlayer = "";
// Support unicode characters (UTF-8)
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (escaping) {
// Any char following "\" is inserted verbatim
// (ref) "3.2. Text" in https://www.red-bean.com/sgf/sgf4.html
tagContentBuilder.append(c == 'n' ? "\n" : c);
escaping = false;
continue;
}
switch (c) {
case '(':
if (!inTag) {
subTreeDepth += 1;
// Initialize the step count
subTreeStepMap.put(subTreeDepth, 0);
addPassForMove = true;
pendingProps = new HashMap<String, String>();
} else {
if (i > 0) {
// Allow the comment tag includes '('
tagContentBuilder.append(c);
}
}
break;
case ')':
if (!inTag) {
if (isMultiGo) {
// Restore to the variation node
int varStep = subTreeStepMap.get(subTreeDepth);
for (int s = 0; s < varStep; s++) {
Lizzie.board.previousMove();
}
}
subTreeDepth -= 1;
} else {
// Allow the comment tag includes '('
tagContentBuilder.append(c);
}
break;
case '[':
if (!inProp) {
inProp = true;
if (subTreeDepth > 1 && !isMultiGo) {
break;
}
inTag = true;
String tagTemp = tagBuilder.toString();
if (!tagTemp.isEmpty()) {
// Ignore small letters in tags for the long format Smart-Go file.
// (ex) "PlayerBlack" ==> "PB"
// It is the default format of mgt, an old SGF tool.
// (Mgt is still supported in Debian and Ubuntu.)
tag = tagTemp.replaceAll("[a-z]", "");
}
tagContentBuilder = new StringBuilder();
} else {
tagContentBuilder.append(c);
}
break;
case ']':
if (subTreeDepth > 1 && !isMultiGo) {
break;
}
inTag = false;
inProp = false;
tagBuilder = new StringBuilder();
String tagContent = tagContentBuilder.toString();
// We got tag, we can parse this tag now.
if (tag.equals("B") || tag.equals("W")) {
moveStart = true;
addPassForMove = true;
int[] move = convertSgfPosToCoord(tagContent);
// Save the step count
subTreeStepMap.put(subTreeDepth, subTreeStepMap.get(subTreeDepth) + 1);
Stone color = tag.equals("B") ? Stone.BLACK : Stone.WHITE;
boolean newBranch = (subTreeStepMap.get(subTreeDepth) == 1);
if (move == null) {
Lizzie.board.pass(color, newBranch, false);
} else {
Lizzie.board.place(move[0], move[1], color, newBranch);
}
if (newBranch) {
processPendingPros(Lizzie.board.getHistory(), pendingProps);
}
} else if (tag.equals("C")) {
// Support comment
if (!moveStart) {
headComment = tagContent;
} else {
Lizzie.board.comment(tagContent);
}
} else if (tag.equals("LZ") && Lizzie.config.holdBestMovesToSgf) {
// Content contains data for Lizzie to read
String[] lines = tagContent.split("\n");
String[] line1 = lines[0].split(" ");
String line2 = "";
if (lines.length > 1) {
line2 = lines[1];
}
String versionNumber = line1[0];
Lizzie.board.getData().winrate = 100 - Double.parseDouble(line1[1]);
int numPlayouts =
Integer.parseInt(
line1[2]
.replaceAll("k", "000")
.replaceAll("m", "000000")
.replaceAll("[^0-9]", ""));
Lizzie.board.getData().setPlayouts(numPlayouts);
if (numPlayouts > 0 && !line2.isEmpty()) {
Lizzie.board.getData().bestMoves = Lizzie.leelaz.parseInfo(line2);
}
} else if (tag.equals("AB") || tag.equals("AW")) {
int[] move = convertSgfPosToCoord(tagContent);
Stone color = tag.equals("AB") ? Stone.BLACK : Stone.WHITE;
if (moveStart) {
// add to node properties
Lizzie.board.addNodeProperty(tag, tagContent);
if (addPassForMove) {
// Save the step count
subTreeStepMap.put(subTreeDepth, subTreeStepMap.get(subTreeDepth) + 1);
boolean newBranch = (subTreeStepMap.get(subTreeDepth) == 1);
Lizzie.board.pass(color, newBranch, true);
if (newBranch) {
processPendingPros(Lizzie.board.getHistory(), pendingProps);
}
addPassForMove = false;
}
Lizzie.board.addNodeProperty(tag, tagContent);
if (move != null) {
Lizzie.board.addStone(move[0], move[1], color);
}
} else {
if (move == null) {
Lizzie.board.pass(color);
} else {
Lizzie.board.place(move[0], move[1], color);
}
Lizzie.board.flatten();
}
} else if (tag.equals("PB")) {
blackPlayer = tagContent;
} else if (tag.equals("PW")) {
whitePlayer = tagContent;
} else if (tag.equals("KM")) {
try {
if (tagContent.trim().isEmpty()) {
tagContent = "0.0";
}
Lizzie.board.setKomi(Double.parseDouble(tagContent));
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else {
if (moveStart) {
// Other SGF node properties
if ("AE".equals(tag)) {
// remove a stone
if (addPassForMove) {
// Save the step count
subTreeStepMap.put(subTreeDepth, subTreeStepMap.get(subTreeDepth) + 1);
Stone color =
Lizzie.board.getHistory().getLastMoveColor() == Stone.WHITE
? Stone.BLACK
: Stone.WHITE;
boolean newBranch = (subTreeStepMap.get(subTreeDepth) == 1);
Lizzie.board.pass(color, newBranch, true);
if (newBranch) {
processPendingPros(Lizzie.board.getHistory(), pendingProps);
}
addPassForMove = false;
}
Lizzie.board.addNodeProperty(tag, tagContent);
int[] move = convertSgfPosToCoord(tagContent);
if (move != null) {
Lizzie.board.removeStone(
move[0], move[1], tag.equals("AB") ? Stone.BLACK : Stone.WHITE);
}
} else {
boolean firstProp = (subTreeStepMap.get(subTreeDepth) == 0);
if (firstProp) {
addProperty(pendingProps, tag, tagContent);
} else {
Lizzie.board.addNodeProperty(tag, tagContent);
}
}
} else {
addProperty(gameProperties, tag, tagContent);
}
}
break;
case ';':
break;
default:
if (subTreeDepth > 1 && !isMultiGo) {
break;
}
if (inTag) {
if (c == '\\') {
escaping = true;
continue;
}
tagContentBuilder.append(c);
} else {
if (c != '\n' && c != '\r' && c != '\t' && c != ' ') {
tagBuilder.append(c);
}
}
}
}
Lizzie.frame.setPlayers(whitePlayer, blackPlayer);
// Rewind to game start
while (Lizzie.board.previousMove()) ;
// Set AW/AB Comment
if (!headComment.isEmpty()) {
Lizzie.board.comment(headComment);
Lizzie.frame.refresh();
}
if (gameProperties.size() > 0) {
Lizzie.board.addNodeProperties(gameProperties);
}
return true;
}
#location 128
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private static boolean parse(String value) {
// Drop anything outside "(;...)"
final Pattern SGF_PATTERN = Pattern.compile("(?s).*?(\\(\\s*;{0,1}.*\\))(?s).*?");
Matcher sgfMatcher = SGF_PATTERN.matcher(value);
if (sgfMatcher.matches()) {
value = sgfMatcher.group(1);
} else {
return false;
}
// Determine the SZ property
Pattern szPattern = Pattern.compile("(?s).*?SZ\\[([\\d:]+)\\](?s).*");
Matcher szMatcher = szPattern.matcher(value);
int boardWidth = 19;
int boardHeight = 19;
if (szMatcher.matches()) {
String sizeStr = szMatcher.group(1);
Pattern sizePattern = Pattern.compile("([\\d]+):([\\d]+)");
Matcher sizeMatcher = sizePattern.matcher(sizeStr);
if (sizeMatcher.matches()) {
Lizzie.board.reopen(
Integer.parseInt(sizeMatcher.group(1)), Integer.parseInt(sizeMatcher.group(2)));
} else {
int boardSize = Integer.parseInt(sizeStr);
Lizzie.board.reopen(boardSize, boardSize);
}
} else {
Lizzie.board.reopen(boardWidth, boardHeight);
}
parseValue(value, null, false);
return true;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().playouts) {
history.getData().winrate = stats.maxWinrate;
history.getData().playouts = stats.totalPlayouts;
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) {
history.getData().winrate = stats.maxWinrate;
// we won't set playouts here. but setting winrate is ok... it shows the user that we are computing. i think its fine.
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) {
history.getData().winrate = stats.maxWinrate;
// we won't set playouts here. but setting winrate is ok... it shows the user that we are
// computing. i think its fine.
if (!Lizzie.config.holdWinrateToMove) {
history.getData().setPlayouts(stats.totalPlayouts);
}
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) {
history.getData().winrate = stats.maxWinrate;
// we won't set playouts here. but setting winrate is ok... it shows the user that we are
// computing. i think its fine.
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void reopen(int size) {
size = (size == 13 || size == 9) ? size : 19;
if (size != boardSize) {
boardSize = size;
initialize();
forceRefresh = true;
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void reopen(int size) {
size = (size >= 2) ? size : 19;
if (size != boardSize) {
boardSize = size;
Zobrist.init();
clear();
Lizzie.leelaz.sendCommand("boardsize " + boardSize);
forceRefresh = true;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) {
history.getData().winrate = stats.maxWinrate;
// we won't set playouts here. but setting winrate is ok... it shows the user that we are
// computing. i think its fine.
if (!Lizzie.config.holdWinrateToMove) {
history.getData().setPlayouts(stats.totalPlayouts);
}
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) {
history.getData().winrate = stats.maxWinrate;
// we won't set playouts here. but setting winrate is ok... it shows the user that we are
// computing. i think its fine.
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void drawMoveStatistics(Graphics2D g, int posX, int posY, int width, int height) {
if (width < 0 || height < 0)
return; // we don't have enough space
double lastWR;
if (Lizzie.board.getData().moveNumber == 0)
lastWR = 50;
else
lastWR = Lizzie.board.getHistory().getPrevious().winrate;
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
double curWR = stats.maxWinrate;
if (isPlayingAgainstLeelaz && playerIsBlack == !Lizzie.board.getHistory().getData().blackToPlay)
curWR = -100;
if (curWR < 0) {
curWR = 100 - lastWR;
}
double whiteWR, blackWR;
if (Lizzie.board.getData().blackToPlay) {
blackWR = curWR;
} else {
blackWR = 100 - curWR;
}
whiteWR = 100 - blackWR;
// Background rectangle
g.setColor(new Color(0, 0, 0, 130));
g.fillRect(posX, posY, width, height);
// border. does not include bottom edge
int strokeRadius = 3;
g.setStroke(new BasicStroke(2 * strokeRadius));
g.drawLine(posX + strokeRadius, posY + strokeRadius, posX - strokeRadius + width, posY + strokeRadius);
g.drawLine(posX + strokeRadius, posY + 3 * strokeRadius, posX + strokeRadius, posY - strokeRadius + height);
g.drawLine(posX - strokeRadius + width, posY + 3 * strokeRadius, posX - strokeRadius + width, posY - strokeRadius + height);
// resize the box now so it's inside the border
posX += 2 * strokeRadius;
posY += 2 * strokeRadius;
width -= 4 * strokeRadius;
height -= 4 * strokeRadius;
// Title
Font font = OpenSansRegularBase.deriveFont(Font.PLAIN, (int) (Math.min(width, height) * 0.2));
strokeRadius = 2;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.WHITE);
g.setFont(font);
// Last move
if (lastWR < 0)
// In case leelaz didnt have time to calculate
g.drawString(resourceBundle.getString("LizzieFrame.display.lastMove") + ": ?%", posX + 2 * strokeRadius, posY + height - 2 * strokeRadius);
else
g.drawString(resourceBundle.getString("LizzieFrame.display.lastMove") + String.format(": %.1f%%", 100 - lastWR - curWR), posX + 2 * strokeRadius,
posY + height - 2 * strokeRadius);// - font.getSize());
int maxBarwidth = (int) (width);
int barWidthB = (int) (blackWR * maxBarwidth / 100);
int barWidthW = (int) (whiteWR * maxBarwidth / 100);
int barPosY = posY + height / 3;
int barPosxB = (int) (posX);
int barPosxW = barPosxB + barWidthB;
int barHeight = height / 3;
// Draw winrate bars
g.fillRect(barPosxW, barPosY, barWidthW, barHeight);
g.setColor(Color.BLACK);
g.fillRect(barPosxB, barPosY, barWidthB, barHeight);
// Show percentage above bars
g.setColor(Color.WHITE);
g.drawString(String.format("%.1f%%", blackWR), barPosxB + 2 * strokeRadius, posY + barHeight - 2 * strokeRadius);
String winString = String.format("%.1f%%", whiteWR);
int sw = g.getFontMetrics().stringWidth(winString);
g.drawString(winString, barPosxB + maxBarwidth - sw - 2 * strokeRadius, posY + barHeight - 2 * strokeRadius);
g.setColor(Color.GRAY);
Stroke oldstroke = g.getStroke();
Stroke dashed = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0,
new float[]{4}, 0);
g.setStroke(dashed);
int middleX = barPosxB + (int) (maxBarwidth / 2);
g.drawLine(middleX, barPosY, middleX, barPosY + barHeight);
g.setStroke(oldstroke);
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void drawMoveStatistics(Graphics2D g, int posX, int posY, int width, int height) {
if (width < 0 || height < 0)
return; // we don't have enough space
double lastWR = 50; // winrate the previous move
boolean validLastWinrate = false; // whether it was actually calculated
BoardData lastNode = Lizzie.board.getHistory().getPrevious();
if (lastNode != null && lastNode.playouts > 0) {
lastWR = lastNode.winrate;
validLastWinrate = true;
}
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
double curWR = stats.maxWinrate; // winrate on this move
boolean validWinrate = (stats.totalPlayouts > 0); // and whether it was actually calculated
if (isPlayingAgainstLeelaz && playerIsBlack == !Lizzie.board.getHistory().getData().blackToPlay)
validWinrate = false;
if (!validWinrate) {
curWR = 100 - lastWR; // display last move's winrate for now (with color difference)
}
double whiteWR, blackWR;
if (Lizzie.board.getData().blackToPlay) {
blackWR = curWR;
} else {
blackWR = 100 - curWR;
}
whiteWR = 100 - blackWR;
// Background rectangle
g.setColor(new Color(0, 0, 0, 130));
g.fillRect(posX, posY, width, height);
// border. does not include bottom edge
int strokeRadius = 3;
g.setStroke(new BasicStroke(2 * strokeRadius));
g.drawLine(posX + strokeRadius, posY + strokeRadius,
posX - strokeRadius + width, posY + strokeRadius);
g.drawLine(posX + strokeRadius, posY + 3 * strokeRadius,
posX + strokeRadius, posY - strokeRadius + height);
g.drawLine(posX - strokeRadius + width, posY + 3 * strokeRadius,
posX - strokeRadius + width, posY - strokeRadius + height);
// resize the box now so it's inside the border
posX += 2 * strokeRadius;
posY += 2 * strokeRadius;
width -= 4 * strokeRadius;
height -= 4 * strokeRadius;
// Title
Font font = OpenSansRegularBase.deriveFont(Font.PLAIN, (int) (Math.min(width, height) * 0.2));
strokeRadius = 2;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.WHITE);
g.setFont(font);
// Last move
if (validLastWinrate && validWinrate)
g.drawString(resourceBundle.getString("LizzieFrame.display.lastMove") +
String.format(": %.1f%%", 100 - lastWR - curWR),
posX + 2 * strokeRadius,
posY + height - 2 * strokeRadius); // - font.getSize());
else {
// I think it's more elegant to just not display anything when we don't have
// valid data --dfannius
// g.drawString(resourceBundle.getString("LizzieFrame.display.lastMove") + ": ?%",
// posX + 2 * strokeRadius, posY + height - 2 * strokeRadius);
}
if (validWinrate || validLastWinrate) {
int maxBarwidth = (int) (width);
int barWidthB = (int) (blackWR * maxBarwidth / 100);
int barWidthW = (int) (whiteWR * maxBarwidth / 100);
int barPosY = posY + height / 3;
int barPosxB = (int) (posX);
int barPosxW = barPosxB + barWidthB;
int barHeight = height / 3;
// Draw winrate bars
g.fillRect(barPosxW, barPosY, barWidthW, barHeight);
g.setColor(Color.BLACK);
g.fillRect(barPosxB, barPosY, barWidthB, barHeight);
// Show percentage above bars
g.setColor(Color.WHITE);
g.drawString(String.format("%.1f%%", blackWR),
barPosxB + 2 * strokeRadius,
posY + barHeight - 2 * strokeRadius);
String winString = String.format("%.1f%%", whiteWR);
int sw = g.getFontMetrics().stringWidth(winString);
g.drawString(winString,
barPosxB + maxBarwidth - sw - 2 * strokeRadius,
posY + barHeight - 2 * strokeRadius);
g.setColor(Color.GRAY);
Stroke oldstroke = g.getStroke();
Stroke dashed = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0,
new float[]{4}, 0);
g.setStroke(dashed);
int middleX = barPosxB + (int) (maxBarwidth / 2);
g.drawLine(middleX, barPosY, middleX, barPosY + barHeight);
g.setStroke(oldstroke);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testGetPropertyType() throws Exception {
assertThat(TypeUtil.getPropertyType(A.class, "b.i").equals(Integer.class), equalTo(true));
assertThat(TypeUtil.getPropertyType(A.class, "s").equals(String.class), equalTo(true));
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testGetPropertyType() throws Exception {
assertThat(TypeUtil.getPropertyType(A.class, "b.i", "1").equals(Integer.class), equalTo(true));
assertThat(TypeUtil.getPropertyType(A.class, "s", "2").equals(String.class), equalTo(true));
TypeUtil.getPropertyType(A.class, "b.j", "3");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testGetPropertyType() throws Exception {
assertThat(TypeUtil.getPropertyType(A.class, "b.i").equals(Integer.class), equalTo(true));
assertThat(TypeUtil.getPropertyType(A.class, "s").equals(String.class), equalTo(true));
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testGetPropertyType() throws Exception {
assertThat(TypeUtil.getPropertyType(A.class, "b.i", "1").equals(Integer.class), equalTo(true));
assertThat(TypeUtil.getPropertyType(A.class, "s", "2").equals(String.class), equalTo(true));
TypeUtil.getPropertyType(A.class, "b.j", "3");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void executeDDL(Object test, String[] sqls) {
Connection connection = CONNECTION_TABLE.get(test);
try {
Statement statement = connection.createStatement();
for (int i = 0; i < sqls.length; i++) {
statement.execute(sqls[i]);
}
connection.commit();
statement.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static void executeDDL(Object test, String[] sqls) {
try {
executeSql(CONNECTION_TABLE.get(test), sqls);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected Properties getProperties() {
if (propertyFile!=null) {
Properties properties = new Properties(); // TODO: should we "inherit" from the ant projects properties ?
try {
properties.load(new FileInputStream(propertyFile) );
return properties;
}
catch (FileNotFoundException e) {
throw new BuildException(propertyFile + " not found.",e);
}
catch (IOException e) {
throw new BuildException("Problem while loading " + propertyFile,e);
}
} else {
return null;
}
}
#location 5
#vulnerability type RESOURCE_LEAK
|
#fixed code
protected Properties getProperties() {
if (propertyFile!=null) {
Properties properties = new Properties(); // TODO: should we "inherit" from the ant projects properties ?
FileInputStream is = null;
try {
is = new FileInputStream(propertyFile);
properties.load(is);
return properties;
}
catch (FileNotFoundException e) {
throw new BuildException(propertyFile + " not found.",e);
}
catch (IOException e) {
throw new BuildException("Problem while loading " + propertyFile,e);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
} else {
return null;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void execute() {
getLog().info("Starting " + this.getClass().getSimpleName() + "...");
RevengStrategy strategy = setupReverseEngineeringStrategy();
Properties properties = loadPropertiesFile();
MetadataDescriptor jdbcDescriptor = createJdbcDescriptor(strategy, properties);
executeExporter(jdbcDescriptor);
getLog().info("Finished " + this.getClass().getSimpleName() + "!");
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void execute() {
getLog().info("Starting " + this.getClass().getSimpleName() + "...");
RevengStrategy strategy = setupReverseEngineeringStrategy();
if (propertyFile.exists()) {
executeExporter(createJdbcDescriptor(strategy, loadPropertiesFile()));
} else {
getLog().info("Property file '" + propertyFile + "' cannot be found, aborting...");
}
getLog().info("Finished " + this.getClass().getSimpleName() + "!");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testPropertySet() throws FileNotFoundException, IOException {
GenericExporter ge = new GenericExporter();
ge.setConfiguration(getCfg());
ge.setOutputDirectory(getOutputDir());
Properties p = new Properties();
p.setProperty("proptest", "A value");
p.setProperty( "refproperty", "proptest=${proptest}" );
p.setProperty("hibernatetool.booleanProperty", "true");
p.setProperty("hibernatetool.myTool.toolclass", "org.hibernate.tool.hbm2x.Cfg2JavaTool");
ge.setProperties(p);
ge.setTemplateName("generictemplates/pojo/generic-class.ftl");
ge.setFilePattern("{package-name}/generic{class-name}.txt");
ge.start();
Properties generated = new Properties();
generated.load(new FileInputStream(new File(getOutputDir(), "org/hibernate/tool/hbm2x/genericArticle.txt")));
assertEquals(generated.getProperty("booleanProperty"), "true");
assertEquals(generated.getProperty("hibernatetool.booleanProperty"), "true");
assertNull(generated.getProperty("booleanWasTrue"));
assertEquals(generated.getProperty("myTool.value"), "value");
assertEquals(generated.getProperty("refproperty"), "proptest=A value");
}
#location 17
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testPropertySet() throws FileNotFoundException, IOException {
GenericExporter ge = new GenericExporter();
ge.setConfiguration(getCfg());
ge.setOutputDirectory(getOutputDir());
Properties p = new Properties();
p.setProperty("proptest", "A value");
p.setProperty( "refproperty", "proptest=${proptest}" );
p.setProperty("hibernatetool.booleanProperty", "true");
p.setProperty("hibernatetool.myTool.toolclass", "org.hibernate.tool.hbm2x.Cfg2JavaTool");
ge.setProperties(p);
ge.setTemplateName("generictemplates/pojo/generic-class.ftl");
ge.setFilePattern("{package-name}/generic{class-name}.txt");
ge.start();
Properties generated = new Properties();
FileInputStream is = null;
try {
is = new FileInputStream(new File(getOutputDir(), "org/hibernate/tool/hbm2x/genericArticle.txt"));
generated.load(is);
} finally {
if (is != null) {
is.close();
}
}
assertEquals(generated.getProperty("booleanProperty"), "true");
assertEquals(generated.getProperty("hibernatetool.booleanProperty"), "true");
assertNull(generated.getProperty("booleanWasTrue"));
assertEquals(generated.getProperty("myTool.value"), "value");
assertEquals(generated.getProperty("refproperty"), "proptest=A value");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public String getAllExecutors(String jobName, CuratorRepository.CuratorFrameworkOp curatorFrameworkOp) {
String executorsNodePath = SaturnExecutorsNode.getExecutorsNodePath();
if (!curatorFrameworkOp.checkExists(executorsNodePath)) {
return null;
}
StringBuilder allExecutorsBuilder = new StringBuilder();
StringBuilder offlineExecutorsBuilder = new StringBuilder();
List<String> executors = curatorFrameworkOp.getChildren(executorsNodePath);
if (executors != null && executors.size() > 0) {
for (String executor : executors) {
if (curatorFrameworkOp.checkExists(SaturnExecutorsNode.getExecutorTaskNodePath(executor))) {
continue;// 过滤容器中的Executor,容器资源只需要可以选择taskId即可
}
String ip = curatorFrameworkOp.getData(SaturnExecutorsNode.getExecutorIpNodePath(executor));
if (StringUtils.isNotBlank(ip)) {// if ip exists, means the executor is online
allExecutorsBuilder.append(executor + "(" + ip + ")").append(",");
continue;
}
offlineExecutorsBuilder.append(executor + "(该executor已离线)").append(",");// if ip is not exists,means the
// executor is offline
}
}
StringBuilder containerTaskIdsBuilder = new StringBuilder();
String containerNodePath = ContainerNodePath.getDcosTasksNodePath();
if (curatorFrameworkOp.checkExists(containerNodePath)) {
List<String> containerTaskIds = curatorFrameworkOp.getChildren(containerNodePath);
if (!CollectionUtils.isEmpty(containerTaskIds)) {
for (String containerTaskId : containerTaskIds) {
containerTaskIdsBuilder.append(containerTaskId + "(容器资源)").append(",");
}
}
}
allExecutorsBuilder.append(containerTaskIdsBuilder.toString());
allExecutorsBuilder.append(offlineExecutorsBuilder.toString());
String preferListNodePath = JobNodePath.getConfigNodePath(jobName, "preferList");
if (curatorFrameworkOp.checkExists(preferListNodePath)) {
String preferList = curatorFrameworkOp.getData(preferListNodePath);
if (!Strings.isNullOrEmpty(preferList)) {
String[] preferExecutorList = preferList.split(",");
for (String preferExecutor : preferExecutorList) {
if (executors != null && !executors.contains(preferExecutor) && !preferExecutor.startsWith("@")) {
allExecutorsBuilder.append(preferExecutor + "(该executor已删除)").append(",");
}
}
}
}
return allExecutorsBuilder.toString();
}
#location 29
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public String getAllExecutors(String jobName, CuratorRepository.CuratorFrameworkOp curatorFrameworkOp) {
String executorsNodePath = SaturnExecutorsNode.getExecutorsNodePath();
if (!curatorFrameworkOp.checkExists(executorsNodePath)) {
return null;
}
StringBuilder allExecutorsBuilder = new StringBuilder();
StringBuilder offlineExecutorsBuilder = new StringBuilder();
List<String> executors = curatorFrameworkOp.getChildren(executorsNodePath);
if (executors != null && executors.size() > 0) {
for (String executor : executors) {
if (curatorFrameworkOp.checkExists(SaturnExecutorsNode.getExecutorTaskNodePath(executor))) {
continue;// 过滤容器中的Executor,容器资源只需要可以选择taskId即可
}
String ip = curatorFrameworkOp.getData(SaturnExecutorsNode.getExecutorIpNodePath(executor));
if (StringUtils.isNotBlank(ip)) {// if ip exists, means the executor is online
allExecutorsBuilder.append(executor + "(" + ip + ")").append(",");
continue;
}
offlineExecutorsBuilder.append(executor + "(该executor已离线)").append(",");// if ip is not exists,means the
// executor is offline
}
}
String containerTaskIdsStr = generateContainerTaskIdStr(curatorFrameworkOp);
allExecutorsBuilder.append(containerTaskIdsStr);
allExecutorsBuilder.append(offlineExecutorsBuilder.toString());
String preferListNodePath = JobNodePath.getConfigNodePath(jobName, "preferList");
if (curatorFrameworkOp.checkExists(preferListNodePath)) {
String preferList = curatorFrameworkOp.getData(preferListNodePath);
if (!Strings.isNullOrEmpty(preferList)) {
String[] preferExecutorList = preferList.split(",");
for (String preferExecutor : preferExecutorList) {
if (executors != null && !executors.contains(preferExecutor) && !preferExecutor.startsWith("@")) {
allExecutorsBuilder.append(preferExecutor + "(该executor已删除)").append(",");
}
}
}
}
return allExecutorsBuilder.toString();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void refreshTreeData() {
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster : zkClusters) {
InitRegistryCenterService.initTreeJson(REGISTRY_CENTER_CONFIGURATION_MAP.get(zkCluster.getZkAddr()), zkCluster.getZkAddr());
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void refreshTreeData() {
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster : zkClusters) {
InitRegistryCenterService.initTreeJson(zkCluster.getRegCenterConfList(), zkCluster.getZkAddr());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public RegistryCenterConfiguration findConfigByNamespace(String namespace) {
if(Strings.isNullOrEmpty(namespace)){
return null;
}
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration each: REGISTRY_CENTER_CONFIGURATION_MAP.get(zkCluster.getZkAddr())) {
if (each != null && namespace.equals(each.getNamespace())) {
return each;
}
}
}
return null;
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public RegistryCenterConfiguration findConfigByNamespace(String namespace) {
if(Strings.isNullOrEmpty(namespace)){
return null;
}
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration each: zkCluster.getRegCenterConfList()) {
if (each != null && namespace.equals(each.getNamespace())) {
return each;
}
}
}
return null;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void zip(List<File> runtimeLibFiles, File saturnContainerDir, File zipFile) throws IOException {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
for(File file : saturnContainerDir.listFiles()) {
zip(file, "saturn", zos);
}
for(File file : runtimeLibFiles) {
zip(file, "app"+fileSeparator+"lib", zos);
}
zos.close();
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static void zip(List<File> runtimeLibFiles, File saturnContainerDir, File zipFile) throws IOException {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
/* for(File file : saturnContainerDir.listFiles()) {
zip(file, "saturn", zos);
}*/
for(File file : runtimeLibFiles) {
zip(file, "app"+fileSeparator+"lib", zos);
}
zos.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void run() {
while (!halted.get()) {
try {
synchronized (sigLock) {
while (paused && !halted.get()) {
try {
sigLock.wait(1000L);
} catch (InterruptedException ignore) {
}
}
if (halted.get()) {
break;
}
}
boolean noFireTime = false; // 没有下次执行时间,初始化为false
long timeUntilTrigger = 1000;
if (triggerObj != null) {
triggerObj.updateAfterMisfire(null);
long now = System.currentTimeMillis();
Date nextFireTime = triggerObj.getNextFireTime();
if (nextFireTime != null) {
timeUntilTrigger = nextFireTime.getTime() - now;
} else {
noFireTime = true;
}
}
while (!noFireTime && timeUntilTrigger > 2) {
synchronized (sigLock) {
if (halted.get()) {
break;
}
if (triggered) {
break;
}
try {
sigLock.wait(timeUntilTrigger);
} catch (InterruptedException ignore) {
}
if (triggerObj != null) {
long now = System.currentTimeMillis();
Date nextFireTime = triggerObj.getNextFireTime();
if (nextFireTime != null) {
timeUntilTrigger = nextFireTime.getTime() - now;
} else {
noFireTime = true;
}
}
}
}
boolean goAhead;
// 触发执行只有两个条件:1.时间到了;2。点立即执行;
synchronized (sigLock) {
goAhead = !halted.get() && !paused;
// 重置立即执行标志;
if (triggered) {
triggered = false;
} else { // 非立即执行。即,执行时间到了,或者没有下次执行时间。
goAhead = goAhead && !noFireTime;
if (goAhead && triggerObj != null) { // 执行时间到了,更新执行时间;没有下次执行时间,不更新时间,并且不执行作业
triggerObj.triggered(null);
}
}
}
if (goAhead) {
job.execute();
}
} catch (RuntimeException e) {
log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, job.getJobName(), e.getMessage()), e);
}
}
}
#location 64
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void run() {
while (!halted.get()) {
try {
synchronized (sigLock) {
while (paused && !halted.get()) {
try {
sigLock.wait(1000L);
} catch (InterruptedException ignore) {
}
}
if (halted.get()) {
break;
}
}
boolean noFireTime = false; // 没有下次执行时间,初始化为false
long timeUntilTrigger = 1000;
if (triggerObj != null) {
triggerObj.updateAfterMisfire(null);
long now = System.currentTimeMillis();
Date nextFireTime = triggerObj.getNextFireTime();
if (nextFireTime != null) {
timeUntilTrigger = nextFireTime.getTime() - now;
} else {
noFireTime = true;
}
}
while (!noFireTime && timeUntilTrigger > 2) {
synchronized (sigLock) {
if (halted.get()) {
break;
}
if (triggered) {
break;
}
try {
sigLock.wait(timeUntilTrigger);
} catch (InterruptedException ignore) {
}
if (triggerObj != null) {
long now = System.currentTimeMillis();
Date nextFireTime = triggerObj.getNextFireTime();
if (nextFireTime != null) {
timeUntilTrigger = nextFireTime.getTime() - now;
} else {
noFireTime = true;
}
}
}
}
boolean goAhead;
// 触发执行只有两个条件:1.时间到了 2.点立即执行
synchronized (sigLock) {
goAhead = !halted.get() && !paused;
// 重置立即执行标志;
if (triggered) {
triggered = false;
} else if(goAhead){ // 非立即执行。即,执行时间到了,或者没有下次执行时间
goAhead = goAhead && !noFireTime; // 有下次执行时间,即执行时间到了,才执行作业
if (goAhead) { // 执行时间到了,更新执行时间
if(triggerObj != null) {
triggerObj.triggered(null);
}
} else { // 没有下次执行时间,则尝试睡一秒,防止不停的循环导致CPU使用率过高(如果cron不再改为周期性执行)
try {
sigLock.wait(1000L);
} catch (InterruptedException ignore) {
}
}
}
}
if (goAhead) {
job.execute();
}
} catch (RuntimeException e) {
log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, job.getJobName(), e.getMessage()), e);
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public RegistryCenterConfiguration findConfig(String nameAndNamespace) {
if(Strings.isNullOrEmpty(nameAndNamespace)){
return null;
}
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration each: REGISTRY_CENTER_CONFIGURATION_MAP.get(zkCluster.getZkAddr())) {
if (each != null && nameAndNamespace.equals(each.getNameAndNamespace())) {
return each;
}
}
}
return null;
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public RegistryCenterConfiguration findConfig(String nameAndNamespace) {
if(Strings.isNullOrEmpty(nameAndNamespace)){
return null;
}
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration each: zkCluster.getRegCenterConfList()) {
if (each != null && nameAndNamespace.equals(each.getNameAndNamespace())) {
return each;
}
}
}
return null;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void handleResponse(CloseableHttpResponse httpResponse) throws IOException, SaturnJobException {
int status = httpResponse.getStatusLine().getStatusCode();
if (status == 201) {
logger.info("raise alarm successfully.");
return;
}
if (status >= 400 && status <= 500) {
HttpEntity entity = httpResponse.getEntity();
StringBuffer buffer = new StringBuffer();
if (entity != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent()));
String temp = null;
while ((temp = in.readLine()) != null) {
buffer.append(temp);
}
}
if (buffer.toString().length() > 0) {
String errMsg = JSONObject.parseObject(buffer.toString()).getString("message");
throw constructSaturnJobException(status, errMsg);
}
} else {
// if have unexpected status, then throw RuntimeException directly.
String errMsg = "unexpected status returned from Saturn Server.";
throw new SaturnJobException(SaturnJobException.SYSTEM_ERROR, errMsg);
}
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
private void handleResponse(CloseableHttpResponse httpResponse) throws IOException, SaturnJobException {
int status = httpResponse.getStatusLine().getStatusCode();
if (status == 201) {
logger.info("raise alarm successfully.");
return;
}
if (status >= 400 && status <= 500) {
String responseBody = EntityUtils.toString(httpResponse.getEntity());
if (StringUtils.isNotBlank(responseBody)) {
String errMsg = JSONObject.parseObject(responseBody).getString("message");
throw constructSaturnJobException(status, errMsg);
} else {
throw new SaturnJobException(SaturnJobException.SYSTEM_ERROR, "internal server error");
}
} else {
// if have unexpected status, then throw RuntimeException directly.
String errMsg = "unexpected status returned from Saturn Server.";
throw new SaturnJobException(SaturnJobException.SYSTEM_ERROR, errMsg);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static String[] getItemsPaths(String executorName, String jobName) {
String jobNamePath = String.format(EXECUTINGJOBPATH, executorName, jobName);
File jobNameFile = new File(jobNamePath);
if (!jobNameFile.exists() || jobNameFile.isFile()) {
return new String[0];
}
File[] files = jobNameFile.listFiles();
if(files.length == 0){
return new String[]{};
}
String[] filePaths = new String[files.length];
int i=0;
for(File file:files){
filePaths[i++] = file.getAbsolutePath();
}
return filePaths;
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static String[] getItemsPaths(String executorName, String jobName) {
String jobNamePath = String.format(EXECUTINGJOBPATH, executorName, jobName);
File jobNameFile = new File(jobNamePath);
if (!jobNameFile.exists() || jobNameFile.isFile()) {
return new String[0];
}
File[] files = jobNameFile.listFiles();
if(files == null || files.length == 0){
return new String[]{};
}
String[] filePaths = new String[files.length];
int i=0;
for(File file:files){
filePaths[i++] = file.getAbsolutePath();
}
return filePaths;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void init() {
if (zkConfig.isUseNestedZookeeper()) {
NestedZookeeperServers.getInstance().startServerIfNotStarted(zkConfig.getNestedPort(), zkConfig.getNestedDataDir());
}
log.info("msg=Saturn job: zookeeper registry center init, server lists is: {}.", zkConfig.getServerLists());
Builder builder = CuratorFrameworkFactory.builder()
.connectString(zkConfig.getServerLists())
.sessionTimeoutMs(SESSION_TIMEOUT)
.connectionTimeoutMs(CONNECTION_TIMEOUT)
.retryPolicy(new ExponentialBackoffRetry(zkConfig.getBaseSleepTimeMilliseconds(), zkConfig.getMaxRetries(), zkConfig.getMaxSleepTimeMilliseconds()))
.namespace(zkConfig.getNamespace());
if (0 != zkConfig.getSessionTimeoutMilliseconds()) {
builder.sessionTimeoutMs(zkConfig.getSessionTimeoutMilliseconds());
sessionTimeout = zkConfig.getSessionTimeoutMilliseconds();
}
if (0 != zkConfig.getConnectionTimeoutMilliseconds()) {
builder.connectionTimeoutMs(zkConfig.getConnectionTimeoutMilliseconds());
}
if (!Strings.isNullOrEmpty(zkConfig.getDigest())) {
builder.authorization("digest", zkConfig.getDigest().getBytes(Charset.forName("UTF-8")))
.aclProvider(new ACLProvider() {
@Override
public List<ACL> getDefaultAcl() {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
@Override
public List<ACL> getAclForPath(final String path) {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
});
}
client = builder.build();
client.start();
try {
client.getZookeeperClient().blockUntilConnectedOrTimedOut();
if (!client.getZookeeperClient().isConnected()) {
throw new Exception("the zk client is not connected");
}
client.checkExists().forPath(SLASH_CONSTNAT + zkConfig.getNamespace()); // check namespace node by using client, for UnknownHostException of connection string.
//CHECKSTYLE:OFF
} catch (final Exception ex) {
throw new RuntimeException("zk connect fail, zkList is " + zkConfig.getServerLists(),ex);
}
// start monitor.
if (zkConfig.getMonitorPort() > 0) {
MonitorService monitorService = new MonitorService(this, zkConfig.getMonitorPort());
monitorService.listen();
log.info("msg=zk monitor port starts at {}. usage: telnet {jobServerIP} {} and execute dump {jobName}", zkConfig.getMonitorPort(), zkConfig.getMonitorPort());
}
}
#location 51
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public void init() {
if (zkConfig.isUseNestedZookeeper()) {
NestedZookeeperServers.getInstance().startServerIfNotStarted(zkConfig.getNestedPort(), zkConfig.getNestedDataDir());
}
log.info("msg=Saturn job: zookeeper registry center init, server lists is: {}.", zkConfig.getServerLists());
Builder builder = CuratorFrameworkFactory.builder()
.connectString(zkConfig.getServerLists())
.sessionTimeoutMs(SESSION_TIMEOUT)
.connectionTimeoutMs(CONNECTION_TIMEOUT)
.retryPolicy(new ExponentialBackoffRetry(zkConfig.getBaseSleepTimeMilliseconds(), zkConfig.getMaxRetries(), zkConfig.getMaxSleepTimeMilliseconds()))
.namespace(zkConfig.getNamespace());
if (0 != zkConfig.getSessionTimeoutMilliseconds()) {
builder.sessionTimeoutMs(zkConfig.getSessionTimeoutMilliseconds());
sessionTimeout = zkConfig.getSessionTimeoutMilliseconds();
}
if (0 != zkConfig.getConnectionTimeoutMilliseconds()) {
builder.connectionTimeoutMs(zkConfig.getConnectionTimeoutMilliseconds());
}
if (!Strings.isNullOrEmpty(zkConfig.getDigest())) {
builder.authorization("digest", zkConfig.getDigest().getBytes(Charset.forName("UTF-8")))
.aclProvider(new ACLProvider() {
@Override
public List<ACL> getDefaultAcl() {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
@Override
public List<ACL> getAclForPath(final String path) {
return ZooDefs.Ids.CREATOR_ALL_ACL;
}
});
}
client = builder.build();
client.start();
try {
client.getZookeeperClient().blockUntilConnectedOrTimedOut();
if (!client.getZookeeperClient().isConnected()) {
throw new Exception("the zk client is not connected");
}
client.checkExists().forPath(SLASH_CONSTNAT + zkConfig.getNamespace()); // check namespace node by using client, for UnknownHostException of connection string.
//CHECKSTYLE:OFF
} catch (final Exception ex) {
throw new RuntimeException("zk connect fail, zkList is " + zkConfig.getServerLists(),ex);
}
// start monitor.
if (zkConfig.getMonitorPort() > 0) {
monitorService = new MonitorService(this, zkConfig.getMonitorPort());
monitorService.listen();
log.info("msg=zk monitor port starts at {}. usage: telnet {jobServerIP} {} and execute dump {jobName}", zkConfig.getMonitorPort(), zkConfig.getMonitorPort());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static List<Long> getPidsFromFile(String executorName, String jobName, String jobItem) {
List<Long> pids = new ArrayList<Long>();
//兼容旧版PID目录
Long pid = _getPidFromFile(executorName, jobName, jobItem);
if(pid > 0){
pids.add(pid);
}
String path = String.format(JOBITEMPIDSPATH, executorName, jobName, jobItem);
File dir = new File(path);
if (!dir.exists() || !dir.isDirectory()) {
return pids;
}
File[] files = dir.listFiles();
if(files.length == 0){
return pids;
}
for(File file:files){
try {
pids.add(Long.parseLong(file.getName()));
} catch (Exception e) {
log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, jobName, "Parsing the pid file error"), e);
}
}
return pids;
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static List<Long> getPidsFromFile(String executorName, String jobName, String jobItem) {
List<Long> pids = new ArrayList<Long>();
//兼容旧版PID目录
Long pid = _getPidFromFile(executorName, jobName, jobItem);
if(pid > 0){
pids.add(pid);
}
String path = String.format(JOBITEMPIDSPATH, executorName, jobName, jobItem);
File dir = new File(path);
if (!dir.exists() || !dir.isDirectory()) {
return pids;
}
File[] files = dir.listFiles();
if(files == null || files.length == 0){
return pids;
}
for(File file:files){
try {
pids.add(Long.parseLong(file.getName()));
} catch (Exception e) {
log.error(String.format(SaturnConstant.ERROR_LOG_FORMAT, jobName, "Parsing the pid file error"), e);
}
}
return pids;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void startNamespaceShardingManagerList(int count) throws Exception {
assertThat(nestedZkUtils.isStarted());
for (int i = 0; i < count; i++) {
shardingRegCenter = new ZookeeperRegistryCenter(new ZookeeperConfiguration(-1, nestedZkUtils.getZkString(), NAMESPACE, 1000, 3000, 3));
shardingRegCenter.init();
NamespaceShardingManager namespaceShardingManager = new NamespaceShardingManager((CuratorFramework) shardingRegCenter.getRawClient(),NAMESPACE, "127.0.0.1-" + i);
namespaceShardingManager.start();
namespaceShardingManagerList.add(namespaceShardingManager);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static void startNamespaceShardingManagerList(int count) throws Exception {
assertThat(nestedZkUtils.isStarted());
for (int i = 0; i < count; i++) {
ZookeeperRegistryCenter shardingRegCenter = new ZookeeperRegistryCenter(new ZookeeperConfiguration(-1, nestedZkUtils.getZkString(), NAMESPACE, 1000, 3000, 3));
shardingRegCenter.init();
NamespaceShardingManager namespaceShardingManager = new NamespaceShardingManager((CuratorFramework) shardingRegCenter.getRawClient(),NAMESPACE, "127.0.0.1-" + i);
namespaceShardingManager.start();
namespaceShardingManagerList.add(namespaceShardingManager);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void refreshNamespaceShardingListenerManagerMap() {
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration conf: REGISTRY_CENTER_CONFIGURATION_MAP.get(zkCluster.getZkAddr())) {
String namespace = conf.getNamespace();
if(!namespaceShardingListenerManagerMap.containsKey(namespace)) {
// client 从缓存取,不再新建也就不需要关闭
try {
CuratorFramework client = connect(conf.getNameAndNamespace()).getCuratorClient();
NamespaceShardingManager newObj = new NamespaceShardingManager(client, namespace, generateShardingLeadershipHostValue());
if (namespaceShardingListenerManagerMap.putIfAbsent(namespace, newObj) == null) {
log.info("start NamespaceShardingManager {}", namespace);
newObj.start();
log.info("done starting NamespaceShardingManager {}", namespace);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
// 关闭无用的
Iterator<Entry<String, NamespaceShardingManager>> iterator = namespaceShardingListenerManagerMap.entrySet().iterator();
while(iterator.hasNext()) {
Entry<String, NamespaceShardingManager> next = iterator.next();
String namespace = next.getKey();
NamespaceShardingManager namespaceShardingManager = next.getValue();
boolean find = false;
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration conf: REGISTRY_CENTER_CONFIGURATION_MAP.get(zkCluster.getZkAddr())) {
if(conf.getNamespace().equals(namespace)) {
find = true;
break;
}
}
}
if(!find) {
namespaceShardingManager.stop();
iterator.remove();
}
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void refreshNamespaceShardingListenerManagerMap() {
Collection<ZkCluster> zkClusters = RegistryCenterServiceImpl.ZKADDR_TO_ZKCLUSTER_MAP.values();
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration conf: zkCluster.getRegCenterConfList()) {
String nns = conf.getNameAndNamespace();
if(!namespaceShardingListenerManagerMap.containsKey(nns)) {
// client 从缓存取,不再新建也就不需要关闭
try {
CuratorFramework client = connect(conf.getNameAndNamespace()).getCuratorClient();
NamespaceShardingManager newObj = new NamespaceShardingManager(client, conf.getNamespace(), generateShardingLeadershipHostValue());
if (namespaceShardingListenerManagerMap.putIfAbsent(nns, newObj) == null) {
log.info("start NamespaceShardingManager {}", nns);
newObj.start();
log.info("done starting NamespaceShardingManager {}", nns);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
// 关闭无用的
Iterator<Entry<String, NamespaceShardingManager>> iterator = namespaceShardingListenerManagerMap.entrySet().iterator();
while(iterator.hasNext()) {
Entry<String, NamespaceShardingManager> next = iterator.next();
String nns = next.getKey();
NamespaceShardingManager namespaceShardingManager = next.getValue();
boolean find = false;
for (ZkCluster zkCluster: zkClusters) {
for(RegistryCenterConfiguration conf: zkCluster.getRegCenterConfList()) {
if(conf.getNameAndNamespace().equals(nns)) {
find = true;
break;
}
}
if(find) {
break;
}
}
if(!find) {
namespaceShardingManager.stop();
iterator.remove();
// clear NNS_CURATOR_CLIENT_MAP
RegistryCenterClient registryCenterClient = NNS_CURATOR_CLIENT_MAP.remove(nns);
if (registryCenterClient != null) {
log.info("close zk client in NNS_CURATOR_CLIENT_MAP, nns: {}");
CloseableUtils.closeQuietly(registryCenterClient.getCuratorClient());
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public <T> Cursor<T> queryForCursor(Query query, final Class<T> clazz) {
return new DelegatingCursor<T>(queryParsers.getForClass(query.getClass()).constructSolrQuery(query)) {
@Override
protected org.springframework.data.solr.core.query.result.DelegatingCursor.PartialResult<T> doLoad(
SolrQuery nativeQuery) {
QueryResponse response = executeSolrQuery(nativeQuery);
if (response == null) {
return new PartialResult<T>("", Collections.<T> emptyList());
}
return new PartialResult<T>(response.getNextCursorMark(), convertQueryResponseToBeans(response, clazz));
}
}.open();
}
#location 17
#vulnerability type RESOURCE_LEAK
|
#fixed code
public <T> Cursor<T> queryForCursor(Query query, final Class<T> clazz) {
return new DelegatingCursor<T>(queryParsers.getForClass(query.getClass()).constructSolrQuery(query)) {
@Override
protected org.springframework.data.solr.core.query.result.DelegatingCursor.PartialResult<T> doLoad(
SolrQuery nativeQuery) {
QueryResponse response = executeSolrQuery(nativeQuery, getSolrRequestMethod(getDefaultRequestMethod()));
if (response == null) {
return new PartialResult<T>("", Collections.<T> emptyList());
}
return new PartialResult<T>(response.getNextCursorMark(), convertQueryResponseToBeans(response, clazz));
}
}.open();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void deliver() {
if (actor.lifeCycle.isResuming()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this));
}
actor.lifeCycle.nextResuming();
} else if (actor.isDispersing()) {
internalDeliver(actor.lifeCycle.environment.stowage.swapWith(this));
} else {
internalDeliver(this);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void deliver() {
if (actor.lifeCycle.isResuming()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this));
}
actor.lifeCycle.nextResuming();
} else if (actor.isDispersing()) {
internalDeliver(this);
actor.lifeCycle.nextDispersing();
} else {
internalDeliver(this);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static <T> T createFor(final Class<T> protocol, final Actor actor, final Mailbox mailbox) {
final T maybeCachedProxy = actor.lifeCycle.environment.lookUpProxy(protocol);
if (maybeCachedProxy != null) {
return maybeCachedProxy;
}
final String proxyClassname = fullyQualifiedClassnameFor(protocol, "__Proxy");
final T maybeProxy = tryProxyFor(proxyClassname, actor, mailbox);
if (maybeProxy != null) {
actor.lifeCycle.environment.cacheProxy(maybeProxy);
return maybeProxy;
}
synchronized (protocol) {
T newProxy;
try {
newProxy = tryCreate(protocol, actor, mailbox, proxyClassname);
} catch (Exception e) {
newProxy = tryGenerateCreate(protocol, actor, mailbox, proxyClassname);
}
actor.lifeCycle.environment.cacheProxy(newProxy);
return newProxy;
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public static <T> T createFor(final Class<T> protocol, final Actor actor, final Mailbox mailbox) {
final T maybeCachedProxy = actor.lifeCycle.environment.lookUpProxy(protocol);
if (maybeCachedProxy != null) {
return maybeCachedProxy;
}
final String proxyClassname = fullyQualifiedClassnameFor(protocol, "__Proxy");
T newProxy;
try {
newProxy = tryCreate(protocol, actor, mailbox, proxyClassname);
} catch (Exception e) {
synchronized (protocol) {
newProxy = tryGenerateCreate(protocol, actor, mailbox, proxyClassname);
}
}
actor.lifeCycle.environment.cacheProxy(newProxy);
return newProxy;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void deliver() {
if (actor.__internal__IsResumed()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.__internal__Environment().suspended.swapWith(this));
}
actor.__internal__NextResuming();
} else if (actor.isDispersing()) {
internalDeliver(actor.__internal__Environment().stowage.swapWith(this));
} else {
internalDeliver(this);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void deliver() {
if (actor.lifeCycle.isResuming()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this));
}
actor.lifeCycle.nextResuming();
} else if (actor.isDispersing()) {
internalDeliver(actor.lifeCycle.environment.stowage.swapWith(this));
} else {
internalDeliver(this);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void deliver() {
if (actor.lifeCycle.isResuming()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this));
}
actor.lifeCycle.nextResuming();
} else if (actor.isDispersing()) {
internalDeliver(actor.lifeCycle.environment.stowage.swapWith(this));
} else {
internalDeliver(this);
}
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void deliver() {
if (actor.lifeCycle.isResuming()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this));
}
actor.lifeCycle.nextResuming();
} else if (actor.isDispersing()) {
internalDeliver(this);
actor.lifeCycle.nextDispersing();
} else {
internalDeliver(this);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void stop() {
if (stopped.compareAndSet(false, true)) {
stopChildren();
// suspended.reset();
// stowage.reset();
mailbox.close();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
void addChild(final Actor child) {
children.add(child);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
void addChild(final Actor child) {
children = children.plus(child);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
void addChild(final Actor child) {
children.add(child);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void deliver() {
if (actor.__internal__IsResumed()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.__internal__Environment().suspended.swapWith(this));
}
actor.__internal__NextResuming();
} else if (actor.isDispersing()) {
internalDeliver(actor.__internal__Environment().stowage.swapWith(this));
} else {
internalDeliver(this);
}
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void deliver() {
if (actor.lifeCycle.isResuming()) {
if (isStowed()) {
internalDeliver(this);
} else {
internalDeliver(actor.lifeCycle.environment.suspended.swapWith(this));
}
actor.lifeCycle.nextResuming();
} else if (actor.isDispersing()) {
internalDeliver(actor.lifeCycle.environment.stowage.swapWith(this));
} else {
internalDeliver(this);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public ZMQ.Event make(SendEvent sender, int eventFilter)
{
Ctx ctx = new Ctx();
@SuppressWarnings("deprecation")
SocketBase s = ctx.createSocket(ZMQ.PUB);
@SuppressWarnings("deprecation")
SocketBase m = ctx.createSocket(ZMQ.PAIR);
m.connect("inproc://TestEventResolution");
s.monitor("inproc://TestEventResolution", eventFilter);
sender.send(s, "tcp://127.0.0.1:8000");
zmq.ZMQ.Event ev = zmq.ZMQ.Event.read(m);
return new ZMQ.Event(ev.event, ev.arg, ev.addr);
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
public ZMQ.Event make(SendEvent sender, int eventFilter)
{
try (ZMQ.Context zctx = new ZMQ.Context(1);
ZMQ.Socket s = zctx.socket(SocketType.PUB);
ZMQ.Socket m = zctx.socket(SocketType.PAIR)) {
s.monitor("inproc://TestEventResolution", eventFilter);
m.connect("inproc://TestEventResolution");
sender.send(s.base(), "tcp://127.0.0.1:8000");
return ZMQ.Event.recv(m);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testProxy() throws Exception
{
Context ctx = ZMQ.context(1);
assert (ctx != null);
Main mt = new Main(ctx);
mt.start();
new Dealer(ctx, "AA").start();
new Dealer(ctx, "BB").start();
Thread.sleep(1000);
Thread c1 = new Client(ctx, "X");
c1.start();
Thread c2 = new Client(ctx, "Y");
c2.start();
c1.join();
c2.join();
ctx.term();
}
#location 19
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testProxy() throws Exception
{
int frontendPort = Utils.findOpenPort();
int backendPort = Utils.findOpenPort();
Context ctx = ZMQ.context(1);
assert (ctx != null);
Main mt = new Main(ctx, frontendPort, backendPort);
mt.start();
new Dealer(ctx, "AA", backendPort).start();
new Dealer(ctx, "BB", backendPort).start();
Thread.sleep(1000);
Thread c1 = new Client(ctx, "X", frontendPort);
c1.start();
Thread c2 = new Client(ctx, "Y", frontendPort);
c2.start();
c1.join();
c2.join();
ctx.term();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected boolean xsend(Msg msg_)
{
// If this is the first part of the message it's the ID of the
// peer to send the message to.
if (!more_out) {
assert (current_out == null);
// If we have malformed message (prefix with no subsequent message)
// then just silently ignore it.
// TODO: The connections should be killed instead.
if (msg_.has_more()) {
more_out = true;
// Find the pipe associated with the identity stored in the prefix.
// If there's no such pipe just silently ignore the message, unless
// mandatory is set.
Blob identity = new Blob(msg_.data());
Outpipe op = outpipes.get(identity);
if (op != null) {
current_out = op.pipe;
if (!current_out.check_write ()) {
op.active = false;
current_out = null;
if (mandatory) {
more_out = false;
errno.set(ZError.EAGAIN);
return false;
}
}
} else if (mandatory) {
more_out = false;
errno.set(ZError.EHOSTUNREACH);
return false;
}
}
return true;
}
// Check whether this is the last part of the message.
more_out = msg_.has_more();
// Push the message into the pipe. If there's no out pipe, just drop it.
if (current_out != null) {
boolean ok = current_out.write (msg_);
if (!ok)
current_out = null;
else if (!more_out) {
current_out.flush ();
current_out = null;
}
}
return true;
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
protected boolean xsend(Msg msg_)
{
// If this is the first part of the message it's the ID of the
// peer to send the message to.
if (!more_out) {
assert (current_out == null);
// If we have malformed message (prefix with no subsequent message)
// then just silently ignore it.
// TODO: The connections should be killed instead.
if (msg_.has_more()) {
more_out = true;
// Find the pipe associated with the identity stored in the prefix.
// If there's no such pipe just silently ignore the message, unless
// mandatory is set.
Blob identity = Blob.createBlob(msg_.data(), true);
Outpipe op = outpipes.get(identity);
if (op != null) {
current_out = op.pipe;
if (!current_out.check_write ()) {
op.active = false;
current_out = null;
if (mandatory) {
more_out = false;
errno.set(ZError.EAGAIN);
return false;
}
}
} else if (mandatory) {
more_out = false;
errno.set(ZError.EHOSTUNREACH);
return false;
}
}
return true;
}
// Check whether this is the last part of the message.
more_out = msg_.has_more();
// Push the message into the pipe. If there's no out pipe, just drop it.
if (current_out != null) {
boolean ok = current_out.write (msg_);
if (!ok)
current_out = null;
else if (!more_out) {
current_out.flush ();
current_out = null;
}
}
return true;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public int start ()
{
int rc = 0;
timers.addAll(newTimers);
newTimers.clear();
// Recalculate all timers now
for (STimer timer: timers) {
timer.when = timer.delay + System.currentTimeMillis();
}
Selector selector;
try {
selector = Selector.open();
} catch (IOException e) {
System.err.println (e.getMessage());
return -1;
}
// Main reactor loop
while (!Thread.currentThread().isInterrupted()) {
if (dirty) {
// If s_rebuild_pollset() fails, break out of the loop and
// return its error
rebuild ();
}
long wait = ticklessTimer();
rc = zmq.ZMQ.zmq_poll (selector, pollset, wait);
if (rc == -1) {
if (verbose)
System.out.printf ("I: zloop: interrupted\n", rc);
rc = 0;
break; // Context has been shut down
}
// Handle any timers that have now expired
Iterator<STimer> it = timers.iterator();
while (it.hasNext()) {
STimer timer = it.next();
if (System.currentTimeMillis() >= timer.when && timer.when != -1) {
if (verbose)
System.out.println ("I: zloop: call timer handler");
rc = timer.handler.handle(this, null, timer.arg);
if (rc == -1)
break; // Timer handler signalled break
if (timer.times != 0 && --timer.times == 0) {
it.remove();
}
else
timer.when = timer.delay + System.currentTimeMillis();
}
}
if (rc == -1)
break; // Some timer signalled break from the reactor loop
// Handle any pollers that are ready
for (int item_nbr = 0; item_nbr < poll_size; item_nbr++) {
SPoller poller = pollact [item_nbr];
assert (pollset [item_nbr].getSocket() == poller.item.getSocket());
if (pollset [item_nbr].isError()) {
if (verbose)
System.out.printf ("I: zloop: can't poll %s socket (%s, %s)",
poller.item.getSocket() != null? poller.item.getSocket().typeString(): "FD",
poller.item.getSocket(), poller.item.getChannel());
// Give handler one chance to handle error, then kill
// poller because it'll disrupt the reactor otherwise.
if (poller.errors++ > 0) {
pollerEnd (poller.item);
}
}
else
poller.errors = 0; // A non-error happened
if (pollset [item_nbr].readyOps() > 0) {
if (verbose)
System.out.printf ("I: zloop: call %s socket handler (%s, %s)\n",
poller.item.getSocket() != null? poller.item.getSocket().typeString(): "FD",
poller.item.getSocket(), poller.item.getChannel());
rc = poller.handler.handle (this, poller.item, poller.arg);
if (rc == -1)
break; // Poller handler signalled break
}
}
// Now handle any timer zombies
// This is going to be slow if we have many zombies
for (Object arg: zombies) {
it = timers.iterator();
while (it.hasNext()) {
STimer timer = it.next();
if (timer.arg == arg) {
it.remove();
}
}
}
// Now handle any new timers added inside the loop
timers.addAll(newTimers);
newTimers.clear();
if (rc == -1)
break;
}
try {
selector.close();
} catch (IOException e) {
}
return rc;
}
#location 32
#vulnerability type CHECKERS_PRINTF_ARGS
|
#fixed code
public int start ()
{
int rc = 0;
timers.addAll(newTimers);
newTimers.clear();
// Recalculate all timers now
for (STimer timer: timers) {
timer.when = timer.delay + System.currentTimeMillis();
}
Selector selector;
try {
selector = Selector.open();
} catch (IOException e) {
System.err.println (e.getMessage());
return -1;
}
// Main reactor loop
while (!Thread.currentThread().isInterrupted()) {
if (dirty) {
// If s_rebuild_pollset() fails, break out of the loop and
// return its error
rebuild ();
}
long wait = ticklessTimer();
rc = zmq.ZMQ.zmq_poll (selector, pollset, wait);
if (rc == -1) {
if (verbose)
System.out.println("I: zloop: interrupted");
rc = 0;
break; // Context has been shut down
}
// Handle any timers that have now expired
Iterator<STimer> it = timers.iterator();
while (it.hasNext()) {
STimer timer = it.next();
if (System.currentTimeMillis() >= timer.when && timer.when != -1) {
if (verbose)
System.out.println ("I: zloop: call timer handler");
rc = timer.handler.handle(this, null, timer.arg);
if (rc == -1)
break; // Timer handler signalled break
if (timer.times != 0 && --timer.times == 0) {
it.remove();
}
else
timer.when = timer.delay + System.currentTimeMillis();
}
}
if (rc == -1)
break; // Some timer signalled break from the reactor loop
// Handle any pollers that are ready
for (int item_nbr = 0; item_nbr < poll_size; item_nbr++) {
SPoller poller = pollact [item_nbr];
assert (pollset [item_nbr].getSocket() == poller.item.getSocket());
if (pollset [item_nbr].isError()) {
if (verbose)
System.out.printf ("I: zloop: can't poll %s socket (%s, %s)",
poller.item.getSocket() != null? poller.item.getSocket().typeString(): "FD",
poller.item.getSocket(), poller.item.getChannel());
// Give handler one chance to handle error, then kill
// poller because it'll disrupt the reactor otherwise.
if (poller.errors++ > 0) {
pollerEnd (poller.item);
}
}
else
poller.errors = 0; // A non-error happened
if (pollset [item_nbr].readyOps() > 0) {
if (verbose)
System.out.printf ("I: zloop: call %s socket handler (%s, %s)\n",
poller.item.getSocket() != null? poller.item.getSocket().typeString(): "FD",
poller.item.getSocket(), poller.item.getChannel());
rc = poller.handler.handle (this, poller.item, poller.arg);
if (rc == -1)
break; // Poller handler signalled break
}
}
// Now handle any timer zombies
// This is going to be slow if we have many zombies
for (Object arg: zombies) {
it = timers.iterator();
while (it.hasNext()) {
STimer timer = it.next();
if (timer.arg == arg) {
it.remove();
}
}
}
// Now handle any new timers added inside the loop
timers.addAll(newTimers);
newTimers.clear();
if (rc == -1)
break;
}
try {
selector.close();
} catch (IOException e) {
}
return rc;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public Command recv (long timeout_)
{
Command cmd_ = null;
// Try to get the command straight away.
if (active) {
cmd_ = cpipe.read ();
if (cmd_ != null) {
return cmd_;
}
// If there are no more commands available, switch into passive state.
active = false;
signaler.recv ();
}
// Wait for signal from the command sender.
boolean rc = signaler.wait_event (timeout_);
if (!rc)
return null;
assert (rc);
// We've got the signal. Now we can switch into active state.
active = true;
// Get a command.
cmd_ = cpipe.read ();
assert (cmd_ != null);
return cmd_;
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public Command recv (long timeout_)
{
Command cmd_ = null;
// Try to get the command straight away.
if (active) {
cmd_ = cpipe.read ();
if (cmd_ != null) {
return cmd_;
}
// If there are no more commands available, switch into passive state.
active = false;
signaler.recv ();
}
// Wait for signal from the command sender.
boolean rc = signaler.wait_event (timeout_);
if (!rc)
return null;
// We've got the signal. Now we can switch into active state.
active = true;
// Get a command.
cmd_ = cpipe.read ();
assert (cmd_ != null);
return cmd_;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main (String[] args) throws Exception {
// Prepare our context and sockets
ZMQ.Context context = ZMQ.context(1);
// Connect to task ventilator
ZMQ.Socket receiver = context.socket(ZMQ.PULL);
receiver.connect("tcp://localhost:5557");
// Connect to weather server
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5556");
subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET));
// Process messages from both sockets
// We prioritize traffic from the task ventilator
while (!Thread.currentThread ().isInterrupted ()) {
// Process any waiting tasks
byte[] task;
while((task = receiver.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process task");
}
// Process any waiting weather updates
byte[] update;
while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process weather update");
}
// No activity, so sleep for 1 msec
Thread.sleep(1000);
}
subscriber.close ();
context.term ();
}
#location 21
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main (String[] args) throws Exception {
// Prepare our context and sockets
ZMQ.Context context = ZMQ.context(1);
// Connect to task ventilator
ZMQ.Socket receiver = context.socket(ZMQ.PULL);
receiver.connect("tcp://localhost:5557");
// Connect to weather server
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5556");
subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET));
// Process messages from both sockets
// We prioritize traffic from the task ventilator
while (!Thread.currentThread ().isInterrupted ()) {
// Process any waiting tasks
byte[] task;
while((task = receiver.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process task");
}
// Process any waiting weather updates
byte[] update;
while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process weather update");
}
// No activity, so sleep for 1 msec
Thread.sleep(1000);
}
receiver.close ();
subscriber.close ();
context.term ();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private boolean identify_peer(Pipe pipe_)
{
Blob identity;
Msg msg = pipe_.read();
if (msg == null)
return false;
if (msg.size () == 0) {
// Fall back on the auto-generation
ByteBuffer buf = ByteBuffer.allocate(5);
buf.put((byte)0);
buf.putInt (next_peer_id++);
buf.flip();
identity = new Blob(buf);
}
else {
identity = new Blob(msg.data ());
// Ignore peers with duplicate ID.
if (outpipes.containsKey(identity))
return false;
}
pipe_.set_identity (identity);
// Add the record into output pipes lookup table
Outpipe outpipe = new Outpipe(pipe_, true);
outpipes.put (identity, outpipe);
return true;
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private boolean identify_peer(Pipe pipe_)
{
Blob identity;
Msg msg = pipe_.read();
if (msg == null)
return false;
if (msg.size () == 0) {
// Fall back on the auto-generation
ByteBuffer buf = ByteBuffer.allocate(5);
buf.put((byte) 0);
buf.putInt (next_peer_id++);
identity = Blob.createBlob(buf.array(), false);
}
else {
identity = Blob.createBlob(msg.data (), true);
// Ignore peers with duplicate ID.
if (outpipes.containsKey(identity))
return false;
}
pipe_.set_identity (identity);
// Add the record into output pipes lookup table
Outpipe outpipe = new Outpipe(pipe_, true);
outpipes.put (identity, outpipe);
return true;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main (String[] args) throws Exception {
// Prepare our context and sockets
ZMQ.Context context = ZMQ.context(1);
// Connect to task ventilator
ZMQ.Socket receiver = context.socket(ZMQ.PULL);
receiver.connect("tcp://localhost:5557");
// Connect to weather server
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5556");
subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET));
// Process messages from both sockets
// We prioritize traffic from the task ventilator
while (!Thread.currentThread ().isInterrupted ()) {
// Process any waiting tasks
byte[] task;
while((task = receiver.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process task");
}
// Process any waiting weather updates
byte[] update;
while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process weather update");
}
// No activity, so sleep for 1 msec
Thread.sleep(1000);
}
subscriber.close ();
context.term ();
}
#location 21
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main (String[] args) throws Exception {
// Prepare our context and sockets
ZMQ.Context context = ZMQ.context(1);
// Connect to task ventilator
ZMQ.Socket receiver = context.socket(ZMQ.PULL);
receiver.connect("tcp://localhost:5557");
// Connect to weather server
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5556");
subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET));
// Process messages from both sockets
// We prioritize traffic from the task ventilator
while (!Thread.currentThread ().isInterrupted ()) {
// Process any waiting tasks
byte[] task;
while((task = receiver.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process task");
}
// Process any waiting weather updates
byte[] update;
while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process weather update");
}
// No activity, so sleep for 1 msec
Thread.sleep(1000);
}
receiver.close ();
subscriber.close ();
context.term ();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void destroySocket(Socket s)
{
if (s == null) {
return;
}
if (sockets.remove(s)) {
s.setLinger(linger);
s.close();
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void destroySocket(Socket s)
{
if (s == null) {
return;
}
s.setLinger(linger);
s.close();
try {
mutex.lock();
this.sockets.remove(s);
}
finally {
mutex.unlock();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testConnectResolve()
{
System.out.println("test_connect_resolve running...\n");
Ctx ctx = ZMQ.init(1);
assertThat(ctx, notNullValue());
// Create pair of socket, each with high watermark of 2. Thus the total
// buffer space should be 4 messages.
SocketBase sock = ZMQ.socket(ctx, ZMQ.ZMQ_PUB);
assertThat(sock, notNullValue());
boolean brc = ZMQ.connect(sock, "tcp://localhost:1234");
assertThat(brc, is(true));
/*
try {
brc = ZMQ.connect (sock, "tcp://foobar123xyz:1234");
assertTrue(false);
} catch (IllegalArgumentException e) {
}
*/
ZMQ.close(sock);
ZMQ.term(ctx);
}
#location 26
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testConnectResolve() throws IOException
{
int port = Utils.findOpenPort();
System.out.println("test_connect_resolve running...\n");
Ctx ctx = ZMQ.init(1);
assertThat(ctx, notNullValue());
// Create pair of socket, each with high watermark of 2. Thus the total
// buffer space should be 4 messages.
SocketBase sock = ZMQ.socket(ctx, ZMQ.ZMQ_PUB);
assertThat(sock, notNullValue());
boolean brc = ZMQ.connect(sock, "tcp://localhost:" + port);
assertThat(brc, is(true));
/*
try {
brc = ZMQ.connect (sock, "tcp://foobar123xyz:" + port);
assertTrue(false);
} catch (IllegalArgumentException e) {
}
*/
ZMQ.close(sock);
ZMQ.term(ctx);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public final boolean bind(final String addr)
{
lock();
try {
if (ctxTerminated) {
errno.set(ZError.ETERM);
return false;
}
options.mechanism.check(options);
// Process pending commands, if any.
boolean brc = processCommands(0, false);
if (!brc) {
return false;
}
SimpleURI uri = SimpleURI.create(addr);
String address = uri.getAddress();
NetProtocol protocol = checkProtocol(uri.getProtocol());
if (protocol == null) {
return false;
}
switch(protocol) {
case inproc: {
Ctx.Endpoint endpoint = new Ctx.Endpoint(this, options);
boolean rc = registerEndpoint(addr, endpoint);
if (rc) {
connectPending(addr, this);
// Save last endpoint URI
options.lastEndpoint = addr;
}
else {
errno.set(ZError.EADDRINUSE);
}
return rc;
}
case pgm:
// continue
case epgm:
// continue
case norm:
// For convenience's sake, bind can be used interchangeable with
// connect for PGM, EPGM and NORM transports.
return connect(addr);
case tcp:
// continue
case ipc:
// continue
case tipc: {
// Remaining transports require to be run in an I/O thread, so at this
// point we'll choose one.
IOThread ioThread = chooseIoThread(options.affinity);
if (ioThread == null) {
errno.set(ZError.EMTHREAD);
return false;
}
Listener listener = protocol.getListener(ioThread, this, options);
boolean rc = listener.setAddress(address);
if (!rc) {
listener.destroy();
eventBindFailed(address, errno.get());
return false;
}
// Save last endpoint URI
options.lastEndpoint = listener.getAddress();
addEndpoint(options.lastEndpoint, listener, null);
return true;
}
default:
throw new IllegalArgumentException(addr);
}
}
finally {
unlock();
}
}
#location 63
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public final boolean bind(final String addr)
{
lock();
try {
if (ctxTerminated) {
errno.set(ZError.ETERM);
return false;
}
options.mechanism.check(options);
// Process pending commands, if any.
boolean brc = processCommands(0, false, null);
if (!brc) {
return false;
}
SimpleURI uri = SimpleURI.create(addr);
String address = uri.getAddress();
NetProtocol protocol = checkProtocol(uri.getProtocol());
if (protocol == null) {
return false;
}
switch(protocol) {
case inproc: {
Ctx.Endpoint endpoint = new Ctx.Endpoint(this, options);
boolean rc = registerEndpoint(addr, endpoint);
if (rc) {
connectPending(addr, this);
// Save last endpoint URI
options.lastEndpoint = addr;
}
else {
errno.set(ZError.EADDRINUSE);
}
return rc;
}
case pgm:
// continue
case epgm:
// continue
case norm:
// For convenience's sake, bind can be used interchangeable with
// connect for PGM, EPGM and NORM transports.
return connect(addr);
case tcp:
// continue
case ipc:
// continue
case tipc: {
// Remaining transports require to be run in an I/O thread, so at this
// point we'll choose one.
IOThread ioThread = chooseIoThread(options.affinity);
if (ioThread == null) {
errno.set(ZError.EMTHREAD);
return false;
}
Listener listener = protocol.getListener(ioThread, this, options);
boolean rc = listener.setAddress(address);
if (!rc) {
listener.destroy();
eventBindFailed(address, errno.get());
return false;
}
// Save last endpoint URI
options.lastEndpoint = listener.getAddress();
addEndpoint(options.lastEndpoint, listener, null);
return true;
}
default:
throw new IllegalArgumentException(addr);
}
}
finally {
unlock();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public ZMQ.Event make(SendEvent sender, int eventFilter)
{
Ctx ctx = new Ctx();
@SuppressWarnings("deprecation")
SocketBase s = ctx.createSocket(ZMQ.PUB);
@SuppressWarnings("deprecation")
SocketBase m = ctx.createSocket(ZMQ.PAIR);
m.connect("inproc://TestEventResolution");
s.monitor("inproc://TestEventResolution", eventFilter);
sender.send(s, "tcp://127.0.0.1:8000");
zmq.ZMQ.Event ev = zmq.ZMQ.Event.read(m);
return new ZMQ.Event(ev.event, ev.arg, ev.addr);
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public ZMQ.Event make(SendEvent sender, int eventFilter)
{
try (ZMQ.Context zctx = new ZMQ.Context(1);
ZMQ.Socket s = zctx.socket(SocketType.PUB);
ZMQ.Socket m = zctx.socket(SocketType.PAIR)) {
s.monitor("inproc://TestEventResolution", eventFilter);
m.connect("inproc://TestEventResolution");
sender.send(s.base(), "tcp://127.0.0.1:8000");
return ZMQ.Event.recv(m);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void destroy()
{
for (Socket socket : sockets) {
socket.setLinger(linger);
socket.close();
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain() && context != null) {
context.term();
}
synchronized (this) {
context = null;
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void destroy()
{
for (Socket socket : sockets) {
destroySocket(socket);
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain() && context != null) {
context.term();
context = null;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test(timeout = 1000)
public void testSocketDoubleClose()
{
Context ctx = ZMQ.context(1);
Socket socket = ctx.socket(ZMQ.PUSH);
socket.close();
socket.close();
}
#location 5
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test(timeout = 1000)
public void testSocketDoubleClose()
{
Context ctx = ZMQ.context(1);
Socket socket = ctx.socket(ZMQ.PUSH);
socket.close();
socket.close();
ctx.term();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testIssue476() throws InterruptedException, IOException, ExecutionException
{
final int front = Utils.findOpenPort();
final int back = Utils.findOpenPort();
final int max = 10;
ExecutorService service = Executors.newFixedThreadPool(3);
final ZContext ctx = new ZContext();
service.submit(new Runnable()
{
@Override
public void run()
{
Thread.currentThread().setName("Proxy");
ZMQ.Socket xpub = ctx.createSocket(SocketType.XPUB);
xpub.bind("tcp://*:" + back);
ZMQ.Socket xsub = ctx.createSocket(SocketType.XSUB);
xsub.bind("tcp://*:" + front);
ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR);
ctrl.bind("inproc://ctrl-proxy");
ZMQ.proxy(xpub, xsub, null, ctrl);
}
});
final AtomicReference<Throwable> error = testIssue476(front, back, max, service, ctx);
ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR);
ctrl.connect("inproc://ctrl-proxy");
ctrl.send(ZMQ.PROXY_TERMINATE);
ctrl.close();
service.shutdown();
service.awaitTermination(2, TimeUnit.SECONDS);
assertThat(error.get(), nullValue());
ctx.close();
}
#location 24
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testIssue476() throws InterruptedException, IOException, ExecutionException
{
final int front = Utils.findOpenPort();
final int back = Utils.findOpenPort();
final int max = 20;
ExecutorService service = Executors.newFixedThreadPool(3);
try (final ZContext ctx = new ZContext()) {
service.submit(() -> {
Thread.currentThread().setName("Proxy");
Socket xpub = ctx.createSocket(SocketType.XPUB);
xpub.bind("tcp://*:" + back);
Socket xsub = ctx.createSocket(SocketType.XSUB);
xsub.bind("tcp://*:" + front);
Socket ctrl = ctx.createSocket(SocketType.PAIR);
ctrl.bind("inproc://ctrl-proxy");
ZMQ.proxy(xpub, xsub, null, ctrl);
});
final AtomicReference<Throwable> error = testIssue476(front, back, max, service, ctx);
ZMQ.Socket ctrl = ctx.createSocket(SocketType.PAIR);
ctrl.connect("inproc://ctrl-proxy");
ctrl.send(ZMQ.PROXY_TERMINATE);
ctrl.close();
service.shutdown();
service.awaitTermination(2, TimeUnit.SECONDS);
assertThat(error.get(), nullValue());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public byte[] receive(int flags)
{
final Msg msg = socketBase.recv(flags);
return msg.data();
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public byte[] receive(int flags)
{
final Msg msg = socketBase.recv(flags);
if (msg == null) {
return null;
}
return msg.data();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void destroy()
{
for (Socket socket : sockets) {
socket.setLinger(linger);
socket.close();
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain() && context != null) {
context.term();
}
synchronized (this) {
context = null;
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void destroy()
{
for (Socket socket : sockets) {
destroySocket(socket);
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain() && context != null) {
context.term();
context = null;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main (String[] args) throws Exception {
// Prepare our context and sockets
ZMQ.Context context = ZMQ.context(1);
// Connect to task ventilator
ZMQ.Socket receiver = context.socket(ZMQ.PULL);
receiver.connect("tcp://localhost:5557");
// Connect to weather server
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5556");
subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET));
// Process messages from both sockets
// We prioritize traffic from the task ventilator
while (!Thread.currentThread ().isInterrupted ()) {
// Process any waiting tasks
byte[] task;
while((task = receiver.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process task");
}
// Process any waiting weather updates
byte[] update;
while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process weather update");
}
// No activity, so sleep for 1 msec
Thread.sleep(1000);
}
subscriber.close ();
context.term ();
}
#location 30
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main (String[] args) throws Exception {
// Prepare our context and sockets
ZMQ.Context context = ZMQ.context(1);
// Connect to task ventilator
ZMQ.Socket receiver = context.socket(ZMQ.PULL);
receiver.connect("tcp://localhost:5557");
// Connect to weather server
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5556");
subscriber.subscribe("10001 ".getBytes(ZMQ.CHARSET));
// Process messages from both sockets
// We prioritize traffic from the task ventilator
while (!Thread.currentThread ().isInterrupted ()) {
// Process any waiting tasks
byte[] task;
while((task = receiver.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process task");
}
// Process any waiting weather updates
byte[] update;
while ((update = subscriber.recv(ZMQ.DONTWAIT)) != null) {
System.out.println("process weather update");
}
// No activity, so sleep for 1 msec
Thread.sleep(1000);
}
receiver.close ();
subscriber.close ();
context.term ();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
boolean wasPending (kvmsg msg)
{
Iterator<kvmsg> it = pending.iterator();
while (it.hasNext()) {
if (msg.UUID().equals(it.next().UUID())) {
it.remove();
return true;
}
}
return false;
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
boolean wasPending (kvmsg msg)
{
Iterator<kvmsg> it = pending.iterator();
while (it.hasNext()) {
if(java.util.Arrays.equals(msg.UUID(), it.next().UUID())){
it.remove();
return true;
}
}
return false;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testHeartbeatTimeout() throws IOException, InterruptedException
{
Ctx ctx = ZMQ.createContext();
assertThat(ctx, notNullValue());
SocketBase server = prepServerSocket(ctx, true, false);
assertThat(server, notNullValue());
SocketBase monitor = ZMQ.socket(ctx, ZMQ.ZMQ_PAIR);
boolean rc = monitor.connect("inproc://monitor");
assertThat(rc, is(true));
String endpoint = (String) ZMQ.getSocketOptionExt(server, ZMQ.ZMQ_LAST_ENDPOINT);
assertThat(endpoint, notNullValue());
Socket socket = new Socket("127.0.0.1", TestUtils.port(endpoint));
// Mock a ZMTP 3 client so we can forcibly time out a connection
mockHandshake(socket);
// By now everything should report as connected
ZMQ.Event event = ZMQ.Event.read(monitor);
assertThat(event.event, is(ZMQ.ZMQ_EVENT_ACCEPTED));
// We should have been disconnected
event = ZMQ.Event.read(monitor);
assertThat(event.event, is(ZMQ.ZMQ_EVENT_DISCONNECTED));
socket.close();
ZMQ.close(monitor);
ZMQ.close(server);
ZMQ.term(ctx);
}
#location 35
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testHeartbeatTimeout() throws IOException, InterruptedException
{
testHeartbeatTimeout(false);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void destroy()
{
for (Socket socket : sockets) {
socket.setLinger(linger);
socket.close();
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain() && context != null) {
context.term();
}
synchronized (this) {
context = null;
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void destroy()
{
for (Socket socket : sockets) {
destroySocket(socket);
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain() && context != null) {
context.term();
context = null;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testLastEndpoint()
{
// Create the infrastructure
Ctx ctx = ZMQ.init(1);
assertThat(ctx, notNullValue());
SocketBase sb = ZMQ.socket(ctx, ZMQ.ZMQ_ROUTER);
assertThat(sb, notNullValue());
bindAndVerify(sb, "tcp://127.0.0.1:5560");
bindAndVerify(sb, "tcp://127.0.0.1:5561");
bindAndVerify(sb, "ipc:///tmp/testep");
sb.close();
ctx.terminate();
}
#location 16
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testLastEndpoint()
{
// Create the infrastructure
Ctx ctx = ZMQ.init(1);
assertThat(ctx, notNullValue());
SocketBase sb = ZMQ.socket(ctx, ZMQ.ZMQ_ROUTER);
assertThat(sb, notNullValue());
bindAndVerify(sb, "tcp://127.0.0.1:5560");
bindAndVerify(sb, "tcp://127.0.0.1:5561");
bindAndVerify(sb, "ipc:///tmp/testep" + UUID.randomUUID().toString());
sb.close();
ctx.terminate();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void destroy()
{
for (Socket socket : sockets) {
destroySocket(socket);
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain() && context != null) {
context.term();
context = null;
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void destroy()
{
for (Socket socket : sockets) {
destroySocket(socket);
}
sockets.clear();
// Only terminate context if we are on the main thread
if (isMain()) {
context.term();
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public ZMQ.Event make(SendEvent sender, int eventFilter)
{
Ctx ctx = new Ctx();
@SuppressWarnings("deprecation")
SocketBase s = ctx.createSocket(ZMQ.PUB);
@SuppressWarnings("deprecation")
SocketBase m = ctx.createSocket(ZMQ.PAIR);
m.connect("inproc://TestEventResolution");
s.monitor("inproc://TestEventResolution", eventFilter);
sender.send(s, "tcp://127.0.0.1:8000");
zmq.ZMQ.Event ev = zmq.ZMQ.Event.read(m);
return new ZMQ.Event(ev.event, ev.arg, ev.addr);
}
#location 12
#vulnerability type RESOURCE_LEAK
|
#fixed code
public ZMQ.Event make(SendEvent sender, int eventFilter)
{
try (ZMQ.Context zctx = new ZMQ.Context(1);
ZMQ.Socket s = zctx.socket(SocketType.PUB);
ZMQ.Socket m = zctx.socket(SocketType.PAIR)) {
s.monitor("inproc://TestEventResolution", eventFilter);
m.connect("inproc://TestEventResolution");
sender.send(s.base(), "tcp://127.0.0.1:8000");
return ZMQ.Event.recv(m);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public boolean send(Msg msg_, int flags_) {
// Drop the message if required. If we are at the end of the message
// switch back to non-dropping mode.
if (dropping) {
more = msg_.has_more();
dropping = more;
msg_.close ();
return true;
}
Pipe pipe = null;
while (active > start) {
pipe = pipes.get(current);
if (pipe.write (msg_))
break;
assert (!more);
current++;
start = current;
if (current == active)
current = start = active = 0;
}
// If there are no pipes we cannot send the message.
if (active == start) {
ZError.errno(ZError.EAGAIN);
return false;
}
// If it's final part of the message we can fluch it downstream and
// continue round-robinning (load balance).
more = msg_.has_more();
if (!more) {
pipe.flush ();
current++;
if (current == active)
current = start;
}
return true;
}
#location 36
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public boolean send(Msg msg_, int flags_) {
// Drop the message if required. If we are at the end of the message
// switch back to non-dropping mode.
if (dropping) {
more = msg_.has_more();
dropping = more;
msg_.close ();
return true;
}
while (active > 0) {
if (pipes.get(current).write (msg_))
break;
assert (!more);
active--;
if (current < active)
Utils.swap (pipes, current, active);
else
current = 0;
}
// If there are no pipes we cannot send the message.
if (active == 0) {
ZError.errno(ZError.EAGAIN);
return false;
}
// If it's final part of the message we can fluch it downstream and
// continue round-robinning (load balance).
more = msg_.has_more();
if (!more) {
pipes.get(current).flush ();
if (active > 1)
current = (current + 1) % active;
}
return true;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void test_streaming_changes() throws IOException {
HttpResponse httpResponse = ResponseOnFileStub.newInstance(200, "changes/changes_full.json");
StreamingChangesResult changes = new StreamingChangesResult(new ObjectMapper(),
httpResponse);
int i = 0;
for (DocumentChange documentChange : changes) {
Assert.assertEquals(++i, documentChange.getSequence());
}
Assert.assertEquals(5, changes.getLastSeq());
}
#location 10
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void test_streaming_changes() throws IOException {
HttpResponse httpResponse = ResponseOnFileStub.newInstance(200, "changes/changes_full.json");
StreamingChangesResult changes = new StreamingChangesResult(new ObjectMapper(),
httpResponse);
int i = 0;
for (DocumentChange documentChange : changes) {
Assert.assertEquals(++i, documentChange.getSequence());
}
Assert.assertEquals(5, changes.getLastSeq());
changes.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected ReadResponse doRead(ServerIdentity identity, ReadRequest request) {
LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
List<LwM2mObjectInstance> lwM2mObjectInstances = new ArrayList<>();
for (Entry<Integer, LwM2mInstanceEnabler> entry : instances.entrySet()) {
lwM2mObjectInstances.add(getLwM2mObjectInstance(entry.getKey(), entry.getValue(), identity, false));
}
return ReadResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances));
}
// Manage Instance case
LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId());
if (instance == null)
return ReadResponse.notFound();
if (path.getResourceId() == null) {
return ReadResponse.success(getLwM2mObjectInstance(path.getObjectInstanceId(), instance, identity, false));
}
// Manage Resource case
return instance.read(identity, path.getResourceId());
}
#location 20
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
protected ReadResponse doRead(ServerIdentity identity, ReadRequest request) {
LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
List<LwM2mObjectInstance> lwM2mObjectInstances = new ArrayList<>();
for (LwM2mInstanceEnabler instance : instances.values()) {
ReadResponse response = instance.read(identity);
if (response.isSuccess()) {
lwM2mObjectInstances.add((LwM2mObjectInstance) response.getContent());
}
}
return ReadResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances));
}
// Manage Instance case
LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId());
if (instance == null)
return ReadResponse.notFound();
if (path.getResourceId() == null) {
return instance.read(identity);
}
// Manage Resource case
return instance.read(identity, path.getResourceId());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void createRPKClient() {
ObjectsInitializer initializer = new ObjectsInitializer();
initializer.setInstancesForObject(LwM2mId.SECURITY,
Security.rpk(
"coaps://" + server.getSecureAddress().getHostString() + ":"
+ server.getSecureAddress().getPort(),
12345, clientPublicKey.getEncoded(), clientPrivateKey.getEncoded(),
serverPublicKey.getEncoded()));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
DtlsConnectorConfig.Builder config = new DtlsConnectorConfig.Builder().setAddress(clientAddress);
// TODO we should read the config from the security object
// TODO no way to provide a dynamic config with the current scandium API
config.setIdentity(clientPrivateKey, clientPublicKey);
CoapServer coapServer = new CoapServer();
coapServer.addEndpoint(new CoapEndpoint(new DTLSConnector(config.build()), NetworkConfig.getStandard()));
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void createRPKClient() {
ObjectsInitializer initializer = new ObjectsInitializer();
initializer.setInstancesForObject(LwM2mId.SECURITY,
Security.rpk(
"coaps://" + server.getSecuredAddress().getHostString() + ":"
+ server.getSecuredAddress().getPort(),
12345, clientPublicKey.getEncoded(), clientPrivateKey.getEncoded(),
serverPublicKey.getEncoded()));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
DtlsConnectorConfig.Builder config = new DtlsConnectorConfig.Builder().setAddress(clientAddress);
// TODO we should read the config from the security object
// TODO no way to provide a dynamic config with the current scandium API
config.setIdentity(clientPrivateKey, clientPublicKey);
CoapServer coapServer = new CoapServer();
coapServer.addEndpoint(new CoapEndpoint(new DTLSConnector(config.build()), NetworkConfig.getStandard()));
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@SuppressWarnings("unchecked")
private void loadFromFile() {
try {
File file = new File(filename);
if (file.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
bootstrapByEndpoint.putAll((Map<String, BootstrapConfig>) in.readObject());
}
}
} catch (Exception e) {
LOG.error("Could not load bootstrap infos from file", e);
}
}
#location 6
#vulnerability type RESOURCE_LEAK
|
#fixed code
@SuppressWarnings("unchecked")
private void loadFromFile() {
try {
File file = new File(filename);
if (file.exists()) {
try (InputStreamReader in = new InputStreamReader(new FileInputStream(file))) {
Map<String, BootstrapConfig> config = gson.fromJson(in, gsonType);
bootstrapByEndpoint.putAll(config);
}
} else {
// TODO temporary code for retro compatibility: remove it later.
if (DEFAULT_FILE.equals(filename)) {
file = new File("data/bootstrap.data");// old bootstrap configurations default filename
if (file.exists()) {
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(file))) {
bootstrapByEndpoint.putAll((Map<String, BootstrapConfig>) in.readObject());
}
}
}
}
} catch (Exception e) {
LOG.error("Could not load bootstrap infos from file", e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
if (nodeClass == LwM2mObject.class) {
List<LwM2mObjectInstance> instances = new ArrayList<>();
// is it an array of TLV resources?
if (tlvs.length > 0 && //
(tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) {
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel == null) {
LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object",
path.getObjectId());
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else if (!oModel.multiple) {
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else {
throw new CodecException(String
.format("Object instance TLV is mandatory for multiple instances object [path:%s]", path));
}
} else {
for (Tlv tlv : tlvs) {
if (tlv.getType() != TlvType.OBJECT_INSTANCE)
throw new CodecException(
String.format("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]",
tlv.getType().name(), path));
instances.add(parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(),
tlv.getIdentifier(), model));
}
}
return (T) new LwM2mObject(path.getObjectId(), instances);
}
// Object instance
else if (nodeClass == LwM2mObjectInstance.class) {
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException(String.format("Id conflict between path [%s] and instance TLV [%d]", path,
tlvs[0].getIdentifier()));
}
// object instance TLV
return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(),
model);
} else {
// array of TLV resources
// try to retrieve the instanceId from the path or the model
Integer instanceId = path.getObjectInstanceId();
if (instanceId == null) {
// single instance object?
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel != null && !oModel.multiple) {
instanceId = 0;
} else {
instanceId = LwM2mObjectInstance.UNDEFINED;
}
}
return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model);
}
}
// Resource
else if (nodeClass == LwM2mResource.class) {
if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) {
if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) {
throw new CodecException(String.format("Id conflict between path [%s] and resource TLV [%s]", path,
tlvs[0].getIdentifier()));
}
return (T) parseResourceTlv(tlvs[0], path.getObjectId(), path.getObjectInstanceId(), model);
} else {
Type expectedRscType = getResourceType(path, model);
return (T) LwM2mMultipleResource.newResource(path.getResourceId(),
parseTlvValues(tlvs, expectedRscType, path), expectedRscType);
}
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
}
#location 76
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
if (nodeClass == LwM2mObject.class) {
List<LwM2mObjectInstance> instances = new ArrayList<>();
// is it an array of TLV resources?
if (tlvs.length > 0 && //
(tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) {
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel == null) {
LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object",
path.getObjectId());
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else if (!oModel.multiple) {
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else {
throw new CodecException(String
.format("Object instance TLV is mandatory for multiple instances object [path:%s]", path));
}
} else {
for (Tlv tlv : tlvs) {
if (tlv.getType() != TlvType.OBJECT_INSTANCE)
throw new CodecException(
String.format("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]",
tlv.getType().name(), path));
instances.add(parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(),
tlv.getIdentifier(), model));
}
}
return (T) new LwM2mObject(path.getObjectId(), instances);
}
// Object instance
else if (nodeClass == LwM2mObjectInstance.class) {
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException(String.format("Id conflict between path [%s] and instance TLV [%d]", path,
tlvs[0].getIdentifier()));
}
// object instance TLV
return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(),
model);
} else {
// array of TLV resources
// try to retrieve the instanceId from the path or the model
Integer instanceId = path.getObjectInstanceId();
if (instanceId == null) {
// single instance object?
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel != null && !oModel.multiple) {
instanceId = 0;
} else {
instanceId = LwM2mObjectInstance.UNDEFINED;
}
}
return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model);
}
}
// Resource
else if (nodeClass == LwM2mResource.class) {
ResourceModel resourceModel = model.getResourceModel(path.getObjectId(), path.getResourceId());
if (tlvs.length == 0 && resourceModel != null && !resourceModel.multiple) {
// If there is no TlV value and we know that this resource is a single resource we raise an exception
// else we consider this is a multi-instance resource
throw new CodecException(String.format("TLV payload is mandatory for single resource %s", path));
} else if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) {
if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) {
throw new CodecException(String.format("Id conflict between path [%s] and resource TLV [%s]", path,
tlvs[0].getIdentifier()));
}
return (T) parseResourceTlv(tlvs[0], path.getObjectId(), path.getObjectInstanceId(), model);
} else {
Type expectedRscType = getResourceType(path, model);
return (T) LwM2mMultipleResource.newResource(path.getResourceId(),
parseTlvValues(tlvs, expectedRscType, path), expectedRscType);
}
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void visit(final UpdateRequest request) {
coapRequest = Request.newPut();
buildRequestSettings();
coapRequest.getOptions().setUriPath(request.getRegistrationId());
Long lifetime = request.getLifeTimeInSec();
if (lifetime != null)
coapRequest.getOptions().addUriQuery("lt=" + lifetime);
String smsNumber = request.getSmsNumber();
if (smsNumber != null)
coapRequest.getOptions().addUriQuery("sms=" + smsNumber);
BindingMode bindingMode = request.getBindingMode();
if (bindingMode != null)
coapRequest.getOptions().addUriQuery("b=" + bindingMode.toString());
LinkObject[] linkObjects = request.getObjectLinks();
if (linkObjects == null)
coapRequest.setPayload(LinkObject.serialyse(linkObjects));
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void visit(final UpdateRequest request) {
coapRequest = Request.newPut();
buildRequestSettings();
coapRequest.getOptions().setUriPath(request.getRegistrationId());
Long lifetime = request.getLifeTimeInSec();
if (lifetime != null)
coapRequest.getOptions().addUriQuery("lt=" + lifetime);
String smsNumber = request.getSmsNumber();
if (smsNumber != null)
coapRequest.getOptions().addUriQuery("sms=" + smsNumber);
BindingMode bindingMode = request.getBindingMode();
if (bindingMode != null)
coapRequest.getOptions().addUriQuery("b=" + bindingMode.toString());
LinkObject[] linkObjects = request.getObjectLinks();
if (linkObjects != null)
coapRequest.setPayload(LinkObject.serialyse(linkObjects));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void createPSKClient() {
ObjectsInitializer initializer = new ObjectsInitializer();
initializer.setInstancesForObject(LwM2mId.SECURITY,
Security.psk(
"coaps://" + server.getSecureAddress().getHostString() + ":"
+ server.getSecureAddress().getPort(),
12345, GOOD_PSK_ID.getBytes(StandardCharsets.UTF_8), GOOD_PSK_KEY));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void createPSKClient() {
ObjectsInitializer initializer = new ObjectsInitializer();
initializer.setInstancesForObject(LwM2mId.SECURITY,
Security.psk(
"coaps://" + server.getSecuredAddress().getHostString() + ":"
+ server.getSecuredAddress().getPort(),
12345, GOOD_PSK_ID.getBytes(StandardCharsets.UTF_8), GOOD_PSK_KEY));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected void fireResourcesChanged(int instanceid, int... resourceIds) {
if (listener != null) {
listener.resourceChanged(this, instanceid, resourceIds);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
protected void fireResourcesChanged(int instanceid, int... resourceIds) {
transactionalListener.resourceChanged(this, instanceid, resourceIds);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
if (nodeClass == LwM2mObject.class) {
List<LwM2mObjectInstance> instances = new ArrayList<>();
// is it an array of TLV resources?
if (tlvs.length > 0 && //
(tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) {
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel == null) {
LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object",
path.getObjectId());
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else if (!oModel.multiple) {
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else {
throw new CodecException(String
.format("Object instance TLV is mandatory for multiple instances object [path:%s]", path));
}
} else {
for (Tlv tlv : tlvs) {
if (tlv.getType() != TlvType.OBJECT_INSTANCE)
throw new CodecException(
String.format("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]",
tlv.getType().name(), path));
instances.add(parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(),
tlv.getIdentifier(), model));
}
}
return (T) new LwM2mObject(path.getObjectId(), instances);
}
// Object instance
else if (nodeClass == LwM2mObjectInstance.class) {
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException(String.format("Id conflict between path [%s] and instance TLV [%d]", path,
tlvs[0].getIdentifier()));
}
// object instance TLV
return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(),
model);
} else {
// array of TLV resources
// try to retrieve the instanceId from the path or the model
Integer instanceId = path.getObjectInstanceId();
if (instanceId == null) {
// single instance object?
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel != null && !oModel.multiple) {
instanceId = 0;
} else {
instanceId = LwM2mObjectInstance.UNDEFINED;
}
}
return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model);
}
}
// Resource
else if (nodeClass == LwM2mResource.class) {
if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) {
if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) {
throw new CodecException(String.format("Id conflict between path [%s] and resource TLV [%s]", path,
tlvs[0].getIdentifier()));
}
return (T) parseResourceTlv(tlvs[0], path.getObjectId(), path.getObjectInstanceId(), model);
} else {
Type expectedRscType = getResourceType(path, model);
return (T) LwM2mMultipleResource.newResource(path.getResourceId(),
parseTlvValues(tlvs, expectedRscType, path), expectedRscType);
}
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
}
#location 49
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
if (nodeClass == LwM2mObject.class) {
List<LwM2mObjectInstance> instances = new ArrayList<>();
// is it an array of TLV resources?
if (tlvs.length > 0 && //
(tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) {
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel == null) {
LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object",
path.getObjectId());
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else if (!oModel.multiple) {
instances.add(parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else {
throw new CodecException(String
.format("Object instance TLV is mandatory for multiple instances object [path:%s]", path));
}
} else {
for (Tlv tlv : tlvs) {
if (tlv.getType() != TlvType.OBJECT_INSTANCE)
throw new CodecException(
String.format("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]",
tlv.getType().name(), path));
instances.add(parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(),
tlv.getIdentifier(), model));
}
}
return (T) new LwM2mObject(path.getObjectId(), instances);
}
// Object instance
else if (nodeClass == LwM2mObjectInstance.class) {
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException(String.format("Id conflict between path [%s] and instance TLV [%d]", path,
tlvs[0].getIdentifier()));
}
// object instance TLV
return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(),
model);
} else {
// array of TLV resources
// try to retrieve the instanceId from the path or the model
Integer instanceId = path.getObjectInstanceId();
if (instanceId == null) {
// single instance object?
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel != null && !oModel.multiple) {
instanceId = 0;
} else {
instanceId = LwM2mObjectInstance.UNDEFINED;
}
}
return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model);
}
}
// Resource
else if (nodeClass == LwM2mResource.class) {
ResourceModel resourceModel = model.getResourceModel(path.getObjectId(), path.getResourceId());
if (tlvs.length == 0 && resourceModel != null && !resourceModel.multiple) {
// If there is no TlV value and we know that this resource is a single resource we raise an exception
// else we consider this is a multi-instance resource
throw new CodecException(String.format("TLV payload is mandatory for single resource %s", path));
} else if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) {
if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) {
throw new CodecException(String.format("Id conflict between path [%s] and resource TLV [%s]", path,
tlvs[0].getIdentifier()));
}
return (T) parseResourceTlv(tlvs[0], path.getObjectId(), path.getObjectInstanceId(), model);
} else {
Type expectedRscType = getResourceType(path, model);
return (T) LwM2mMultipleResource.newResource(path.getResourceId(),
parseTlvValues(tlvs, expectedRscType, path), expectedRscType);
}
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void register_with_invalid_request() throws InterruptedException, IOException {
// Check registration
helper.assertClientNotRegisterered();
// create a register request without the list of supported object
Request coapRequest = new Request(Code.POST);
coapRequest.setDestination(helper.server.getNonSecureAddress().getAddress());
coapRequest.setDestinationPort(helper.server.getNonSecureAddress().getPort());
coapRequest.getOptions().setContentFormat(ContentFormat.LINK.getCode());
coapRequest.getOptions().addUriPath("rd");
coapRequest.getOptions().addUriQuery("ep=" + helper.currentEndpointIdentifier);
// send request
CoapEndpoint coapEndpoint = new CoapEndpoint(new InetSocketAddress(0));
coapEndpoint.start();
coapEndpoint.sendRequest(coapRequest);
// check response
Response response = coapRequest.waitForResponse(1000);
assertEquals(response.getCode(), org.eclipse.californium.core.coap.CoAP.ResponseCode.BAD_REQUEST);
coapEndpoint.stop();
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void register_with_invalid_request() throws InterruptedException, IOException {
// Check registration
helper.assertClientNotRegisterered();
// create a register request without the list of supported object
Request coapRequest = new Request(Code.POST);
coapRequest.setDestination(helper.server.getUnsecuredAddress().getAddress());
coapRequest.setDestinationPort(helper.server.getUnsecuredAddress().getPort());
coapRequest.getOptions().setContentFormat(ContentFormat.LINK.getCode());
coapRequest.getOptions().addUriPath("rd");
coapRequest.getOptions().addUriQuery("ep=" + helper.currentEndpointIdentifier);
// send request
CoapEndpoint coapEndpoint = new CoapEndpoint(new InetSocketAddress(0));
coapEndpoint.start();
coapEndpoint.sendRequest(coapRequest);
// check response
Response response = coapRequest.waitForResponse(1000);
assertEquals(response.getCode(), org.eclipse.californium.core.coap.CoAP.ResponseCode.BAD_REQUEST);
coapEndpoint.stop();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void register_with_invalid_request() throws InterruptedException, IOException {
// Check registration
helper.assertClientNotRegisterered();
// create a register request without the list of supported object
Request coapRequest = new Request(Code.POST);
coapRequest.setDestination(helper.server.getUnsecuredAddress().getAddress());
coapRequest.setDestinationPort(helper.server.getUnsecuredAddress().getPort());
coapRequest.getOptions().setContentFormat(ContentFormat.LINK.getCode());
coapRequest.getOptions().addUriPath("rd");
coapRequest.getOptions().addUriQuery("ep=" + helper.currentEndpointIdentifier);
// send request
CoapEndpoint coapEndpoint = new CoapEndpoint(new InetSocketAddress(0));
coapEndpoint.start();
coapEndpoint.sendRequest(coapRequest);
// check response
Response response = coapRequest.waitForResponse(1000);
assertEquals(response.getCode(), org.eclipse.californium.core.coap.CoAP.ResponseCode.BAD_REQUEST);
coapEndpoint.stop();
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void register_with_invalid_request() throws InterruptedException, IOException {
// Check registration
helper.assertClientNotRegisterered();
// create a register request without the list of supported object
Request coapRequest = new Request(Code.POST);
coapRequest.setDestinationContext(new AddressEndpointContext(helper.server.getUnsecuredAddress()));
coapRequest.getOptions().setContentFormat(ContentFormat.LINK.getCode());
coapRequest.getOptions().addUriPath("rd");
coapRequest.getOptions().addUriQuery("ep=" + helper.currentEndpointIdentifier);
// send request
CoapEndpoint coapEndpoint = new CoapEndpoint(new InetSocketAddress(0));
coapEndpoint.start();
coapEndpoint.sendRequest(coapRequest);
// check response
Response response = coapRequest.waitForResponse(1000);
assertEquals(response.getCode(), org.eclipse.californium.core.coap.CoAP.ResponseCode.BAD_REQUEST);
coapEndpoint.stop();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void createX509CertClient(PrivateKey privatekey, Certificate[] trustedCertificates) {
ObjectsInitializer initializer = new ObjectsInitializer();
// TODO security instance with certificate info
initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec(
"coaps://" + server.getSecureAddress().getHostString() + ":" + server.getSecureAddress().getPort(),
12345));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
DtlsConnectorConfig.Builder config = new DtlsConnectorConfig.Builder().setAddress(clientAddress);
// TODO we should read the config from the security object
config.setIdentity(privatekey, clientX509CertChain, false);
config.setTrustStore(trustedCertificates);
CoapServer coapServer = new CoapServer();
coapServer.addEndpoint(new CoapEndpoint(new DTLSConnector(config.build()), NetworkConfig.getStandard()));
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void createX509CertClient(PrivateKey privatekey, Certificate[] trustedCertificates) {
ObjectsInitializer initializer = new ObjectsInitializer();
// TODO security instance with certificate info
initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec(
"coaps://" + server.getSecuredAddress().getHostString() + ":" + server.getSecuredAddress().getPort(),
12345));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
DtlsConnectorConfig.Builder config = new DtlsConnectorConfig.Builder().setAddress(clientAddress);
// TODO we should read the config from the security object
config.setIdentity(privatekey, clientX509CertChain, false);
config.setTrustStore(trustedCertificates);
CoapServer coapServer = new CoapServer();
coapServer.addEndpoint(new CoapEndpoint(new DTLSConnector(config.build()), NetworkConfig.getStandard()));
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected BootstrapWriteResponse doWrite(ServerIdentity identity, BootstrapWriteRequest request) {
LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
for (LwM2mObjectInstance instanceNode : ((LwM2mObject) request.getNode()).getInstances().values()) {
LwM2mInstanceEnabler instanceEnabler = instances.get(instanceNode.getId());
if (instanceEnabler == null) {
doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode));
} else {
doWrite(identity, new WriteRequest(Mode.REPLACE, path.getObjectId(), path.getObjectInstanceId(),
instanceNode.getResources().values()));
}
}
return BootstrapWriteResponse.success();
}
// Manage Instance case
if (path.isObjectInstance()) {
LwM2mObjectInstance instanceNode = (LwM2mObjectInstance) request.getNode();
LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId());
if (instanceEnabler == null) {
doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode));
} else {
doWrite(identity, new WriteRequest(Mode.REPLACE, request.getContentFormat(), path.getObjectId(),
path.getObjectInstanceId(), instanceNode.getResources().values()));
}
return BootstrapWriteResponse.success();
}
// Manage resource case
LwM2mResource resource = (LwM2mResource) request.getNode();
LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId());
if (instanceEnabler == null) {
doCreate(identity, new CreateRequest(path.getObjectId(),
new LwM2mObjectInstance(path.getObjectInstanceId(), resource)));
} else {
instanceEnabler.write(identity, path.getResourceId(), resource);
}
return BootstrapWriteResponse.success();
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
protected BootstrapWriteResponse doWrite(ServerIdentity identity, BootstrapWriteRequest request) {
LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
for (LwM2mObjectInstance instanceNode : ((LwM2mObject) request.getNode()).getInstances().values()) {
LwM2mInstanceEnabler instanceEnabler = instances.get(instanceNode.getId());
if (instanceEnabler == null) {
doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode));
} else {
doWrite(identity, new WriteRequest(Mode.REPLACE, path.getObjectId(), instanceEnabler.getId(),
instanceNode.getResources().values()));
}
}
return BootstrapWriteResponse.success();
}
// Manage Instance case
if (path.isObjectInstance()) {
LwM2mObjectInstance instanceNode = (LwM2mObjectInstance) request.getNode();
LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId());
if (instanceEnabler == null) {
doCreate(identity, new CreateRequest(path.getObjectId(), instanceNode));
} else {
doWrite(identity, new WriteRequest(Mode.REPLACE, request.getContentFormat(), path.getObjectId(),
path.getObjectInstanceId(), instanceNode.getResources().values()));
}
return BootstrapWriteResponse.success();
}
// Manage resource case
LwM2mResource resource = (LwM2mResource) request.getNode();
LwM2mInstanceEnabler instanceEnabler = instances.get(path.getObjectInstanceId());
if (instanceEnabler == null) {
doCreate(identity, new CreateRequest(path.getObjectId(),
new LwM2mObjectInstance(path.getObjectInstanceId(), resource)));
} else {
instanceEnabler.write(identity, path.getResourceId(), resource);
}
return BootstrapWriteResponse.success();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected ObserveResponse doObserve(final ServerIdentity identity, final ObserveRequest request) {
final LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
List<LwM2mObjectInstance> lwM2mObjectInstances = new ArrayList<>();
for (Entry<Integer, LwM2mInstanceEnabler> entry : instances.entrySet()) {
lwM2mObjectInstances.add(getLwM2mObjectInstance(entry.getKey(), entry.getValue(), identity, true));
}
return ObserveResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances));
}
// Manage Instance case
final LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId());
if (instance == null)
return ObserveResponse.notFound();
if (path.getResourceId() == null) {
return ObserveResponse
.success(getLwM2mObjectInstance(path.getObjectInstanceId(), instance, identity, true));
}
// Manage Resource case
return instance.observe(identity, path.getResourceId());
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
protected ObserveResponse doObserve(final ServerIdentity identity, final ObserveRequest request) {
final LwM2mPath path = request.getPath();
// Manage Object case
if (path.isObject()) {
List<LwM2mObjectInstance> lwM2mObjectInstances = new ArrayList<>();
for (LwM2mInstanceEnabler instance : instances.values()) {
ReadResponse response = instance.observe(identity);
if (response.isSuccess()) {
lwM2mObjectInstances.add((LwM2mObjectInstance) response.getContent());
}
}
return ObserveResponse.success(new LwM2mObject(getId(), lwM2mObjectInstances));
}
// Manage Instance case
final LwM2mInstanceEnabler instance = instances.get(path.getObjectInstanceId());
if (instance == null)
return ObserveResponse.notFound();
if (path.getResourceId() == null) {
return instance.observe(identity);
}
// Manage Resource case
return instance.observe(identity, path.getResourceId());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void remove(byte[] token) {
try (Jedis j = pool.getResource()) {
byte[] tokenKey = toKey(OBS_TKN, token);
// fetch the observation by token
byte[] serializedObs = j.get(tokenKey);
if (serializedObs == null)
return;
org.eclipse.californium.core.observe.Observation obs = deserializeObs(serializedObs);
String registrationId = obs.getRequest().getUserContext().get(CoapRequestBuilder.CTX_REGID);
Registration registration = getRegistration(j, registrationId);
String endpoint = registration.getEndpoint();
byte[] lockValue = null;
byte[] lockKey = toKey(LOCK_EP, endpoint);
try {
lockValue = RedisLock.acquire(j, lockKey);
unsafeRemoveObservation(j, registrationId, token);
} finally {
RedisLock.release(j, lockKey, lockValue);
}
}
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void remove(byte[] token) {
try (Jedis j = pool.getResource()) {
byte[] tokenKey = toKey(OBS_TKN, token);
// fetch the observation by token
byte[] serializedObs = j.get(tokenKey);
if (serializedObs == null)
return;
org.eclipse.californium.core.observe.Observation obs = deserializeObs(serializedObs);
String registrationId = obs.getRequest().getUserContext().get(CoapRequestBuilder.CTX_REGID);
Registration registration = getRegistration(j, registrationId);
if (registration == null) {
LOG.warn("Unable to remove observation {}, registration {} does not exist anymore", obs.getRequest(),
registrationId);
return;
}
String endpoint = registration.getEndpoint();
byte[] lockValue = null;
byte[] lockKey = toKey(LOCK_EP, endpoint);
try {
lockValue = RedisLock.acquire(j, lockKey);
unsafeRemoveObservation(j, registrationId, token);
} finally {
RedisLock.release(j, lockKey, lockValue);
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void handleUpdate(CoapExchange exchange, Request request, String registrationId) {
// Get identity
Identity sender = extractIdentity(exchange);
// Create LwM2m request from CoAP request
Long lifetime = null;
String smsNumber = null;
BindingMode binding = null;
Link[] objectLinks = null;
for (String param : request.getOptions().getUriQuery()) {
if (param.startsWith(QUERY_PARAM_LIFETIME)) {
lifetime = Long.valueOf(param.substring(3));
} else if (param.startsWith(QUERY_PARAM_SMS)) {
smsNumber = param.substring(4);
} else if (param.startsWith(QUERY_PARAM_BINDING_MODE)) {
binding = BindingMode.valueOf(param.substring(2));
}
}
if (request.getPayload() != null && request.getPayload().length > 0) {
objectLinks = Link.parse(request.getPayload());
}
UpdateRequest updateRequest = new UpdateRequest(registrationId, lifetime, smsNumber, binding, objectLinks);
// Handle request
UpdateResponse updateResponse = registrationHandler.update(sender, updateRequest);
// Create CoAP Response from LwM2m request
exchange.respond(fromLwM2mCode(updateResponse.getCode()), updateResponse.getErrorMessage());
}
#location 25
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void handleUpdate(CoapExchange exchange, Request request, String registrationId) {
// Get identity
Identity sender = extractIdentity(exchange);
// Create LwM2m request from CoAP request
Long lifetime = null;
String smsNumber = null;
BindingMode binding = null;
Link[] objectLinks = null;
for (String param : request.getOptions().getUriQuery()) {
if (param.startsWith(QUERY_PARAM_LIFETIME)) {
lifetime = Long.valueOf(param.substring(3));
} else if (param.startsWith(QUERY_PARAM_SMS)) {
smsNumber = param.substring(4);
} else if (param.startsWith(QUERY_PARAM_BINDING_MODE)) {
binding = BindingMode.valueOf(param.substring(2));
}
}
if (request.getPayload() != null && request.getPayload().length > 0) {
objectLinks = Link.parse(request.getPayload());
}
UpdateRequest updateRequest = new UpdateRequest(registrationId, lifetime, smsNumber, binding, objectLinks);
// Handle request
final SendableResponse<UpdateResponse> sendableResponse = registrationHandler.update(sender, updateRequest);
UpdateResponse updateResponse = sendableResponse.getResponse();
// Create CoAP Response from LwM2m request
exchange.respond(fromLwM2mCode(updateResponse.getCode()), updateResponse.getErrorMessage());
sendableResponse.sent();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected void beginTransaction() {
if (listener != null) {
listener.beginTransaction();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
protected void beginTransaction() {
transactionalListener.beginTransaction();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void createRPKClient() {
ObjectsInitializer initializer = new ObjectsInitializer();
initializer.setInstancesForObject(LwM2mId.SECURITY,
Security.rpk(
"coaps://" + server.getSecuredAddress().getHostString() + ":"
+ server.getSecuredAddress().getPort(),
12345, clientPublicKey.getEncoded(), clientPrivateKey.getEncoded(),
serverPublicKey.getEncoded()));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.add(initializer.create(2));
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
DtlsConnectorConfig.Builder config = new DtlsConnectorConfig.Builder().setAddress(clientAddress);
// TODO we should read the config from the security object
// TODO no way to provide a dynamic config with the current scandium API
config.setIdentity(clientPrivateKey, clientPublicKey);
CoapServer coapServer = new CoapServer();
CoapEndpoint.CoapEndpointBuilder coapBuilder = new CoapEndpoint.CoapEndpointBuilder();
coapBuilder.setConnector(new DTLSConnector(config.build()));
coapBuilder.setNetworkConfig(new NetworkConfig());
coapServer.addEndpoint(coapBuilder.build());
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
client = builder.build();
setupClientMonitoring();
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void createRPKClient() {
createRPKClient(false);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void createClient() {
// Create Security Object (with bootstrap server only)
String bsUrl = "coap://" + bootstrapServer.getNonSecureAddress().getHostString() + ":"
+ bootstrapServer.getNonSecureAddress().getPort();
Security security = new Security(bsUrl, true, 3, new byte[0], new byte[0], new byte[0], 12345);
createClient(security);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void createClient() {
// Create Security Object (with bootstrap server only)
String bsUrl = "coap://" + bootstrapServer.getUnsecuredAddress().getHostString() + ":"
+ bootstrapServer.getUnsecuredAddress().getPort();
Security security = new Security(bsUrl, true, 3, new byte[0], new byte[0], new byte[0], 12345);
createClient(security);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected void fireInstancesAdded(int... instanceIds) {
if (listener != null) {
listener.objectInstancesAdded(this, instanceIds);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
protected void fireInstancesAdded(int... instanceIds) {
transactionalListener.objectInstancesAdded(this, instanceIds);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static Registration deserialize(JsonObject jObj) {
Registration.Builder b = new Registration.Builder(jObj.getString("regId", null), jObj.getString("ep", null),
new InetSocketAddress(jObj.getString("address", null), jObj.getInt("port", 0)).getAddress(),
jObj.getInt("port", 0),
new InetSocketAddress(jObj.getString("regAddr", null), jObj.getInt("regPort", 0)));
b.bindingMode(BindingMode.valueOf(jObj.getString("bnd", null)));
b.lastUpdate(new Date(jObj.getLong("lastUp", 0)));
b.lifeTimeInSec(jObj.getLong("lt", 0));
b.lwM2mVersion(jObj.getString("ver", "1.0"));
b.registrationDate(new Date(jObj.getLong("regDate", 0)));
if (jObj.get("sms") != null) {
b.smsNumber(jObj.getString("sms", ""));
}
JsonArray links = (JsonArray) jObj.get("objLink");
Link[] linkObjs = new Link[links.size()];
for (int i = 0; i < links.size(); i++) {
JsonObject ol = (JsonObject) links.get(i);
Map<String, Object> attMap = new HashMap<>();
JsonObject att = (JsonObject) ol.get("at");
for (String k : att.names()) {
JsonValue jsonValue = att.get(k);
if (jsonValue.isNumber()) {
attMap.put(k, jsonValue.asInt());
} else {
attMap.put(k, jsonValue.asString());
}
}
Link o = new Link(ol.getString("url", null), attMap);
linkObjs[i] = o;
}
b.objectLinks(linkObjs);
Map<String, String> addAttr = new HashMap<>();
JsonObject o = (JsonObject) jObj.get("addAttr");
for (String k : o.names()) {
addAttr.put(k, o.getString(k, ""));
}
b.additionalRegistrationAttributes(addAttr);
return b.build();
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static Registration deserialize(JsonObject jObj) {
Registration.Builder b = new Registration.Builder(jObj.getString("regId", null), jObj.getString("ep", null),
IdentitySerDes.deserialize(jObj.get("identity").asObject()),
new InetSocketAddress(jObj.getString("regAddr", null), jObj.getInt("regPort", 0)));
b.bindingMode(BindingMode.valueOf(jObj.getString("bnd", null)));
b.lastUpdate(new Date(jObj.getLong("lastUp", 0)));
b.lifeTimeInSec(jObj.getLong("lt", 0));
b.lwM2mVersion(jObj.getString("ver", "1.0"));
b.registrationDate(new Date(jObj.getLong("regDate", 0)));
if (jObj.get("sms") != null) {
b.smsNumber(jObj.getString("sms", ""));
}
JsonArray links = (JsonArray) jObj.get("objLink");
Link[] linkObjs = new Link[links.size()];
for (int i = 0; i < links.size(); i++) {
JsonObject ol = (JsonObject) links.get(i);
Map<String, Object> attMap = new HashMap<>();
JsonObject att = (JsonObject) ol.get("at");
for (String k : att.names()) {
JsonValue jsonValue = att.get(k);
if (jsonValue.isNumber()) {
attMap.put(k, jsonValue.asInt());
} else {
attMap.put(k, jsonValue.asString());
}
}
Link o = new Link(ol.getString("url", null), attMap);
linkObjs[i] = o;
}
b.objectLinks(linkObjs);
Map<String, String> addAttr = new HashMap<>();
JsonObject o = (JsonObject) jObj.get("addAttr");
for (String k : o.names()) {
addAttr.put(k, o.getString(k, ""));
}
b.additionalRegistrationAttributes(addAttr);
return b.build();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void sendNotification(byte[] payload, Response firstCoapResponse, int contentFormat) {
// encode and send it
try (DatagramSocket clientSocket = new DatagramSocket()) {
// create observe response
Response response = new Response(org.eclipse.californium.core.coap.CoAP.ResponseCode.CONTENT);
response.setType(Type.NON);
response.setPayload(payload);
response.setMID(firstCoapResponse.getMID() + 1);
response.setToken(firstCoapResponse.getToken());
OptionSet options = new OptionSet().setContentFormat(contentFormat)
.setObserve(firstCoapResponse.getOptions().getObserve() + 1);
response.setOptions(options);
// serialize response
UdpDataSerializer serializer = new UdpDataSerializer();
RawData data = serializer.serializeResponse(response);
// send it
clientSocket.send(new DatagramPacket(data.bytes, data.bytes.length,
helper.server.getNonSecureAddress().getAddress(), helper.server.getNonSecureAddress().getPort()));
} catch (IOException e) {
throw new AssertionError("Error while timestamped notification", e);
}
}
#location 22
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void sendNotification(byte[] payload, Response firstCoapResponse, int contentFormat) {
// encode and send it
try (DatagramSocket clientSocket = new DatagramSocket()) {
// create observe response
Response response = new Response(org.eclipse.californium.core.coap.CoAP.ResponseCode.CONTENT);
response.setType(Type.NON);
response.setPayload(payload);
response.setMID(firstCoapResponse.getMID() + 1);
response.setToken(firstCoapResponse.getToken());
OptionSet options = new OptionSet().setContentFormat(contentFormat)
.setObserve(firstCoapResponse.getOptions().getObserve() + 1);
response.setOptions(options);
// serialize response
UdpDataSerializer serializer = new UdpDataSerializer();
RawData data = serializer.serializeResponse(response);
// send it
clientSocket.send(new DatagramPacket(data.bytes, data.bytes.length,
helper.server.getUnsecuredAddress().getAddress(), helper.server.getUnsecuredAddress().getPort()));
} catch (IOException e) {
throw new AssertionError("Error while timestamped notification", e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected void fireInstancesRemoved(int... instanceIds) {
if (listener != null) {
listener.objectInstancesRemoved(this, instanceIds);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
protected void fireInstancesRemoved(int... instanceIds) {
transactionalListener.objectInstancesRemoved(this, instanceIds);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void createPSKClient() {
ObjectsInitializer initializer = new ObjectsInitializer();
initializer.setInstancesForObject(LwM2mId.SECURITY,
Security.psk(
"coaps://" + server.getSecuredAddress().getHostString() + ":"
+ server.getSecuredAddress().getPort(),
12345, GOOD_PSK_ID.getBytes(StandardCharsets.UTF_8), GOOD_PSK_KEY));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U"));
initializer.setDummyInstancesForObject(LwM2mId.ACCESS_CONTROL);
List<LwM2mObjectEnabler> objects = initializer.createAll();
InetSocketAddress clientAddress = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
LeshanClientBuilder builder = new LeshanClientBuilder(getCurrentEndpoint());
builder.setLocalAddress(clientAddress.getHostString(), clientAddress.getPort());
builder.setObjects(objects);
// set an editable PSK store for tests
builder.setEndpointFactory(new EndpointFactory() {
@Override
public CoapEndpoint createUnsecuredEndpoint(InetSocketAddress address, NetworkConfig coapConfig,
ObservationStore store) {
CoapEndpoint.Builder builder = new CoapEndpoint.Builder();
builder.setInetSocketAddress(address);
builder.setNetworkConfig(coapConfig);
return builder.build();
}
@Override
public CoapEndpoint createSecuredEndpoint(DtlsConnectorConfig dtlsConfig, NetworkConfig coapConfig,
ObservationStore store) {
CoapEndpoint.Builder builder = new CoapEndpoint.Builder();
Builder dtlsConfigBuilder = new Builder(dtlsConfig);
if (dtlsConfig.getPskStore() != null) {
PskPublicInformation identity = dtlsConfig.getPskStore().getIdentity(null);
SecretKey key = dtlsConfig.getPskStore().getKey(identity);
singlePSKStore = new SinglePSKStore(identity, key);
dtlsConfigBuilder.setPskStore(singlePSKStore);
}
builder.setConnector(new DTLSConnector(dtlsConfigBuilder.build()));
builder.setNetworkConfig(coapConfig);
return builder.build();
}
});
// create client;
client = builder.build();
setupClientMonitoring();
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void createPSKClient() {
createPSKClient(false);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void can_observe_timestamped_resource() throws InterruptedException {
TestObservationListener listener = new TestObservationListener();
helper.server.getObservationService().addListener(listener);
// observe device timezone
ObserveResponse observeResponse = helper.server.send(helper.getCurrentRegistration(),
new ObserveRequest(3, 0, 15));
assertEquals(ResponseCode.CONTENT, observeResponse.getCode());
assertNotNull(observeResponse.getCoapResponse());
assertThat(observeResponse.getCoapResponse(), is(instanceOf(Response.class)));
// an observation response should have been sent
Observation observation = observeResponse.getObservation();
assertEquals("/3/0/15", observation.getPath().toString());
assertEquals(helper.getCurrentRegistration().getId(), observation.getRegistrationId());
// *** HACK send time-stamped notification as Leshan client does not support it *** //
// create time-stamped nodes
TimestampedLwM2mNode mostRecentNode = new TimestampedLwM2mNode(System.currentTimeMillis(),
LwM2mSingleResource.newStringResource(15, "Paris"));
List<TimestampedLwM2mNode> timestampedNodes = new ArrayList<>();
timestampedNodes.add(mostRecentNode);
timestampedNodes.add(new TimestampedLwM2mNode(mostRecentNode.getTimestamp() - 2,
LwM2mSingleResource.newStringResource(15, "Londres")));
byte[] payload = LwM2mNodeJsonEncoder.encodeTimestampedData(timestampedNodes, new LwM2mPath("/3/0/15"),
new LwM2mModel(helper.createObjectModels()));
Response firstCoapResponse = (Response) observeResponse.getCoapResponse();
sendNotification(payload, firstCoapResponse, ContentFormat.JSON_CODE);
// *** Hack End *** //
// verify result
listener.waitForNotification(2000);
assertTrue(listener.receivedNotify().get());
assertEquals(mostRecentNode.getNode(), listener.getResponse().getContent());
assertEquals(timestampedNodes, listener.getResponse().getTimestampedLwM2mNode());
assertNotNull(listener.getResponse().getCoapResponse());
assertThat(listener.getResponse().getCoapResponse(), is(instanceOf(Response.class)));
}
#location 35
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void can_observe_timestamped_resource() throws InterruptedException {
TestObservationListener listener = new TestObservationListener();
helper.server.getObservationService().addListener(listener);
// observe device timezone
ObserveResponse observeResponse = helper.server.send(helper.getCurrentRegistration(),
new ObserveRequest(3, 0, 15));
assertEquals(ResponseCode.CONTENT, observeResponse.getCode());
assertNotNull(observeResponse.getCoapResponse());
assertThat(observeResponse.getCoapResponse(), is(instanceOf(Response.class)));
// an observation response should have been sent
Observation observation = observeResponse.getObservation();
assertEquals("/3/0/15", observation.getPath().toString());
assertEquals(helper.getCurrentRegistration().getId(), observation.getRegistrationId());
// *** HACK send time-stamped notification as Leshan client does not support it *** //
// create time-stamped nodes
TimestampedLwM2mNode mostRecentNode = new TimestampedLwM2mNode(System.currentTimeMillis(),
LwM2mSingleResource.newStringResource(15, "Paris"));
List<TimestampedLwM2mNode> timestampedNodes = new ArrayList<>();
timestampedNodes.add(mostRecentNode);
timestampedNodes.add(new TimestampedLwM2mNode(mostRecentNode.getTimestamp() - 2,
LwM2mSingleResource.newStringResource(15, "Londres")));
byte[] payload = LwM2mNodeJsonEncoder.encodeTimestampedData(timestampedNodes, new LwM2mPath("/3/0/15"),
new LwM2mModel(helper.createObjectModels()), new DefaultLwM2mValueConverter());
Response firstCoapResponse = (Response) observeResponse.getCoapResponse();
sendNotification(payload, firstCoapResponse, ContentFormat.JSON_CODE);
// *** Hack End *** //
// verify result
listener.waitForNotification(2000);
assertTrue(listener.receivedNotify().get());
assertEquals(mostRecentNode.getNode(), listener.getResponse().getContent());
assertEquals(timestampedNodes, listener.getResponse().getTimestampedLwM2mNode());
assertNotNull(listener.getResponse().getCoapResponse());
assertThat(listener.getResponse().getCoapResponse(), is(instanceOf(Response.class)));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
if (nodeClass == LwM2mObject.class) {
Map<Integer, LwM2mObjectInstance> instances = new HashMap<>(tlvs.length);
// is it an array of TLV resources?
if (tlvs.length > 0 && //
(tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) {
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel == null) {
LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object",
path.getObjectId());
instances.put(0, parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else if (!oModel.multiple) {
instances.put(0, parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else {
throw new CodecException("Object instance TLV is mandatory for multiple instances object [path:%s]",
path);
}
} else {
for (Tlv tlv : tlvs) {
if (tlv.getType() != TlvType.OBJECT_INSTANCE)
throw new CodecException("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]",
tlv.getType().name(), path);
LwM2mObjectInstance objectInstance = parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(),
tlv.getIdentifier(), model);
LwM2mObjectInstance previousObjectInstance = instances.put(objectInstance.getId(), objectInstance);
if (previousObjectInstance != null) {
throw new CodecException(
"2 OBJECT_INSTANCE nodes (%s,%s) with the same identifier %d for path %s",
previousObjectInstance, objectInstance, objectInstance.getId(), path);
}
}
}
return (T) new LwM2mObject(path.getObjectId(), instances.values());
}
// Object instance
else if (nodeClass == LwM2mObjectInstance.class) {
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException("Id conflict between path [%s] and instance TLV [%d]", path,
tlvs[0].getIdentifier());
}
// object instance TLV
return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(),
model);
} else {
// array of TLV resources
// try to retrieve the instanceId from the path or the model
Integer instanceId = path.getObjectInstanceId();
if (instanceId == null) {
// single instance object?
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel != null && !oModel.multiple) {
instanceId = 0;
} else {
instanceId = LwM2mObjectInstance.UNDEFINED;
}
}
return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model);
}
}
// Resource
else if (nodeClass == LwM2mResource.class) {
ResourceModel resourceModel = model.getResourceModel(path.getObjectId(), path.getResourceId());
if (tlvs.length == 0 && resourceModel != null && !resourceModel.multiple) {
// If there is no TlV value and we know that this resource is a single resource we raise an exception
// else we consider this is a multi-instance resource
throw new CodecException("TLV payload is mandatory for single resource %s", path);
} else if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) {
if (path.isResource() && path.getResourceId() != tlvs[0].getIdentifier()) {
throw new CodecException("Id conflict between path [%s] and resource TLV [%s]", path,
tlvs[0].getIdentifier());
}
LwM2mPath resourcePath = new LwM2mPath(path.getObjectId(), path.getObjectInstanceId(),
tlvs[0].getIdentifier());
return (T) parseResourceTlv(tlvs[0], resourcePath, model);
} else {
Type expectedRscType = getResourceType(path, model);
return (T) LwM2mMultipleResource.newResource(path.getResourceId(),
parseTlvValues(tlvs, expectedRscType, path), expectedRscType);
}
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
}
#location 86
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@SuppressWarnings("unchecked")
private static <T extends LwM2mNode> T parseTlv(Tlv[] tlvs, LwM2mPath path, LwM2mModel model, Class<T> nodeClass)
throws CodecException {
LOG.trace("Parsing TLV content for path {}: {}", path, tlvs);
// Object
if (nodeClass == LwM2mObject.class) {
Map<Integer, LwM2mObjectInstance> instances = new HashMap<>(tlvs.length);
// is it an array of TLV resources?
if (tlvs.length > 0 && //
(tlvs[0].getType() == TlvType.MULTIPLE_RESOURCE || tlvs[0].getType() == TlvType.RESOURCE_VALUE)) {
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel == null) {
LOG.warn("No model for object {}. The tlv is decoded assuming this is a single instance object",
path.getObjectId());
instances.put(0, parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else if (!oModel.multiple) {
instances.put(0, parseObjectInstanceTlv(tlvs, path.getObjectId(), 0, model));
} else {
throw new CodecException("Object instance TLV is mandatory for multiple instances object [path:%s]",
path);
}
} else {
for (Tlv tlv : tlvs) {
if (tlv.getType() != TlvType.OBJECT_INSTANCE)
throw new CodecException("Expected TLV of type OBJECT_INSTANCE but was %s [path:%s]",
tlv.getType().name(), path);
LwM2mObjectInstance objectInstance = parseObjectInstanceTlv(tlv.getChildren(), path.getObjectId(),
tlv.getIdentifier(), model);
LwM2mObjectInstance previousObjectInstance = instances.put(objectInstance.getId(), objectInstance);
if (previousObjectInstance != null) {
throw new CodecException(
"2 OBJECT_INSTANCE nodes (%s,%s) with the same identifier %d for path %s",
previousObjectInstance, objectInstance, objectInstance.getId(), path);
}
}
}
return (T) new LwM2mObject(path.getObjectId(), instances.values());
}
// Object instance
else if (nodeClass == LwM2mObjectInstance.class) {
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (path.isObjectInstance() && tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException("Id conflict between path [%s] and instance TLV [object instance id=%d]",
path, tlvs[0].getIdentifier());
}
// object instance TLV
return (T) parseObjectInstanceTlv(tlvs[0].getChildren(), path.getObjectId(), tlvs[0].getIdentifier(),
model);
} else {
// array of TLV resources
// try to retrieve the instanceId from the path or the model
Integer instanceId = path.getObjectInstanceId();
if (instanceId == null) {
// single instance object?
ObjectModel oModel = model.getObjectModel(path.getObjectId());
if (oModel != null && !oModel.multiple) {
instanceId = 0;
} else {
instanceId = LwM2mObjectInstance.UNDEFINED;
}
}
return (T) parseObjectInstanceTlv(tlvs, path.getObjectId(), instanceId, model);
}
}
// Resource
else if (nodeClass == LwM2mResource.class) {
// The object instance level should not be here, but if it is provided and consistent we tolerate it
if (tlvs.length == 1 && tlvs[0].getType() == TlvType.OBJECT_INSTANCE) {
if (tlvs[0].getIdentifier() != path.getObjectInstanceId()) {
throw new CodecException("Id conflict between path [%s] and instance TLV [object instance id=%d]",
path, tlvs[0].getIdentifier());
}
tlvs = tlvs[0].getChildren();
}
ResourceModel resourceModel = model.getResourceModel(path.getObjectId(), path.getResourceId());
if (tlvs.length == 0 && resourceModel != null && !resourceModel.multiple) {
// If there is no TlV value and we know that this resource is a single resource we raise an exception
// else we consider this is a multi-instance resource
throw new CodecException("TLV payload is mandatory for single resource %s", path);
} else if (tlvs.length == 1 && tlvs[0].getType() != TlvType.RESOURCE_INSTANCE) {
Tlv tlv = tlvs[0];
if (tlv.getType() != TlvType.RESOURCE_VALUE && tlv.getType() != TlvType.MULTIPLE_RESOURCE) {
throw new CodecException(
"Expected TLV of type RESOURCE_VALUE or MUlTIPLE_RESOURCE but was %s [path:%s]",
tlv.getType().name(), path);
}
if (path.isResource() && path.getResourceId() != tlv.getIdentifier()) {
throw new CodecException("Id conflict between path [%s] and resource TLV [resource id=%s]", path,
tlv.getIdentifier());
}
return (T) parseResourceTlv(tlv, path, model);
} else {
Type expectedRscType = getResourceType(path, model);
return (T) LwM2mMultipleResource.newResource(path.getResourceId(),
parseTlvValues(tlvs, expectedRscType, path), expectedRscType);
}
} else {
throw new IllegalArgumentException("invalid node class: " + nodeClass);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void createPSKClient(String pskIdentity, byte[] pskKey) {
// Create Security Object (with bootstrap server only)
String bsUrl = "coaps://" + bootstrapServer.getSecureAddress().getHostString() + ":"
+ bootstrapServer.getSecureAddress().getPort();
byte[] pskId = pskIdentity.getBytes(StandardCharsets.UTF_8);
Security security = Security.pskBootstrap(bsUrl, pskId, pskKey);
createClient(security);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void createPSKClient(String pskIdentity, byte[] pskKey) {
// Create Security Object (with bootstrap server only)
String bsUrl = "coaps://" + bootstrapServer.getSecuredAddress().getHostString() + ":"
+ bootstrapServer.getSecuredAddress().getPort();
byte[] pskId = pskIdentity.getBytes(StandardCharsets.UTF_8);
Security security = Security.pskBootstrap(bsUrl, pskId, pskKey);
createClient(security);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void createClient() {
// Create objects Enabler
ObjectsInitializer initializer = new ObjectsInitializer(new LwM2mModel(createObjectModels()));
initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec(
"coap://" + server.getNonSecureAddress().getHostString() + ":" + server.getNonSecureAddress().getPort(),
12345));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U") {
@Override
public ExecuteResponse execute(int resourceid, String params) {
if (resourceid == 4) {
return ExecuteResponse.success();
} else {
return super.execute(resourceid, params);
}
}
});
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.addAll(initializer.create(2, 2000));
// Build Client
LeshanClientBuilder builder = new LeshanClientBuilder(currentEndpointIdentifier.get());
builder.setObjects(objects);
client = builder.build();
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void createClient() {
// Create objects Enabler
ObjectsInitializer initializer = new ObjectsInitializer(new LwM2mModel(createObjectModels()));
initializer.setInstancesForObject(LwM2mId.SECURITY, Security.noSec(
"coap://" + server.getUnsecuredAddress().getHostString() + ":" + server.getUnsecuredAddress().getPort(),
12345));
initializer.setInstancesForObject(LwM2mId.SERVER, new Server(12345, LIFETIME, BindingMode.U, false));
initializer.setInstancesForObject(LwM2mId.DEVICE, new Device("Eclipse Leshan", MODEL_NUMBER, "12345", "U") {
@Override
public ExecuteResponse execute(int resourceid, String params) {
if (resourceid == 4) {
return ExecuteResponse.success();
} else {
return super.execute(resourceid, params);
}
}
});
List<LwM2mObjectEnabler> objects = initializer.createMandatory();
objects.addAll(initializer.create(2, 2000));
// Build Client
LeshanClientBuilder builder = new LeshanClientBuilder(currentEndpointIdentifier.get());
builder.setObjects(objects);
client = builder.build();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private static boolean checkRpkIdentity(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) {
// Manage RPK authentication
// ----------------------------------------------------
PublicKey publicKey = clientIdentity.getRawPublicKey();
if (publicKey == null || !publicKey.equals(securityInfo.getRawPublicKey())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Invalid rpk for client {}: expected \n'{}'\n but was \n'{}'", endpoint,
Hex.encodeHexString(securityInfo.getRawPublicKey().getEncoded()),
Hex.encodeHexString(publicKey.getEncoded()));
}
return false;
} else {
LOG.trace("authenticated client '{}' using DTLS RPK", endpoint);
return true;
}
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private static boolean checkRpkIdentity(String endpoint, Identity clientIdentity, SecurityInfo securityInfo) {
// Manage RPK authentication
// ----------------------------------------------------
PublicKey publicKey = clientIdentity.getRawPublicKey();
if (publicKey == null || !publicKey.equals(securityInfo.getRawPublicKey())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Invalid rpk for client {}: expected \n'{}'\n but was \n'{}'", endpoint,
Hex.encodeHexString(securityInfo.getRawPublicKey().getEncoded()),
publicKey != null ? Hex.encodeHexString(publicKey.getEncoded()) : "null");
}
return false;
} else {
LOG.trace("authenticated client '{}' using DTLS RPK", endpoint);
return true;
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void createClient() {
// Create Security Object (with bootstrap server only)
String bsUrl = "coap://" + bootstrapServer.getUnsecuredAddress().getHostString() + ":"
+ bootstrapServer.getUnsecuredAddress().getPort();
Security security = new Security(bsUrl, true, 3, new byte[0], new byte[0], new byte[0], 12345);
createClient(security);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void createClient() {
createClient(withoutSecurity(), null);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static byte[] encodeInteger(Number number) {
ByteBuffer iBuf = null;
long longValue = number.longValue();
if (longValue == Long.MIN_VALUE) {
throw new IllegalArgumentException(
"Could not encode Long.MIN_VALUE, because of signed magnitude representation.");
}
long positiveValue = longValue < 0 ? -longValue : longValue;
if (positiveValue <= Byte.MAX_VALUE) {
iBuf = ByteBuffer.allocate(1);
iBuf.put((byte) positiveValue);
} else if (positiveValue <= Short.MAX_VALUE) {
iBuf = ByteBuffer.allocate(2);
iBuf.putShort((short) positiveValue);
} else if (positiveValue <= Integer.MAX_VALUE) {
iBuf = ByteBuffer.allocate(4);
iBuf.putInt((int) positiveValue);
} else if (positiveValue <= Long.MAX_VALUE) {
iBuf = ByteBuffer.allocate(8);
iBuf.putLong(positiveValue);
}
byte[] bytes = iBuf.array();
// set the most significant bit to 1 if negative value
if (number.longValue() < 0) {
bytes[0] |= 0b1000_0000;
}
return bytes;
}
#location 25
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static byte[] encodeInteger(Number number) {
ByteBuffer iBuf = null;
long lValue = number.longValue();
if (lValue >= Byte.MIN_VALUE && lValue <= Byte.MAX_VALUE) {
iBuf = ByteBuffer.allocate(1);
iBuf.put((byte) lValue);
} else if (lValue >= Short.MIN_VALUE && lValue <= Short.MAX_VALUE) {
iBuf = ByteBuffer.allocate(2);
iBuf.putShort((short) lValue);
} else if (lValue >= Integer.MIN_VALUE && lValue <= Integer.MAX_VALUE) {
iBuf = ByteBuffer.allocate(4);
iBuf.putInt((int) lValue);
} else {
iBuf = ByteBuffer.allocate(8);
iBuf.putLong(lValue);
}
return iBuf.array();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected void endTransaction() {
if (listener != null) {
listener.endTransaction();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
protected void endTransaction() {
transactionalListener.endTransaction();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private Object findInList(final Object current, final Method m, Node mapEq, String map)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
if (m.getParameterTypes().length != 1 && m.getParameterTypes()[0] != int.class) {
fail("Unable to navigate " + current.getClass().getCanonicalName() + " with method "
+ m.getName());
}
Method countM = GwtReflectionUtils.getMethod(current.getClass(), m.getName() + "Count");
if (countM == null) {
fail("Count method not found in " + current.getClass().getCanonicalName() + " method "
+ m.getName());
}
if (countM.getParameterTypes().length > 0) {
fail("Too many parameter in count method " + current.getClass().getCanonicalName()
+ " method " + countM.getName());
}
logger.debug("Searching in list, field " + mapEq + ", value " + map);
final int count = (Integer) countM.invoke(current);
return findInIterable(new Iterable<Object>() {
public Iterator<Object> iterator() {
return new Iterator<Object>() {
int counter = 0;
public boolean hasNext() {
return counter < count;
}
public Object next() {
try {
return m.invoke(current, counter++);
} catch (Exception e) {
throw new GwtTestCsvException("Iterator exception", e);
}
}
public void remove() {
throw new UnsupportedOperationException("Remove not implemented");
}
};
}
}, mapEq, map, current, m);
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private Object findInList(final Object current, final Method m, Node mapEq, String map)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
if (m.getParameterTypes().length != 1 && m.getParameterTypes()[0] != int.class) {
fail("Unable to navigate " + current.getClass().getCanonicalName() + " with method "
+ m.getName());
}
Method countM = GwtReflectionUtils.getMethod(current.getClass(), m.getName() + "Count");
if (countM == null) {
fail("Count method not found in " + current.getClass().getCanonicalName() + " method "
+ m.getName());
return null;
}
if (countM.getParameterTypes().length > 0) {
fail("Too many parameter in count method " + current.getClass().getCanonicalName()
+ " method " + countM.getName());
}
logger.debug("Searching in list, field " + mapEq + ", value " + map);
final int count = (Integer) countM.invoke(current);
return findInIterable(new Iterable<Object>() {
public Iterator<Object> iterator() {
return new Iterator<Object>() {
int counter = 0;
public boolean hasNext() {
return counter < count;
}
public Object next() {
try {
return m.invoke(current, counter++);
} catch (Exception e) {
throw new GwtTestCsvException("Iterator exception", e);
}
}
public void remove() {
throw new UnsupportedOperationException("Remove not implemented");
}
};
}
}, mapEq, map, current, m);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void initCsvTests(CsvDirectory csvDirectory) throws FileNotFoundException, IOException {
File directory = getDirectory(csvDirectory.value());
testMethods = new ArrayList<Method>();
tests = new HashMap<String, List<List<String>>>();
for (File f : directory.listFiles()) {
if (f.getName().endsWith(csvDirectory.extension())) {
tests.put(f.getAbsolutePath(), CsvReader.readCsv(new FileReader(f)));
}
}
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void initCsvTests(CsvDirectory csvDirectory) throws FileNotFoundException, IOException {
File testsRoot = getDirectory(csvDirectory.value());
String extension = csvDirectory.extension();
testMethods = new ArrayList<Method>();
tests = new HashMap<String, List<List<String>>>();
collectCsvTests(testsRoot, extension, tests);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void close () {
super.close();
// Select one last time to complete closing the socket.
synchronized (updateLock) {
if (!isClosed) {
isClosed = true;
selector.wakeup();
try {
selector.selectNow();
} catch (IOException ignored) {
}
}
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void close () {
super.close();
synchronized (updateLock) { // Blocks to avoid a select while the selector is used to bind the server connection.
}
// Select one last time to complete closing the socket.
if (!isClosed) {
isClosed = true;
selector.wakeup();
try {
selector.selectNow();
} catch (IOException ignored) {
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void loadSqlQueries() throws IOException {
String queriesFile = config().getString(CONFIG_WIKIDB_SQL_QUERIES_RESOURCE_FILE);
InputStream queriesInputStream;
if (queriesFile != null) {
queriesInputStream = new FileInputStream(queriesFile);
} else {
queriesInputStream = getClass().getResourceAsStream("/db-queries.properties");
}
Properties queriesProps = new Properties();
queriesProps.load(queriesInputStream);
queriesInputStream.close();
sqlQueries.put(SqlQuery.CREATE_PAGES_TABLE, queriesProps.getProperty("create-pages-table"));
sqlQueries.put(SqlQuery.ALL_PAGES, queriesProps.getProperty("all-pages"));
sqlQueries.put(SqlQuery.GET_PAGE, queriesProps.getProperty("get-page"));
}
#location 9
#vulnerability type RESOURCE_LEAK
|
#fixed code
private void loadSqlQueries() throws IOException {
String queriesFile = config().getString(CONFIG_WIKIDB_SQL_QUERIES_RESOURCE_FILE);
InputStream queriesInputStream;
if (queriesFile != null) {
queriesInputStream = new FileInputStream(queriesFile);
} else {
queriesInputStream = getClass().getResourceAsStream("/db-queries.properties");
}
Properties queriesProps = new Properties();
queriesProps.load(queriesInputStream);
queriesInputStream.close();
sqlQueries.put(SqlQuery.CREATE_PAGES_TABLE, queriesProps.getProperty("create-pages-table"));
sqlQueries.put(SqlQuery.ALL_PAGES, queriesProps.getProperty("all-pages"));
sqlQueries.put(SqlQuery.GET_PAGE, queriesProps.getProperty("get-page"));
sqlQueries.put(SqlQuery.CREATE_PAGE, queriesProps.getProperty("create-page"));
sqlQueries.put(SqlQuery.SAVE_PAGE, queriesProps.getProperty("save-page"));
sqlQueries.put(SqlQuery.DELETE_PAGE, queriesProps.getProperty("delete-page"));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static String toString(final InputStream stream)
{
StringBuilder out = new StringBuilder();
try
{
final char[] buffer = new char[0x10000];
Reader in = new InputStreamReader(stream, "UTF-8");
int read;
do
{
read = in.read(buffer, 0, buffer.length);
if (read > 0)
{
out.append(buffer, 0, read);
}
}
while (read >= 0);
}
catch (UnsupportedEncodingException e)
{
throw new RuntimeException(e);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return out.toString();
}
#location 19
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static String toString(final InputStream stream)
{
StringBuilder out = new StringBuilder();
try
{
final char[] buffer = new char[0x10000];
Reader in = new InputStreamReader(stream, StandardCharsets.UTF_8);
int read;
do
{
read = in.read(buffer, 0, buffer.length);
if (read > 0)
{
out.append(buffer, 0, read);
}
}
while (read >= 0);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return out.toString();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public Field<O> setLiteralInitializer(final String value)
{
String stub = "public class Stub { private String stub = " + value + " }";
JavaClass temp = (JavaClass) JavaParser.parse(stub);
FieldDeclaration internal = (FieldDeclaration) temp.getFields().get(0).getInternal();
for (Object f : internal.fragments())
{
if (f instanceof VariableDeclarationFragment)
{
VariableDeclarationFragment tempFrag = (VariableDeclarationFragment) f;
VariableDeclarationFragment localFrag = getFragment(field);
localFrag.setInitializer((Expression) ASTNode.copySubtree(ast, tempFrag.getInitializer()));
break;
}
}
return this;
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public Field<O> setLiteralInitializer(final String value)
{
String stub = "public class Stub { private String stub = " + value + " }";
JavaClass temp = (JavaClass) JavaParser.parse(stub);
VariableDeclarationFragment tempFrag = (VariableDeclarationFragment) temp.getFields().get(0).getInternal();
fragment.setInitializer((Expression) ASTNode.copySubtree(ast, tempFrag.getInitializer()));
return this;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.