input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code @Test public static void testApp() throws Exception { ParallelThread parallelThread = new ParallelThread(); List<String> tests = new ArrayList<>(); //tests.add("HomePageTest1"); //tests.add("HomePageTest2"); boolean hasFailures = parallelThread.runner("com.test.site"); Assert.assertFalse(hasFailures, "Testcases have failed in parallel execution"); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test public static void testApp() throws Exception { ParallelThread parallelThread = new ParallelThread(); List<String> tests = new ArrayList<>(); tests.add("HomePageTest3"); tests.add("HomePageTest2"); boolean hasFailures = parallelThread.runner("com.test.site",tests); Assert.assertFalse(hasFailures, "Testcases have failed in parallel execution"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Map<String, String> getDevices() throws Exception { startADB(); // start adb service String output = cmd.runCommand("adb devices"); String[] lines = output.split("\n"); if (lines.length <= 1) { System.out.println("No Device Connected"); stopADB(); return null; } else { for (int i = 1; i < lines.length; i++) { lines[i] = lines[i].replaceAll("\\s+", ""); if (lines[i].contains("device")) { lines[i] = lines[i].replaceAll("device", ""); String deviceID = lines[i]; String model = cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model") .replaceAll("\\s+", ""); String brand = cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand") .replaceAll("\\s+", ""); String osVersion = cmd.runCommand( "adb -s " + deviceID + " shell getprop ro.build.version.release") .replaceAll("\\s+", ""); String deviceName = brand + " " + model; String apiLevel = cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk") .replaceAll("\n", ""); devices.put("deviceID" + i, deviceID); devices.put("deviceName" + i, deviceName); devices.put("osVersion" + i, osVersion); devices.put(deviceID, apiLevel); } else if (lines[i].contains("unauthorized")) { lines[i] = lines[i].replaceAll("unauthorized", ""); String deviceID = lines[i]; } else if (lines[i].contains("offline")) { lines[i] = lines[i].replaceAll("offline", ""); String deviceID = lines[i]; } } return devices; } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public Map<String, String> getDevices() throws Exception { startADB(); // start adb service String output = cmd.runCommand("adb devices"); String[] lines = output.split("\n"); if (lines.length <= 1) { System.out.println("No Android Device Connected"); stopADB(); return null; } else { for (int i = 1; i < lines.length; i++) { lines[i] = lines[i].replaceAll("\\s+", ""); if (lines[i].contains("device")) { lines[i] = lines[i].replaceAll("device", ""); String deviceID = lines[i]; if (validDeviceIds == null || (validDeviceIds != null && validDeviceIds.contains(deviceID))) { String model = cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model") .replaceAll("\\s+", ""); String brand = cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand") .replaceAll("\\s+", ""); String osVersion = cmd.runCommand( "adb -s " + deviceID + " shell getprop ro.build.version.release") .replaceAll("\\s+", ""); String deviceName = brand + " " + model; String apiLevel = cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk") .replaceAll("\n", ""); devices.put("deviceID" + i, deviceID); devices.put("deviceName" + i, deviceName); devices.put("osVersion" + i, osVersion); devices.put(deviceID, apiLevel); deviceSerial.add(deviceID); } } else if (lines[i].contains("unauthorized")) { lines[i] = lines[i].replaceAll("unauthorized", ""); String deviceID = lines[i]; } else if (lines[i].contains("offline")) { lines[i] = lines[i].replaceAll("offline", ""); String deviceID = lines[i]; } } return devices; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void destroyAppiumNode(String host) throws IOException { new Api().getResponse("http://" + host + ":4567" + "/appium/stop").body().string(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void destroyAppiumNode(String host) throws Exception { new Api().getResponse("http://" + host + ":" + getRemoteAppiumManagerPort(host) + "/appium/stop").body().string(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized AppiumServiceBuilder startAppiumServer(String methodName) throws Exception { device_udid = getNextAvailableDeviceId(); if (device_udid == null) { System.out.println("No devices are free to run test or Failed to run test"); return null; } if (System.getProperty("os.name").toLowerCase().contains("mac")) { if (iosDevice.checkiOSDevice(device_udid)) { iosDevice.setIOSWebKitProxyPorts(device_udid); category = iosDevice.getDeviceName(device_udid).replace(" ", "_"); } else if (!iosDevice.checkiOSDevice(device_udid)) { category = androidDevice.getDeviceModel(device_udid); System.out.println(category); } } else { category = androidDevice.getDeviceModel(device_udid); } if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { parent = ExtentTestManager.startTest(methodName, "Mobile Appium Test", category + "_" + device_udid.replaceAll("\\W", "_")); parentContext.put(Thread.currentThread().getId(), parent); ExtentTestManager.getTest().log(LogStatus.INFO, "AppiumServerLogs", "<a href=" + System.getProperty("user.dir") + "/target/appiumlogs/" + device_udid .replaceAll("\\W", "_") + "__" + methodName + ".txt" + ">Logs</a>"); } if (System.getProperty("os.name").toLowerCase().contains("mac")) { if (iosDevice.checkiOSDevice(device_udid)) { String webKitPort = iosDevice.startIOSWebKit(device_udid); return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort); } else if (!iosDevice.checkiOSDevice(device_udid)) { return appiumMan.appiumServerForAndroid(device_udid, methodName); } } else { return appiumMan.appiumServerForAndroid(device_udid, methodName); } return null; } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code public synchronized AppiumServiceBuilder startAppiumServer(String methodName) throws Exception { device_udid = getNextAvailableDeviceId(); if (device_udid == null) { System.out.println("No devices are free to run test or Failed to run test"); return null; } if (System.getProperty("os.name").toLowerCase().contains("mac")) { if (iosDevice.checkiOSDevice(device_udid)) { iosDevice.setIOSWebKitProxyPorts(device_udid); category = iosDevice.getDeviceName(device_udid).replace(" ", "_"); } else if (!iosDevice.checkiOSDevice(device_udid)) { category = androidDevice.getDeviceModel(device_udid); System.out.println(category); } } else { category = androidDevice.getDeviceModel(device_udid); } if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) { if (getClass().getAnnotation(Description.class) != null) { testDescription = getClass().getAnnotation(Description.class).value(); } parent = ExtentTestManager.startTest(methodName, testDescription, category + "_" + device_udid.replaceAll("\\W", "_")); parentContext.put(Thread.currentThread().getId(), parent); ExtentTestManager.getTest().log(LogStatus.INFO, "AppiumServerLogs", "<a href=" + System.getProperty("user.dir") + "/target/appiumlogs/" + device_udid .replaceAll("\\W", "_") + "__" + methodName + ".txt" + ">Logs</a>"); } if (System.getProperty("os.name").toLowerCase().contains("mac")) { if (iosDevice.checkiOSDevice(device_udid)) { String webKitPort = iosDevice.startIOSWebKit(device_udid); return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort); } else if (!iosDevice.checkiOSDevice(device_udid)) { return appiumMan.appiumServerForAndroid(device_udid, methodName); } } else { return appiumMan.appiumServerForAndroid(device_udid, methodName); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void startingServerInstance() throws Exception { if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); } else { if (System.getProperty("os.name").toLowerCase().contains("mac")) { if (iosDevice.checkiOSDevice(device_udid)) { driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative()); } else if (!iosDevice.checkiOSDevice(device_udid)) { driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative()); } } else { driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative()); } } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void startingServerInstance() throws Exception { startingServerInstance(null, null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { // TODO Auto-generated method stub // List<Class> testCases = new ArrayList<Class>(); // testCases.add(HomePageTest1.class); // testCases.add(HomePageTest2.class); // testCases.add(HomePageTest3.class); // testCases.add(HomePageTest4.class); // testCases.add(HomePageTest5.class); List textFiles = new ArrayList(); File dir = new File(System.getProperty("user.dir") + "/src/test/java/com/test/site"); for (File file : dir.listFiles()) { if (file.getName().contains(("Test"))) { textFiles.add(file.getClass().getClassLoader()); } } } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) throws IOException { String logo = "http://sauceio.com/wp-content/uploads/2014/04/appium_logo_final.png"; StringBuilder sb = new StringBuilder(); String a = "testcasepassed"; sb.append("<html>"); sb.append("<head>"); sb.append("<title>Automation Results"); sb.append("</title>"); sb.append("</head>"); sb.append("<body BGCOLOR='white'> <center><img src=" + logo + " ALIGN='center'></center>"); sb.append("</body>"); sb.append("<div style=float:left>"); sb.append("<table BORDER='1' ALIGN='center' width='320'>"); sb.append("<tr><th>TestClassName</th></tr>"); sb.append("<tr><TH><a href=#><center><font color='green'>" + a + "</font></center></a></TH>"); sb.append("</tr>"); sb.append("</table>"); sb.append("</div>"); sb.append("<div style=float:left>"); sb.append("<table BORDER='1' ALIGN='center' width='320'>"); sb.append("<tr><th>TestClassMethod</th></tr>"); sb.append("<tr><TH><a href=#><center><font color='red'>" + a + "</font></center></a></TH>"); sb.append("</tr>"); sb.append("</table>"); sb.append("</div>"); sb.append("</html>"); System.out.println(sb.toString()); FileWriter fstream = new FileWriter("MyHtml.html"); BufferedWriter out = new BufferedWriter(fstream); out.write(sb.toString()); out.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void startingServerInstance() throws Exception { if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) { driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb()); } else { if (System.getProperty("os.name").toLowerCase().contains("mac")) { if (iosDevice.checkiOSDevice(device_udid)) { driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative()); } else if (!iosDevice.checkiOSDevice(device_udid)) { driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative()); } } else { driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative()); } } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void startingServerInstance() throws Exception { startingServerInstance(null, null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public static void testApp() throws Exception { ParallelThread parallelThread = new ParallelThread(); List<String> tests = new ArrayList<>(); //tests.add("HomePageTest1"); //tests.add("HomePageTest2"); boolean hasFailures = parallelThread.runner("com.test.site"); Assert.assertFalse(hasFailures, "Testcases have failed in parallel execution"); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public static void testApp() throws Exception { ParallelThread parallelThread = new ParallelThread(); List<String> tests = new ArrayList<>(); tests.add("HomePageTest3"); tests.add("HomePageTest2"); boolean hasFailures = parallelThread.runner("com.test.site",tests); Assert.assertFalse(hasFailures, "Testcases have failed in parallel execution"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void processIsInJarAndlastModified() { try { URLConnection conn = url.openConnection(); if ("jar".equals(url.getProtocol()) || conn instanceof JarURLConnection) { isInJar = true; lastModified = -1; } else { isInJar = false; lastModified = conn.getLastModified(); } } catch (IOException e) { throw new RuntimeException(e); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code protected void processIsInJarAndlastModified() { if ("file".equalsIgnoreCase(url.getProtocol())) { isInJar = false; lastModified = new File(url.getFile()).lastModified(); } else { isInJar = true; lastModified = -1; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected long getLastModified() { try { URLConnection conn = url.openConnection(); return conn.getLastModified(); } catch (IOException e) { throw new RuntimeException(e); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code protected long getLastModified() { return new File(url.getFile()).lastModified(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void processIsInJarAndlastModified() { try { URLConnection conn = url.openConnection(); if ("jar".equals(url.getProtocol()) || conn instanceof JarURLConnection) { isInJar = true; lastModified = -1; } else { isInJar = false; lastModified = conn.getLastModified(); } } catch (IOException e) { throw new RuntimeException(e); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code protected void processIsInJarAndlastModified() { if ("file".equalsIgnoreCase(url.getProtocol())) { isInJar = false; lastModified = new File(url.getFile()).lastModified(); } else { isInJar = true; lastModified = -1; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void processIsInJarAndlastModified() { try { URLConnection conn = url.openConnection(); if ("jar".equals(url.getProtocol()) || conn instanceof JarURLConnection) { isInJar = true; lastModified = -1; } else { isInJar = false; lastModified = conn.getLastModified(); } } catch (IOException e) { throw new RuntimeException(e); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code protected void processIsInJarAndlastModified() { if ("file".equalsIgnoreCase(url.getProtocol())) { isInJar = false; lastModified = new File(url.getFile()).lastModified(); } else { isInJar = true; lastModified = -1; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected long getLastModified() { try { URLConnection conn = url.openConnection(); return conn.getLastModified(); } catch (IOException e) { throw new RuntimeException(e); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code protected long getLastModified() { return new File(url.getFile()).lastModified(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void processIsInJarAndlastModified() { try { URLConnection conn = url.openConnection(); if ("jar".equals(url.getProtocol()) || conn instanceof JarURLConnection) { isInJar = true; lastModified = -1; } else { isInJar = false; lastModified = conn.getLastModified(); } } catch (IOException e) { throw new RuntimeException(e); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code protected void processIsInJarAndlastModified() { if ("file".equalsIgnoreCase(url.getProtocol())) { isInJar = false; lastModified = new File(url.getFile()).lastModified(); } else { isInJar = true; lastModified = -1; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean hookExist() throws IOException { GHRepository ghRepository = getGitHubRepo(); for (GHHook h : ghRepository.getHooks()) { if (!"web".equals(h.getName())) { continue; } if (!getHookUrl().equals(h.getConfig().get("url"))) { continue; } return true; } return false; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean hookExist() throws IOException { GHRepository ghRepository = getGitHubRepo(); if (ghRepository == null) { throw new IOException("Unable to get repo [ " + reponame + " ]"); } for (GHHook h : ghRepository.getHooks()) { if (!"web".equals(h.getName())) { continue; } if (!getHookUrl().equals(h.getConfig().get("url"))) { continue; } return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Environment setUpEnvironment(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, Run.RunnerAbortedException { GhprbTrigger trigger = Ghprb.extractTrigger(build); if (trigger != null) { trigger.getBuilds().onEnvironmentSetup(build, launcher, listener); } return new hudson.model.Environment(){}; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Environment setUpEnvironment(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, Run.RunnerAbortedException { GhprbTrigger trigger = Ghprb.extractTrigger(build); if (trigger != null && trigger.getBuilds() != null) { trigger.getBuilds().onEnvironmentSetup(build, launcher, listener); } return new hudson.model.Environment(){}; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void check(Map<Integer,GhprbPullRequest> pulls){ if(repo == null) try { repo = gh.getRepository(reponame); if(repo == null){ Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve repo named {0} (Do you have properly set 'GitHub project' field in job configuration?)", reponame); } } catch (IOException ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve repo named " + reponame + " (Do you have properly set 'GitHub project' field in job configuration?)", ex); } List<GHPullRequest> prs; try { prs = repo.getPullRequests(GHIssueState.OPEN); } catch (IOException ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve pull requests.", ex); return; } Set<Integer> closedPulls = new HashSet<Integer>(pulls.keySet()); for(GHPullRequest pr : prs){ Integer id = pr.getNumber(); GhprbPullRequest pull; if(pulls.containsKey(id)){ pull = pulls.get(id); }else{ pull = new GhprbPullRequest(pr, this); pulls.put(id, pull); } try { pull.check(pr,this); } catch (IOException ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Couldn't check pull request #" + id, ex); } closedPulls.remove(id); } removeClosed(closedPulls, pulls); checkBuilds(); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code public void check(Map<Integer,GhprbPullRequest> pulls){ if(repo == null) try { repo = gh.getRepository(reponame); if(repo == null){ Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve repo named {0} (Do you have properly set 'GitHub project' field in job configuration?)", reponame); } } catch (IOException ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve repo named " + reponame + " (Do you have properly set 'GitHub project' field in job configuration?)", ex); } List<GHPullRequest> prs; try { prs = repo.getPullRequests(GHIssueState.OPEN); } catch (IOException ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve pull requests.", ex); return; } Set<Integer> closedPulls = new HashSet<Integer>(pulls.keySet()); for(GHPullRequest pr : prs){ Integer id = pr.getNumber(); GhprbPullRequest pull; if(pulls.containsKey(id)){ pull = pulls.get(id); }else{ pull = new GhprbPullRequest(pr, this); pulls.put(id, pull); } pull.check(pr,this); closedPulls.remove(id); } removeClosed(closedPulls, pulls); checkBuilds(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { AbstractProject<?, ?> project = build.getProject(); if (build.getResult().isWorseThan(Result.SUCCESS)) { logger.log(Level.INFO, "Build did not succeed, merge will not be run"); return true; } trigger = GhprbTrigger.extractTrigger(project); if (trigger == null) return false; ConcurrentMap<Integer, GhprbPullRequest> pulls = trigger.getDescriptor().getPullRequests(project.getName()); helper = new Ghprb(project, trigger, pulls); helper.getRepository().init(); cause = getCause(build); if (cause == null) { return true; } pr = helper.getRepository().getPullRequest(cause.getPullID()); if (pr == null) { logger.log(Level.INFO, "Pull request is null for ID: " + cause.getPullID()); return false; } Boolean isMergeable = pr.getMergeable(); int counter = 0; while (counter++ < 15) { if (isMergeable != null) { break; } try { logger.log(Level.INFO, "Waiting for github to settle so we can check if the PR is mergeable."); Thread.sleep(1000); } catch (Exception e) { } isMergeable = pr.getMergeable(); } if (isMergeable == null || isMergeable) { logger.log(Level.INFO, "Pull request cannot be automerged, moving on."); commentOnRequest("Pull request is not mergeable."); return true; } GHUser commentor = cause.getTriggerSender(); boolean merge = true; if (isOnlyAdminsMerge() && !helper.isAdmin(commentor.getLogin())){ merge = false; logger.log(Level.INFO, "Only admins can merge this pull request, {0} is not an admin.", new Object[]{commentor.getLogin()}); commentOnRequest( String.format("Code not merged because %s is not in the Admin list.", commentor.getName())); } if (isOnlyTriggerPhrase() && !helper.isTriggerPhrase(cause.getCommentBody())) { merge = false; logger.log(Level.INFO, "The comment does not contain the required trigger phrase."); commentOnRequest( String.format("Please comment with '%s' to automerge this request", trigger.getTriggerPhrase())); return true; } if (isDisallowOwnCode() && isOwnCode(pr, commentor)) { merge = false; logger.log(Level.INFO, "The commentor is also one of the contributors."); commentOnRequest( String.format("Code not merged because %s has committed code in the request.", commentor.getName())); } if (merge) { logger.log(Level.INFO, "Merging the pull request"); pr.merge(getMergeComment()); // deleteBranch(); //TODO: Update so it also deletes the branch being pulled from. probably make it an option. } return merge; } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener) throws InterruptedException, IOException { AbstractProject<?, ?> project = build.getProject(); if (build.getResult().isWorseThan(Result.SUCCESS)) { logger.log(Level.INFO, "Build did not succeed, merge will not be run"); return true; } trigger = GhprbTrigger.extractTrigger(project); if (trigger == null) return false; cause = getCause(build); if (cause == null) { return true; } ConcurrentMap<Integer, GhprbPullRequest> pulls = trigger.getDescriptor().getPullRequests(project.getName()); pr = pulls.get(cause.getPullID()).getPullRequest(); if (pr == null) { logger.log(Level.INFO, "Pull request is null for ID: " + cause.getPullID()); return false; } Boolean isMergeable = cause.isMerged(); helper = new Ghprb(project, trigger, pulls); helper.init(); if (isMergeable == null || !isMergeable) { logger.log(Level.INFO, "Pull request cannot be automerged, moving on."); commentOnRequest("Pull request is not mergeable."); return true; } GHUser triggerSender = cause.getTriggerSender(); boolean merge = true; if (isOnlyAdminsMerge() && !helper.isAdmin(triggerSender.getLogin())){ merge = false; logger.log(Level.INFO, "Only admins can merge this pull request, {0} is not an admin.", new Object[]{triggerSender.getLogin()}); commentOnRequest( String.format("Code not merged because %s is not in the Admin list.", triggerSender.getName())); } if (isOnlyTriggerPhrase() && !helper.isTriggerPhrase(cause.getCommentBody())) { merge = false; logger.log(Level.INFO, "The comment does not contain the required trigger phrase."); commentOnRequest( String.format("Please comment with '%s' to automerge this request", trigger.getTriggerPhrase())); } if (isDisallowOwnCode() && isOwnCode(pr, triggerSender)) { merge = false; logger.log(Level.INFO, "The commentor is also one of the contributors."); commentOnRequest( String.format("Code not merged because %s has committed code in the request.", triggerSender.getName())); } if (merge) { logger.log(Level.INFO, "Merging the pull request"); pr.merge(getMergeComment()); logger.log(Level.INFO, "Pull request successfully merged"); // deleteBranch(); //TODO: Update so it also deletes the branch being pulled from. probably make it an option. } return merge; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean cancelBuild(int id) { if(queuedBuilds.containsKey(id)){ try { Run<?,?> build = (Run) queuedBuilds.get(id).waitForStart(); if(build.getExecutor() == null) return false; build.getExecutor().interrupt(); queuedBuilds.remove(id); return true; } catch (Exception ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.WARNING, null, ex); return false; } }else if(runningBuilds.containsKey(id)){ try { Run<?,?> build = (Run) runningBuilds.get(id).waitForStart(); if(build.getExecutor() == null) return false; build.getExecutor().interrupt(); runningBuilds.remove(id); return true; } catch (Exception ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.WARNING, null, ex); return false; } }else{ return false; } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean cancelBuild(int id) { Iterator<GhprbBuild> it = builds.iterator(); while(it.hasNext()){ GhprbBuild build = it.next(); if (build.getPullID() == id) { if (build.cancel()) { it.remove(); return true; } } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onCompleted(AbstractBuild<?, ?> build, TaskListener listener) { GhprbTrigger trigger = Ghprb.extractTrigger(build); if (trigger != null) { trigger.getBuilds().onCompleted(build, listener); } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onCompleted(AbstractBuild<?, ?> build, TaskListener listener) { GhprbTrigger trigger = Ghprb.extractTrigger(build); if (trigger != null && trigger.getBuilds() != null) { trigger.getBuilds().onCompleted(build, listener); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void check(Map<Integer,GhprbPullRequest> pulls){ if(repo == null) try { repo = gh.getRepository(reponame); //TODO: potential NPE if(repo == null){ Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve repo named {0} (Do you have properly set 'GitHub project' field in job configuration?)", reponame); } } catch (IOException ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve repo named " + reponame + " (Do you have properly set 'GitHub project' field in job configuration?)", ex); } List<GHPullRequest> prs; try { prs = repo.getPullRequests(GHIssueState.OPEN); } catch (IOException ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve pull requests.", ex); return; } Set<Integer> closedPulls = new HashSet<Integer>(pulls.keySet()); for(GHPullRequest pr : prs){ Integer id = pr.getNumber(); GhprbPullRequest pull; if(pulls.containsKey(id)){ pull = pulls.get(id); }else{ pull = new GhprbPullRequest(pr, this); pulls.put(id, pull); } pull.check(pr,this); closedPulls.remove(id); } removeClosed(closedPulls, pulls); checkBuilds(); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code public void check(Map<Integer,GhprbPullRequest> pulls){ if(repo == null) try { repo = gh.getRepository(reponame); //TODO: potential NPE if(repo == null){ Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve repo named {0} (Do you have properly set 'GitHub project' field in job configuration?)", reponame); return; } } catch (IOException ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve repo named " + reponame + " (Do you have properly set 'GitHub project' field in job configuration?)", ex); } List<GHPullRequest> prs; try { prs = repo.getPullRequests(GHIssueState.OPEN); } catch (IOException ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve pull requests.", ex); return; } Set<Integer> closedPulls = new HashSet<Integer>(pulls.keySet()); for(GHPullRequest pr : prs){ Integer id = pr.getNumber(); GhprbPullRequest pull; if(pulls.containsKey(id)){ pull = pulls.get(id); }else{ pull = new GhprbPullRequest(pr, this); pulls.put(id, pull); } pull.check(pr,this); closedPulls.remove(id); } removeClosed(closedPulls, pulls); checkBuilds(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void onStarted(AbstractBuild<?, ?> build, TaskListener listener) { GhprbTrigger trigger = Ghprb.extractTrigger(build); if (trigger != null) { trigger.getBuilds().onStarted(build, listener); } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void onStarted(AbstractBuild<?, ?> build, TaskListener listener) { GhprbTrigger trigger = Ghprb.extractTrigger(build); if (trigger != null && trigger.getBuilds() != null) { trigger.getBuilds().onStarted(build, listener); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void check(GHIssueComment comment) { if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring comment"); return; } synchronized (this) { try { checkComment(comment); } catch (IOException ex) { logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex); return; } try { GHUser user = null; try { user = comment.getUser(); } catch (IOException e) { logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e); } updatePR(getPullRequest(true), user); } catch (IOException ex) { logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!"); } checkSkipBuild(comment.getParent()); tryBuild(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void check(GHIssueComment comment) { if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring comment"); return; } synchronized (this) { try { checkComment(comment); } catch (IOException ex) { logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex); return; } try { GHUser user = null; try { user = comment.getUser(); } catch (IOException e) { logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e); } updatePR(getPullRequest(true), user); } catch (IOException ex) { logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!"); } tryBuild(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); checkSkipBuild(pr); tryBuild(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); tryBuild(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); checkSkipBuild(pr); tryBuild(); } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); tryBuild(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean initGhRepository() { GitHub gitHub = null; try { GhprbGitHub repo = helper.getGitHub(); if (repo == null) { return false; } gitHub = repo.get(); if (gitHub.getRateLimit().remaining == 0) { return false; } } catch (FileNotFoundException ex) { logger.log(Level.INFO, "Rate limit API not found."); } catch (IOException ex) { logger.log(Level.SEVERE, "Error while accessing rate limit API", ex); return false; } if (ghRepository == null) { try { ghRepository = gitHub.getRepository(reponame); } catch (IOException ex) { logger.log(Level.SEVERE, "Could not retrieve GitHub repository named " + reponame + " (Do you have properly set 'GitHub project' field in job configuration?)", ex); return false; } } return true; } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean initGhRepository() { GitHub gitHub = null; try { GhprbGitHub repo = helper.getGitHub(); if (repo == null) { return false; } gitHub = repo.get(); if (gitHub == null) { logger.log(Level.SEVERE, "No connection returned to GitHub server!"); return false; } if (gitHub.getRateLimit().remaining == 0) { return false; } } catch (FileNotFoundException ex) { logger.log(Level.INFO, "Rate limit API not found."); } catch (IOException ex) { logger.log(Level.SEVERE, "Error while accessing rate limit API", ex); return false; } if (ghRepository == null) { try { ghRepository = gitHub.getRepository(reponame); } catch (IOException ex) { logger.log(Level.SEVERE, "Could not retrieve GitHub repository named " + reponame + " (Do you have properly set 'GitHub project' field in job configuration?)", ex); return false; } } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public QueueTaskFuture<?> startJob(GhprbCause cause, GhprbRepository repo) { ArrayList<ParameterValue> values = getDefaultParameters(); final String commitSha = cause.isMerged() ? "origin/pr/" + cause.getPullID() + "/merge" : cause.getCommit(); values.add(new StringParameterValue("sha1", commitSha)); values.add(new StringParameterValue("ghprbActualCommit", cause.getCommit())); String triggerAuthor = ""; String triggerAuthorEmail = ""; String triggerAuthorLogin = ""; GhprbPullRequest pr = getRepository().getPullRequest(cause.getPullID()); String lastBuildId = pr.getLastBuildId(); BuildData buildData = null; if (!(job instanceof MatrixProject) && !StringUtils.isEmpty(lastBuildId)) { AbstractBuild<?, ?> lastBuild = job.getBuild(lastBuildId); buildData = lastBuild.getAction(BuildData.class); } try { triggerAuthor = getString(cause.getTriggerSender().getName(), ""); } catch (Exception e) {} try { triggerAuthorEmail = getString(cause.getTriggerSender().getEmail(), ""); } catch (Exception e) {} try { triggerAuthorLogin = getString(cause.getTriggerSender().getLogin(), ""); } catch (Exception e) {} setCommitAuthor(cause, values); values.add(new StringParameterValue("ghprbAuthorRepoGitUrl", getString(cause.getAuthorRepoGitUrl(), ""))); values.add(new StringParameterValue("ghprbTriggerAuthor", triggerAuthor)); values.add(new StringParameterValue("ghprbTriggerAuthorEmail", triggerAuthorEmail)); values.add(new StringParameterValue("ghprbTriggerAuthorLogin", triggerAuthorLogin)); values.add(new StringParameterValue("ghprbTriggerAuthorLoginMention", !triggerAuthorLogin.isEmpty() ? "@" + triggerAuthorLogin : "")); final StringParameterValue pullIdPv = new StringParameterValue("ghprbPullId", String.valueOf(cause.getPullID())); values.add(pullIdPv); values.add(new StringParameterValue("ghprbTargetBranch", String.valueOf(cause.getTargetBranch()))); values.add(new StringParameterValue("ghprbSourceBranch", String.valueOf(cause.getSourceBranch()))); values.add(new StringParameterValue("GIT_BRANCH", String.valueOf(cause.getSourceBranch()))); // it's possible the GHUser doesn't have an associated email address values.add(new StringParameterValue("ghprbPullAuthorEmail", getString(cause.getAuthorEmail(), ""))); values.add(new StringParameterValue("ghprbPullAuthorLogin", String.valueOf(cause.getPullRequestAuthor().getLogin()))); values.add(new StringParameterValue("ghprbPullAuthorLoginMention", "@" + cause.getPullRequestAuthor().getLogin())); values.add(new StringParameterValue("ghprbPullDescription", escapeText(String.valueOf(cause.getShortDescription())))); values.add(new StringParameterValue("ghprbPullTitle", String.valueOf(cause.getTitle()))); values.add(new StringParameterValue("ghprbPullLink", String.valueOf(cause.getUrl()))); values.add(new StringParameterValue("ghprbPullLongDescription", escapeText(String.valueOf(cause.getDescription())))); values.add(new StringParameterValue("ghprbCommentBody", escapeText(String.valueOf(cause.getCommentBody())))); values.add(new StringParameterValue("ghprbGhRepository", repo.getName())); values.add(new StringParameterValue("ghprbCredentialsId", getString(getGitHubApiAuth().getCredentialsId(), ""))); // add the previous pr BuildData as an action so that the correct change log is generated by the GitSCM plugin // note that this will be removed from the Actions list after the job is completed so that the old (and incorrect) // one isn't there return this.job.scheduleBuild2(job.getQuietPeriod(), cause, new ParametersAction(values), buildData); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code public QueueTaskFuture<?> startJob(GhprbCause cause, GhprbRepository repo) { for (GhprbExtension ext : Ghprb.getJobExtensions(this, GhprbBuildStep.class)) { if (ext instanceof GhprbBuildStep) { ((GhprbBuildStep)ext).onStartBuild(super.job, cause); } } ArrayList<ParameterValue> values = getDefaultParameters(); final String commitSha = cause.isMerged() ? "origin/pr/" + cause.getPullID() + "/merge" : cause.getCommit(); values.add(new StringParameterValue("sha1", commitSha)); values.add(new StringParameterValue("ghprbActualCommit", cause.getCommit())); String triggerAuthor = ""; String triggerAuthorEmail = ""; String triggerAuthorLogin = ""; GhprbPullRequest pr = getRepository().getPullRequest(cause.getPullID()); String lastBuildId = pr.getLastBuildId(); BuildData buildData = null; if (!(job instanceof MatrixProject) && !StringUtils.isEmpty(lastBuildId)) { AbstractBuild<?, ?> lastBuild = job.getBuild(lastBuildId); buildData = lastBuild.getAction(BuildData.class); } try { triggerAuthor = getString(cause.getTriggerSender().getName(), ""); } catch (Exception e) {} try { triggerAuthorEmail = getString(cause.getTriggerSender().getEmail(), ""); } catch (Exception e) {} try { triggerAuthorLogin = getString(cause.getTriggerSender().getLogin(), ""); } catch (Exception e) {} setCommitAuthor(cause, values); values.add(new StringParameterValue("ghprbAuthorRepoGitUrl", getString(cause.getAuthorRepoGitUrl(), ""))); values.add(new StringParameterValue("ghprbTriggerAuthor", triggerAuthor)); values.add(new StringParameterValue("ghprbTriggerAuthorEmail", triggerAuthorEmail)); values.add(new StringParameterValue("ghprbTriggerAuthorLogin", triggerAuthorLogin)); values.add(new StringParameterValue("ghprbTriggerAuthorLoginMention", !triggerAuthorLogin.isEmpty() ? "@" + triggerAuthorLogin : "")); final StringParameterValue pullIdPv = new StringParameterValue("ghprbPullId", String.valueOf(cause.getPullID())); values.add(pullIdPv); values.add(new StringParameterValue("ghprbTargetBranch", String.valueOf(cause.getTargetBranch()))); values.add(new StringParameterValue("ghprbSourceBranch", String.valueOf(cause.getSourceBranch()))); values.add(new StringParameterValue("GIT_BRANCH", String.valueOf(cause.getSourceBranch()))); // it's possible the GHUser doesn't have an associated email address values.add(new StringParameterValue("ghprbPullAuthorEmail", getString(cause.getAuthorEmail(), ""))); values.add(new StringParameterValue("ghprbPullAuthorLogin", String.valueOf(cause.getPullRequestAuthor().getLogin()))); values.add(new StringParameterValue("ghprbPullAuthorLoginMention", "@" + cause.getPullRequestAuthor().getLogin())); values.add(new StringParameterValue("ghprbPullDescription", escapeText(String.valueOf(cause.getShortDescription())))); values.add(new StringParameterValue("ghprbPullTitle", String.valueOf(cause.getTitle()))); values.add(new StringParameterValue("ghprbPullLink", String.valueOf(cause.getUrl()))); values.add(new StringParameterValue("ghprbPullLongDescription", escapeText(String.valueOf(cause.getDescription())))); values.add(new StringParameterValue("ghprbCommentBody", escapeText(String.valueOf(cause.getCommentBody())))); values.add(new StringParameterValue("ghprbGhRepository", repo.getName())); values.add(new StringParameterValue("ghprbCredentialsId", getString(getGitHubApiAuth().getCredentialsId(), ""))); // add the previous pr BuildData as an action so that the correct change log is generated by the GitSCM plugin // note that this will be removed from the Actions list after the job is completed so that the old (and incorrect) // one isn't there return this.job.scheduleBuild2(job.getQuietPeriod(), cause, new ParametersAction(values), buildData); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); checkSkipBuild(pr); tryBuild(); } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); tryBuild(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); checkSkipBuild(pr); tryBuild(); } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); tryBuild(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void makeBuildVariables(@SuppressWarnings("rawtypes") AbstractBuild build, Map<String,String> variables){ variables.put("ghprbUpstreamStatus", "true"); variables.put("ghprbCommitStatusContext", commitStatusContext); variables.put("ghprbTriggeredStatus", triggeredStatus); variables.put("ghprbStartedStatus", startedStatus); variables.put("ghprbStatusUrl", statusUrl); Map<GHCommitState, StringBuilder> statusMessages = new HashMap<GHCommitState, StringBuilder>(5); for (GhprbBuildResultMessage message : completedStatus) { GHCommitState state = message.getResult(); StringBuilder sb; if (statusMessages.containsKey(state)){ sb = new StringBuilder(); statusMessages.put(state, sb); } else { sb = statusMessages.get(state); sb.append("\n"); } sb.append(message.getMessage()); } for (Entry<GHCommitState, StringBuilder> next : statusMessages.entrySet()) { String key = String.format("ghprb%sMessage", next.getKey().name()); variables.put(key, next.getValue().toString()); } } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void makeBuildVariables(@SuppressWarnings("rawtypes") AbstractBuild build, Map<String,String> variables){ variables.put("ghprbUpstreamStatus", "true"); variables.put("ghprbCommitStatusContext", commitStatusContext); variables.put("ghprbTriggeredStatus", triggeredStatus); variables.put("ghprbStartedStatus", startedStatus); variables.put("ghprbStatusUrl", statusUrl); Map<GHCommitState, StringBuilder> statusMessages = new HashMap<GHCommitState, StringBuilder>(5); for (GhprbBuildResultMessage message : completedStatus) { GHCommitState state = message.getResult(); StringBuilder sb; if (!statusMessages.containsKey(state)) { sb = new StringBuilder(); statusMessages.put(state, sb); } else { sb = statusMessages.get(state); sb.append("\n"); } sb.append(message.getMessage()); } for (Entry<GHCommitState, StringBuilder> next : statusMessages.entrySet()) { String key = String.format("ghprb%sMessage", next.getKey().name()); variables.put(key, next.getValue().toString()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void onStarted(AbstractBuild<?, ?> build, TaskListener listener) { PrintStream logger = listener.getLogger(); GhprbCause c = Ghprb.getCause(build); if (c == null) { return; } GhprbTrigger trigger = Ghprb.extractTrigger(build); ConcurrentMap<Integer, GhprbPullRequest> pulls = trigger.getDescriptor().getPullRequests(build.getProject().getFullName()); GHPullRequest pr = pulls.get(c.getPullID()).getPullRequest(); try { int counter = 0; Boolean isMergeable = pr.getMergeable(); Boolean isMerged = pr.isMerged(); while (isMergeable == null && !isMerged && counter++ < 60) { Thread.sleep(1000); isMergeable = pr.getMergeable(); isMerged = pr.isMerged(); } if (isMergeable != c.isMerged() || isMerged == true) { logger.println("!!! PR status has changed !!! "); if (isMergeable == null) { if (isMerged) { logger.println("PR has already been merged"); } else { logger.println("PR merge status couldn't be retrieved, GitHub maybe hasn't settled yet"); } } else if (isMergeable) { logger.println("PR has NO merge conflicts"); } else if (!isMergeable) { logger.println("PR has merge conflicts!"); } } } catch (Exception e) { logger.print("Unable to query GitHub for status of PullRequest"); e.printStackTrace(logger); } for (GhprbExtension ext : Ghprb.getJobExtensions(trigger, GhprbCommitStatus.class)) { if (ext instanceof GhprbCommitStatus) { try { ((GhprbCommitStatus) ext).onBuildStart(build, listener, repo.getGitHubRepo()); } catch (GhprbCommitStatusException e) { repo.commentOnFailure(build, listener, e); } } } try { build.setDescription("<a title=\"" + c.getTitle() + "\" href=\"" + c.getUrl() + "\">PR #" + c.getPullID() + "</a>: " + c.getAbbreviatedTitle()); } catch (IOException ex) { logger.println("Can't update build description"); ex.printStackTrace(logger); } } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code public void onStarted(AbstractBuild<?, ?> build, TaskListener listener) { PrintStream logger = listener.getLogger(); GhprbCause c = Ghprb.getCause(build); if (c == null) { return; } GhprbTrigger trigger = Ghprb.extractTrigger(build); ConcurrentMap<Integer, GhprbPullRequest> pulls = trigger.getDescriptor().getPullRequests(build.getProject().getFullName()); GHPullRequest pr = pulls.get(c.getPullID()).getPullRequest(); try { int counter = 0; // If the PR is being resolved by GitHub then getMergeable will return null Boolean isMergeable = pr.getMergeable(); Boolean isMerged = pr.isMerged(); // Not sure if isMerged can return null, but adding if just in case if (isMerged == null) { isMerged = false; } while (isMergeable == null && !isMerged && counter++ < 60) { Thread.sleep(1000); isMergeable = pr.getMergeable(); isMerged = pr.isMerged(); if (isMerged == null) { isMerged = false; } } if (isMerged) { logger.println("PR has already been merged, builds using the merged sha1 will fail!!!"); } else if (isMergeable == null) { logger.println("PR merge status couldn't be retrieved, maybe GitHub hasn't settled yet"); } else if (isMergeable != c.isMerged()) { logger.println("!!! PR mergeability status has changed !!! "); if (isMergeable) { logger.println("PR now has NO merge conflicts"); } else if (!isMergeable) { logger.println("PR now has merge conflicts!"); } } } catch (Exception e) { logger.print("Unable to query GitHub for status of PullRequest"); e.printStackTrace(logger); } for (GhprbExtension ext : Ghprb.getJobExtensions(trigger, GhprbCommitStatus.class)) { if (ext instanceof GhprbCommitStatus) { try { ((GhprbCommitStatus) ext).onBuildStart(build, listener, repo.getGitHubRepo()); } catch (GhprbCommitStatusException e) { repo.commentOnFailure(build, listener, e); } } } try { build.setDescription("<a title=\"" + c.getTitle() + "\" href=\"" + c.getUrl() + "\">PR #" + c.getPullID() + "</a>: " + c.getAbbreviatedTitle()); } catch (IOException ex) { logger.println("Can't update build description"); ex.printStackTrace(logger); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void check(GHIssueComment comment) { if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring comment"); return; } synchronized (this) { try { checkComment(comment); } catch (IOException ex) { logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex); return; } try { GHUser user = null; try { user = comment.getUser(); } catch (IOException e) { logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e); } updatePR(getPullRequest(true), user); } catch (IOException ex) { logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!"); } checkSkipBuild(comment.getParent()); tryBuild(); } } #location 28 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void check(GHIssueComment comment) { if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring comment"); return; } synchronized (this) { try { checkComment(comment); } catch (IOException ex) { logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex); return; } try { GHUser user = null; try { user = comment.getUser(); } catch (IOException e) { logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e); } updatePR(getPullRequest(true), user); } catch (IOException ex) { logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!"); } tryBuild(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); checkSkipBuild(pr); tryBuild(); } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void check(GHPullRequest ghpr) { setPullRequest(ghpr); if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring pull request"); return; } try { getPullRequest(false); } catch (IOException e) { logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e); return; } updatePR(pr, pr.getUser()); tryBuild(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void handleWebHook(String event, String payload, String body, String signature) { if (!checkSignature(body, signature, trigger.getGitHubApiAuth().getSecret())){ return; } GhprbRepository repo = trigger.getRepository(); String repoName = repo.getName(); logger.log(Level.INFO, "Got payload event: {0}", event); try { GitHub gh = trigger.getGitHub(); if ("issue_comment".equals(event)) { GHEventPayload.IssueComment issueComment = gh.parseEventPayload( new StringReader(payload), GHEventPayload.IssueComment.class); GHIssueState state = issueComment.getIssue().getState(); if (state == GHIssueState.CLOSED) { logger.log(Level.INFO, "Skip comment on closed PR"); return; } if (matchRepo(repo, issueComment.getRepository())) { logger.log(Level.INFO, "Checking issue comment ''{0}'' for repo {1}", new Object[] { issueComment.getComment(), repoName } ); repo.onIssueCommentHook(issueComment); } } else if ("pull_request".equals(event)) { GHEventPayload.PullRequest pr = gh.parseEventPayload( new StringReader(payload), GHEventPayload.PullRequest.class); if (matchRepo(repo, pr.getPullRequest().getRepository())) { logger.log(Level.INFO, "Checking PR #{1} for {0}", new Object[] { repoName, pr.getNumber() }); repo.onPullRequestHook(pr); } } else { logger.log(Level.WARNING, "Request not known"); } } catch (IOException ex) { logger.log(Level.SEVERE, "Failed to parse github hook payload for " + trigger.getProject(), ex); } } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public void handleWebHook(String event, String payload, String body, String signature) { GhprbRepository repo = trigger.getRepository(); String repoName = repo.getName(); logger.log(Level.INFO, "Got payload event: {0}", event); try { GitHub gh = trigger.getGitHub(); if ("issue_comment".equals(event)) { GHEventPayload.IssueComment issueComment = gh.parseEventPayload( new StringReader(payload), GHEventPayload.IssueComment.class); GHIssueState state = issueComment.getIssue().getState(); if (state == GHIssueState.CLOSED) { logger.log(Level.INFO, "Skip comment on closed PR"); return; } if (matchRepo(repo, issueComment.getRepository())) { if (!checkSignature(body, signature, trigger.getGitHubApiAuth().getSecret())){ return; } logger.log(Level.INFO, "Checking issue comment ''{0}'' for repo {1}", new Object[] { issueComment.getComment(), repoName } ); repo.onIssueCommentHook(issueComment); } } else if ("pull_request".equals(event)) { GHEventPayload.PullRequest pr = gh.parseEventPayload( new StringReader(payload), GHEventPayload.PullRequest.class); if (matchRepo(repo, pr.getPullRequest().getRepository())) { if (!checkSignature(body, signature, trigger.getGitHubApiAuth().getSecret())){ return; } logger.log(Level.INFO, "Checking PR #{1} for {0}", new Object[] { repoName, pr.getNumber() }); repo.onPullRequestHook(pr); } } else { logger.log(Level.WARNING, "Request not known"); } } catch (IOException ex) { logger.log(Level.SEVERE, "Failed to parse github hook payload for " + trigger.getProject(), ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void check(GHIssueComment comment) { if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring comment"); return; } synchronized (this) { try { checkComment(comment); } catch (IOException ex) { logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex); return; } try { GHUser user = null; try { user = comment.getUser(); } catch (IOException e) { logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e); } updatePR(getPullRequest(true), user); } catch (IOException ex) { logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!"); } checkSkipBuild(comment.getParent()); tryBuild(); } } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void check(GHIssueComment comment) { if (helper.isProjectDisabled()) { logger.log(Level.FINE, "Project is disabled, ignoring comment"); return; } synchronized (this) { try { checkComment(comment); } catch (IOException ex) { logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex); return; } try { GHUser user = null; try { user = comment.getUser(); } catch (IOException e) { logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e); } updatePR(getPullRequest(true), user); } catch (IOException ex) { logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!"); } tryBuild(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean cancelBuild(int id) { if(queuedBuilds.containsKey(id)){ try { Run<?,?> build = (Run) queuedBuilds.get(id).waitForStart(); if(build.getExecutor() == null) return false; build.getExecutor().interrupt(); queuedBuilds.remove(id); return true; } catch (Exception ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.WARNING, null, ex); return false; } }else if(runningBuilds.containsKey(id)){ try { Run<?,?> build = (Run) runningBuilds.get(id).waitForStart(); if(build.getExecutor() == null) return false; build.getExecutor().interrupt(); runningBuilds.remove(id); return true; } catch (Exception ex) { Logger.getLogger(GhprbRepo.class.getName()).log(Level.WARNING, null, ex); return false; } }else{ return false; } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean cancelBuild(int id) { Iterator<GhprbBuild> it = builds.iterator(); while(it.hasNext()){ GhprbBuild build = it.next(); if (build.getPullID() == id) { if (build.cancel()) { 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 findByIdTest() { TestEntity result = this.datastoreTemplate.findById(this.key1, TestEntity.class); assertThat(result).isEqualTo(this.ob1); assertThat(result.childEntities).contains(this.childEntity1); assertThat(this.childEntity1).isEqualTo(result.singularReference); assertThat(result.multipleReference).contains(this.childEntity1); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void findByIdTest() { verifyBeforeAndAfterEvents(null, new AfterFindByKeyEvent(Arrays.asList(this.ob1), Collections.singleton(this.key1)), () -> { TestEntity result = this.datastoreTemplate.findById(this.key1, TestEntity.class); assertThat(result).isEqualTo(this.ob1); assertThat(result.childEntities).contains(this.childEntity1); assertThat(this.childEntity1).isEqualTo(result.singularReference); assertThat(result.multipleReference).contains(this.childEntity1); }, x -> { }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void findAllByIdReferenceConsistencyTest() { when(this.objectToKeyFactory.getKeyFromObject(eq(this.childEntity1), any())).thenReturn(this.childEntity1.id); when(this.datastore.fetch(eq(this.key1))) .thenReturn(Arrays.asList(this.e1)); TestEntity parentEntity1 = this.datastoreTemplate.findById(this.key1, TestEntity.class); assertThat(parentEntity1).isSameAs(this.ob1); ChildEntity singularReference1 = parentEntity1.singularReference; ChildEntity childEntity1 = parentEntity1.childEntities.get(0); assertThat(singularReference1).isSameAs(childEntity1); TestEntity parentEntity2 = this.datastoreTemplate.findById(this.key1, TestEntity.class); assertThat(parentEntity2).isSameAs(this.ob1); ChildEntity singularReference2 = parentEntity2.singularReference; ChildEntity childEntity2 = parentEntity2.childEntities.get(0); assertThat(singularReference2).isSameAs(childEntity2); assertThat(childEntity1).isNotSameAs(childEntity2); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void findAllByIdReferenceConsistencyTest() { when(this.objectToKeyFactory.getKeyFromObject(eq(this.childEntity1), any())).thenReturn(this.childEntity1.id); when(this.datastore.fetch(eq(this.key1))) .thenReturn(Arrays.asList(this.e1)); verifyBeforeAndAfterEvents(null, new AfterFindByKeyEvent(Collections.singletonList(this.ob1), Collections.singleton(this.key1)), () -> { TestEntity parentEntity1 = this.datastoreTemplate.findById(this.key1, TestEntity.class); assertThat(parentEntity1).isSameAs(this.ob1); ChildEntity singularReference1 = parentEntity1.singularReference; ChildEntity childEntity1 = parentEntity1.childEntities.get(0); assertThat(singularReference1).isSameAs(childEntity1); TestEntity parentEntity2 = this.datastoreTemplate.findById(this.key1, TestEntity.class); assertThat(parentEntity2).isSameAs(this.ob1); ChildEntity singularReference2 = parentEntity2.singularReference; ChildEntity childEntity2 = parentEntity2.childEntities.get(0); assertThat(singularReference2).isSameAs(childEntity2); assertThat(childEntity1).isNotSameAs(childEntity2); }, x -> { }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") private static Map<Class<?>, BiConsumer<ValueBinder<?>, Iterable>> createIterableTypeMapping() { // Java 8 has compile errors when using the builder extension methods // @formatter:off ImmutableMap.Builder<Class<?>, BiConsumer<ValueBinder<?>, Iterable>> builder = new ImmutableMap.Builder<>(); // @formatter:on builder.put(com.google.cloud.Date.class, ValueBinder::toDateArray); builder.put(Boolean.class, ValueBinder::toBoolArray); builder.put(Long.class, ValueBinder::toInt64Array); builder.put(String.class, ValueBinder::toStringArray); builder.put(Double.class, ValueBinder::toFloat64Array); builder.put(Timestamp.class, ValueBinder::toTimestampArray); builder.put(ByteArray.class, ValueBinder::toBytesArray); return builder.build(); } #location 2 #vulnerability type CHECKERS_IMMUTABLE_CAST
#fixed code @SuppressWarnings("unchecked") private static Map<Class<?>, BiConsumer<ValueBinder<?>, Iterable>> createIterableTypeMapping() { Map<Class<?>, BiConsumer<ValueBinder<?>, Iterable>> map = new LinkedHashMap<>(); map.put(com.google.cloud.Date.class, ValueBinder::toDateArray); map.put(Boolean.class, ValueBinder::toBoolArray); map.put(Long.class, ValueBinder::toInt64Array); map.put(String.class, ValueBinder::toStringArray); map.put(Double.class, ValueBinder::toFloat64Array); map.put(Timestamp.class, ValueBinder::toTimestampArray); map.put(ByteArray.class, ValueBinder::toBytesArray); return Collections.unmodifiableMap(map); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void findAllByIdReferenceConsistencyTest() { when(this.objectToKeyFactory.getKeyFromObject(eq(this.childEntity1), any())).thenReturn(this.childEntity1.id); when(this.datastore.fetch(eq(this.key1))) .thenReturn(Arrays.asList(this.e1)); TestEntity parentEntity1 = this.datastoreTemplate.findById(this.key1, TestEntity.class); assertThat(parentEntity1).isSameAs(this.ob1); ChildEntity singularReference1 = parentEntity1.singularReference; ChildEntity childEntity1 = parentEntity1.childEntities.get(0); assertThat(singularReference1).isSameAs(childEntity1); TestEntity parentEntity2 = this.datastoreTemplate.findById(this.key1, TestEntity.class); assertThat(parentEntity2).isSameAs(this.ob1); ChildEntity singularReference2 = parentEntity2.singularReference; ChildEntity childEntity2 = parentEntity2.childEntities.get(0); assertThat(singularReference2).isSameAs(childEntity2); assertThat(childEntity1).isNotSameAs(childEntity2); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void findAllByIdReferenceConsistencyTest() { when(this.objectToKeyFactory.getKeyFromObject(eq(this.childEntity1), any())).thenReturn(this.childEntity1.id); when(this.datastore.fetch(eq(this.key1))) .thenReturn(Arrays.asList(this.e1)); verifyBeforeAndAfterEvents(null, new AfterFindByKeyEvent(Collections.singletonList(this.ob1), Collections.singleton(this.key1)), () -> { TestEntity parentEntity1 = this.datastoreTemplate.findById(this.key1, TestEntity.class); assertThat(parentEntity1).isSameAs(this.ob1); ChildEntity singularReference1 = parentEntity1.singularReference; ChildEntity childEntity1 = parentEntity1.childEntities.get(0); assertThat(singularReference1).isSameAs(childEntity1); TestEntity parentEntity2 = this.datastoreTemplate.findById(this.key1, TestEntity.class); assertThat(parentEntity2).isSameAs(this.ob1); ChildEntity singularReference2 = parentEntity2.singularReference; ChildEntity childEntity2 = parentEntity2.childEntities.get(0); assertThat(singularReference2).isSameAs(childEntity2); assertThat(childEntity1).isNotSameAs(childEntity2); }, x -> { }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private <T> String buildResourceName(T entity) { FirestorePersistentEntity<?> persistentEntity = this.mappingContext.getPersistentEntity(entity.getClass()); FirestorePersistentProperty idProperty = persistentEntity.getIdPropertyOrFail(); Object idVal = persistentEntity.getPropertyAccessor(entity).getProperty(idProperty); return buildResourceName(persistentEntity, idVal.toString()); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code private <T> String buildResourceName(T entity) { FirestorePersistentEntity<?> persistentEntity = this.mappingContext.getPersistentEntity(entity.getClass()); FirestorePersistentProperty idProperty = persistentEntity.getIdPropertyOrFail(); Object idVal = persistentEntity.getPropertyAccessor(entity).getProperty(idProperty); if (idVal == null) { if (idProperty.getType() != String.class) { throw new FirestoreDataException( "ID property was null; automatic ID generation is only supported for String type"); } //TODO: replace with com.google.cloud.firestore.Internal.autoId() when it is available idVal = AutoId.autoId(); persistentEntity.getPropertyAccessor(entity).setProperty(idProperty, idVal); } return buildResourceName(persistentEntity, idVal.toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean isDiscriminationFieldMatch(DatastorePersistentEntity entity, EntityPropertyValueProvider propertyValueProvider) { return propertyValueProvider.getPropertyValue(entity.getDiscriminationFieldName(), EmbeddedType.NOT_EMBEDDED, ClassTypeInformation.from(String.class)).equals(entity.getDiscriminationValue()); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean isDiscriminationFieldMatch(DatastorePersistentEntity entity, EntityPropertyValueProvider propertyValueProvider) { return ((String[]) propertyValueProvider.getPropertyValue(entity.getDiscriminationFieldName(), EmbeddedType.NOT_EMBEDDED, ClassTypeInformation.from(String[].class)))[0].equals(entity.getDiscriminationValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(proxyValue, proxyUser, proxyPass); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(driverManagerType); urlFilter = new UrlFilter(); if (isForcingDownload) { downloader.forceDownload(); } updateValuesWithConfig(); boolean getLatest = version == null || version.isEmpty() || version.equalsIgnoreCase(LATEST.name()) || version.equalsIgnoreCase(NOT_SPECIFIED.name()); boolean cache = this.isForcingCache || getBoolean("wdm.forceCache") || !isNetAvailable(); log.trace(">> Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); Optional<String> driverInCache = handleCache(arch, version, getLatest, cache); if (driverInCache.isPresent()) { versionToDownload = version; downloadedVersion = version; log.debug("Driver for {} {} found in cache {}", getDriverName(), versionToDownload, driverInCache.get()); exportDriver(getExportParameter(), driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String versionStr = getLatest ? "(latest version)" : version; String errorMessage = getDriverName() + " " + versionStr + " for " + myOsName + arch.toString() + " not found in " + getDriverUrl(); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { handleException(e, arch, version); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(proxyValue, proxyUser, proxyPass); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(driverManagerType); urlFilter = new UrlFilter(); updateValuesWithConfig(); boolean getLatest = version == null || version.isEmpty() || version.equalsIgnoreCase(LATEST.name()) || version.equalsIgnoreCase(NOT_SPECIFIED.name()); boolean cache = this.isForcingCache || getBoolean("wdm.forceCache") || !isNetAvailable(); log.trace(">> Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); Optional<String> driverInCache = handleCache(arch, version, getLatest, cache); if (driverInCache.isPresent()) { versionToDownload = version; downloadedVersion = version; log.debug("Driver for {} {} found in cache {}", getDriverName(), versionToDownload, driverInCache.get()); exportDriver(getExportParameter(), driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String versionStr = getLatest ? "(latest version)" : version; String errorMessage = getDriverName() + " " + versionStr + " for " + myOsName + arch.toString() + " not found in " + getDriverUrl(); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { handleException(e, arch, version); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public BrowserManager useTaobaoMirror() { String taobaoUrl = null; try { taobaoUrl = WdmConfig .getString(WdmConfig.getString("wdm.geckoDriverTaobaoUrl")); driverUrl = new URL(taobaoUrl); } catch (MalformedURLException e) { String errorMessage = "Malformed URL " + taobaoUrl; log.error(errorMessage, e); throw new WebDriverManagerException(errorMessage, e); } return instance; } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public BrowserManager useTaobaoMirror() { return useTaobaoMirror("wdm.geckoDriverTaobaoUrl"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); if (isUnknown(driverVersion)) { preferenceKey = getDriverManagerType().getNameInLowerCase(); Optional<String> browserVersion = empty(); if (usePreferences() && preferences.checkKeyInPreferences(preferenceKey)) { browserVersion = Optional.of( preferences.getValueFromPreferences(preferenceKey)); } if (!browserVersion.isPresent()) { browserVersion = detectBrowserVersion(); } if (browserVersion.isPresent()) { // Calculate driverVersion using browserVersion preferenceKey = getDriverManagerType().getNameInLowerCase() + browserVersion.get(); if (usePreferences() && preferences .checkKeyInPreferences(preferenceKey)) { driverVersion = preferences .getValueFromPreferences(preferenceKey); } if (isUnknown(driverVersion)) { Optional<String> driverVersionFromRepository = getDriverVersionFromRepository( browserVersion); if (driverVersionFromRepository.isPresent()) { driverVersion = driverVersionFromRepository.get(); } } if (isUnknown(driverVersion)) { Optional<String> driverVersionFromProperties = getDriverVersionFromProperties( preferenceKey); if (driverVersionFromProperties.isPresent()) { driverVersion = driverVersionFromProperties.get(); } } else { log.info( "Using {} {} (since {} {} is installed in your machine)", getDriverName(), driverVersion, getDriverManagerType(), browserVersion.get()); } if (usePreferences()) { preferences.putValueInPreferencesIfEmpty( getDriverManagerType().getNameInLowerCase(), browserVersion.get()); preferences.putValueInPreferencesIfEmpty(preferenceKey, driverVersion); } if (isUnknown(driverVersion)) { log.debug( "The driver version for {} {} is unknown ... trying with latest", getDriverManagerType(), browserVersion.get()); } } // if driverVersion is still unknown, try with latest if (isUnknown(driverVersion)) { Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository(); if (latestDriverVersionFromRepository.isPresent()) { driverVersion = latestDriverVersionFromRepository.get(); } } } downloadAndExport(driverVersion); } catch (Exception e) { handleException(e, driverVersion); } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); if (isUnknown(driverVersion)) { driverVersion = resolveDriverVersion(driverVersion); } downloadAndExport(driverVersion); } catch (Exception e) { handleException(e, driverVersion); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected List<URL> getDriversFromGitHub() throws IOException { List<URL> urls; URL driverUrl = getDriverUrl(); log.info("Reading {} to seek {}", driverUrl, getDriverName()); Optional<URL> mirrorUrl = getMirrorUrl(); if (mirrorUrl.isPresent() && config.isUseMirror()) { urls = getDriversFromMirror(mirrorUrl.get()); } else { String driverVersion = versionToDownload; try (BufferedReader reader = new BufferedReader( new InputStreamReader(openGitHubConnection(driverUrl)))) { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class); if (driverVersion != null) { releaseArray = new GitHubApi[] { getVersion(releaseArray, driverVersion) }; } urls = new ArrayList<>(); for (GitHubApi release : releaseArray) { if (release != null) { List<LinkedTreeMap<String, Object>> assets = release .getAssets(); for (LinkedTreeMap<String, Object> asset : assets) { urls.add(new URL(asset.get("browser_download_url") .toString())); } } } } } return urls; } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected List<URL> getDriversFromGitHub() throws IOException { List<URL> urls; URL driverUrl = getDriverUrl(); log.info("Reading {} to seek {}", driverUrl, getDriverName()); Optional<URL> mirrorUrl = getMirrorUrl(); if (mirrorUrl.isPresent() && config.isUseMirror()) { urls = getDriversFromMirror(mirrorUrl.get()); } else { String driverVersion = driverVersionToDownload; try (BufferedReader reader = new BufferedReader( new InputStreamReader(openGitHubConnection(driverUrl)))) { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class); if (driverVersion != null) { releaseArray = new GitHubApi[] { getVersionFromGitHub(releaseArray, driverVersion) }; } urls = new ArrayList<>(); for (GitHubApi release : releaseArray) { if (release != null) { List<LinkedTreeMap<String, Object>> assets = release .getAssets(); for (LinkedTreeMap<String, Object> asset : assets) { urls.add(new URL(asset.get("browser_download_url") .toString())); } } } } } return urls; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest) { Optional<String> optionalBrowserVersion = config() .isAvoidAutoVersion() ? empty() : getBrowserVersion(); if (optionalBrowserVersion.isPresent()) { String browserVersion = optionalBrowserVersion.get(); preferenceKey = getDriverManagerType().name().toLowerCase() + browserVersion; if (getLatest && !config.isOverride() && !config().isAvoidAutoVersion() && !config().isAvoidPreferences() && preferences .checkKeyInPreferences(preferenceKey)) { version = preferences .getValueFromPreferences(preferenceKey); } else { version = getVersionForInstalledBrowser( getDriverManagerType()); } getLatest = version.isEmpty(); } } // For Edge if (checkInsiderVersion(version)) { return; } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", getDriverName(), latestVersion); version = latestVersion; cache = true; } Optional<String> driverInCache = handleCache(arch, version, os, getLatest, cache); String versionStr = getLatest ? "(latest version)" : version; if (driverInCache.isPresent() && !config().isOverride()) { storeVersionToDownload(version); downloadedVersion = version; log.debug("Driver {} {} found in cache", getDriverName(), versionStr); exportDriver(driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String errorMessage = getDriverName() + " " + versionStr + " for " + os + arch.toString() + " not found in " + getDriverUrl(); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { handleException(e, arch, version); } } #location 47 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest) { version = detectDriverVersionFromBrowser(); } getLatest = isNullOrEmpty(version); // For Edge if (checkInsiderVersion(version)) { return; } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", getDriverName(), latestVersion); version = latestVersion; cache = true; } Optional<String> driverInCache = handleCache(arch, version, os, getLatest, cache); String versionStr = getLatest ? "(latest version)" : version; if (driverInCache.isPresent() && !config().isOverride()) { storeVersionToDownload(version); downloadedVersion = version; log.debug("Driver {} {} found in cache", getDriverName(), versionStr); exportDriver(driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String errorMessage = getDriverName() + " " + versionStr + " for " + os + arch.toString() + " not found in " + getDriverUrl(); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { handleException(e, arch, version); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static final File extract(File compressedFile, String export) throws IOException { log.trace("Compressed file {}", compressedFile); File file = null; if (compressedFile.getName().toLowerCase().endsWith("tar.bz2")) { file = unBZip2(compressedFile, export); } else if (compressedFile.getName().toLowerCase().endsWith("gz")) { file = unGzip(compressedFile); } else { ZipFile zipFolder = new ZipFile(compressedFile); Enumeration<?> enu = zipFolder.entries(); while (enu.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) enu.nextElement(); String name = zipEntry.getName(); long size = zipEntry.getSize(); long compressedSize = zipEntry.getCompressedSize(); log.trace("Unzipping {} (size: {} KB, compressed size: {} KB)", name, size, compressedSize); file = new File( compressedFile.getParentFile() + File.separator + name); if (!file.exists() || WdmConfig.getBoolean("wdm.override")) { if (name.endsWith("/")) { file.mkdirs(); continue; } File parent = file.getParentFile(); if (parent != null) { parent.mkdirs(); } InputStream is = zipFolder.getInputStream(zipEntry); FileOutputStream fos = new FileOutputStream(file); byte[] bytes = new byte[1024]; int length; while ((length = is.read(bytes)) >= 0) { fos.write(bytes, 0, length); } is.close(); fos.close(); file.setExecutable(true); } else { log.debug(file + " already exists"); } } zipFolder.close(); } log.trace("Resulting binary file {}", file.getAbsoluteFile()); return file.getAbsoluteFile(); } #location 55 #vulnerability type NULL_DEREFERENCE
#fixed code public static final File extract(File compressedFile, String export) throws IOException { log.trace("Compressed file {}", compressedFile); File file = null; if (compressedFile.getName().toLowerCase().endsWith("tar.bz2")) { file = unBZip2(compressedFile, export); } else if (compressedFile.getName().toLowerCase().endsWith("gz")) { file = unGzip(compressedFile); } else { ZipFile zipFolder = new ZipFile(compressedFile); Enumeration<?> enu = zipFolder.entries(); while (enu.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) enu.nextElement(); String name = zipEntry.getName(); long size = zipEntry.getSize(); long compressedSize = zipEntry.getCompressedSize(); log.trace("Unzipping {} (size: {} KB, compressed size: {} KB)", name, size, compressedSize); file = new File( compressedFile.getParentFile() + File.separator + name); if (!file.exists() || WdmConfig.getBoolean("wdm.override")) { if (name.endsWith("/")) { file.mkdirs(); continue; } File parent = file.getParentFile(); if (parent != null) { parent.mkdirs(); } InputStream is = zipFolder.getInputStream(zipEntry); FileOutputStream fos = new FileOutputStream(file); byte[] bytes = new byte[1024]; int length; while ((length = is.read(bytes)) >= 0) { fos.write(bytes, 0, length); } is.close(); fos.close(); file.setExecutable(true); } else { log.debug(file + " already exists"); } } zipFolder.close(); } file = checkPhantom(compressedFile, export); log.trace("Resulting binary file {}", file.getAbsoluteFile()); return file.getAbsoluteFile(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static File checkPhantom(File archive, String export) throws IOException { File target; String phantomName = "phantomjs"; if (export.contains(phantomName)) { String fileNoExtension = archive.getName().replace(".tar.bz2", "") .replace(".zip", ""); File phantomjs = null; try { phantomjs = new File(archive.getParentFile().getAbsolutePath() + File.separator + fileNoExtension + File.separator + "bin" + File.separator).listFiles()[0]; } catch (Exception e) { String extension = IS_OS_WINDOWS ? ".exe" : ""; phantomjs = new File(archive.getParentFile().getAbsolutePath() + File.separator + fileNoExtension + File.separator + phantomName + extension); } target = new File(archive.getParentFile().getAbsolutePath() + File.separator + phantomjs.getName()); phantomjs.renameTo(target); File delete = new File(archive.getParentFile().getAbsolutePath() + File.separator + fileNoExtension); log.trace("Folder to be deleted: {}", delete); FileUtils.deleteDirectory(delete); } else { target = archive.getParentFile().listFiles()[0]; } return target; } #location 30 #vulnerability type NULL_DEREFERENCE
#fixed code private static File checkPhantom(File archive, String export) throws IOException { File target = null; String phantomName = "phantomjs"; if (export.contains(phantomName)) { String fileNoExtension = archive.getName().replace(".tar.bz2", "") .replace(".zip", ""); File phantomjs = null; try { phantomjs = new File(archive.getParentFile().getAbsolutePath() + File.separator + fileNoExtension + File.separator + "bin" + File.separator).listFiles()[0]; } catch (Exception e) { String extension = IS_OS_WINDOWS ? ".exe" : ""; phantomjs = new File(archive.getParentFile().getAbsolutePath() + File.separator + fileNoExtension + File.separator + phantomName + extension); } target = new File(archive.getParentFile().getAbsolutePath() + File.separator + phantomjs.getName()); phantomjs.renameTo(target); File delete = new File(archive.getParentFile().getAbsolutePath() + File.separator + fileNoExtension); log.trace("Folder to be deleted: {}", delete); FileUtils.deleteDirectory(delete); } else { File[] ls = archive.getParentFile().listFiles(); for (File f : ls) { if (f.canExecute()) { target = f; break; } } } return target; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void reset() { config().reset(); mirrorLog = false; listVersions = null; versionToDownload = null; forcedArch = false; forcedOs = false; retryCount = 0; isLatest = true; isSnap = false; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void reset() { config().reset(); mirrorLog = false; versionToDownload = null; forcedArch = false; forcedOs = false; retryCount = 0; isLatest = true; isSnap = false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static final synchronized void download(URL url, String version, String export) throws IOException { File targetFile = new File(getTarget(version, url)); File binary; if (!targetFile.getParentFile().exists() || WdmConfig.getBoolean("wdm.override")) { log.debug("Downloading {} to {}", url, targetFile); FileUtils.copyURLToFile(url, targetFile); binary = unZip(targetFile); targetFile.delete(); } else { binary = targetFile.getParentFile().listFiles()[0]; log.debug("Using binary driver previously downloaded {}", binary); } if (export != null) { BrowserManager.exportDriver(export, binary.toString()); } } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code public static final synchronized void download(URL url, String version, String export) throws IOException { File targetFile = new File(getTarget(version, url)); File binary; if (!targetFile.getParentFile().exists() || WdmConfig.getBoolean("wdm.override")) { log.debug("Downloading {} to {}", url, targetFile); FileUtils.copyURLToFile(url, targetFile); if (export.contains("edge")) { binary = extractMsi(targetFile); } else { binary = unZip(targetFile); } targetFile.delete(); } else { binary = FileUtils .listFiles(targetFile.getParentFile(), null, true) .iterator().next(); log.debug("Using binary driver previously downloaded {}", binary); } if (export != null) { BrowserManager.exportDriver(export, binary.toString()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected List<URL> getDriversFromGitHub() throws IOException { List<URL> urls; URL driverUrl = getDriverUrl(); log.info("Reading {} to seek {}", driverUrl, getDriverName()); Optional<URL> mirrorUrl = getMirrorUrl(); if (mirrorUrl.isPresent() && config.isUseMirror()) { urls = getDriversFromMirror(mirrorUrl.get()); } else { String driverVersion = versionToDownload; try (BufferedReader reader = new BufferedReader( new InputStreamReader(openGitHubConnection(driverUrl)))) { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class); if (driverVersion != null) { releaseArray = new GitHubApi[] { getVersion(releaseArray, driverVersion) }; } urls = new ArrayList<>(); for (GitHubApi release : releaseArray) { if (release != null) { List<LinkedTreeMap<String, Object>> assets = release .getAssets(); for (LinkedTreeMap<String, Object> asset : assets) { urls.add(new URL(asset.get("browser_download_url") .toString())); } } } } } return urls; } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected List<URL> getDriversFromGitHub() throws IOException { List<URL> urls; URL driverUrl = getDriverUrl(); log.info("Reading {} to seek {}", driverUrl, getDriverName()); Optional<URL> mirrorUrl = getMirrorUrl(); if (mirrorUrl.isPresent() && config.isUseMirror()) { urls = getDriversFromMirror(mirrorUrl.get()); } else { String driverVersion = driverVersionToDownload; try (BufferedReader reader = new BufferedReader( new InputStreamReader(openGitHubConnection(driverUrl)))) { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class); if (driverVersion != null) { releaseArray = new GitHubApi[] { getVersionFromGitHub(releaseArray, driverVersion) }; } urls = new ArrayList<>(); for (GitHubApi release : releaseArray) { if (release != null) { List<LinkedTreeMap<String, Object>> assets = release .getAssets(); for (LinkedTreeMap<String, Object> asset : assets) { urls.add(new URL(asset.get("browser_download_url") .toString())); } } } } } return urls; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public BrowserManager useTaobaoMirror() { String taobaoUrl = null; try { taobaoUrl = WdmConfig.getString( WdmConfig.getString("wdm.chromeDriverTaobaoUrl")); driverUrl = new URL(taobaoUrl); } catch (MalformedURLException e) { String errorMessage = "Malformed URL " + taobaoUrl; log.error(errorMessage, e); throw new WebDriverManagerException(errorMessage, e); } return instance; } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public BrowserManager useTaobaoMirror() { return useTaobaoMirror("wdm.chromeDriverTaobaoUrl"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected List<URL> filterCandidateUrls(Architecture arch, String version, boolean getLatest) throws IOException { List<URL> urls = getDrivers(); List<URL> candidateUrls; log.trace("All URLs: {}", urls); boolean continueSearchingVersion; do { // Get the latest or concrete version candidateUrls = getLatest ? getLatest(urls, getDriverName()) : getVersion(urls, getDriverName(), version); log.trace("Candidate URLs: {}", candidateUrls); if (versionToDownload == null || this.getClass().equals(EdgeDriverManager.class)) { break; } // Filter by OS if (!getDriverName().contains("IEDriverServer")) { candidateUrls = urlFilter.filterByOs(candidateUrls, config().getOs()); } // Filter by architecture candidateUrls = urlFilter.filterByArch(candidateUrls, arch, forcedArch); // Extra round of filter phantomjs 2.5.0 in Linux if (config().getOs().equalsIgnoreCase("linux") && getDriverName().contains("phantomjs")) { candidateUrls = urlFilter.filterByDistro(candidateUrls, "2.5.0"); } // Filter by ignored version if (config().getIgnoreVersions() != null && !candidateUrls.isEmpty()) { candidateUrls = urlFilter.filterByIgnoredVersions(candidateUrls, config().getIgnoreVersions()); } // Find out if driver version has been found or not continueSearchingVersion = candidateUrls.isEmpty() && getLatest; if (continueSearchingVersion) { String driverNameString = listToString(getDriverName()); log.info( "No binary found for {} {} ... seeking another version", driverNameString, versionToDownload); urls = removeFromList(urls, versionToDownload); versionToDownload = null; } } while (continueSearchingVersion); return candidateUrls; } #location 25 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected List<URL> filterCandidateUrls(Architecture arch, String version, boolean getLatest) throws IOException { List<URL> urls = getDrivers(); List<URL> candidateUrls; log.trace("All URLs: {}", urls); boolean continueSearchingVersion; do { // Get the latest or concrete version candidateUrls = getLatest ? getLatest(urls, getDriverName()) : getVersion(urls, getDriverName(), version); log.trace("Candidate URLs: {}", candidateUrls); if (versionToDownload == null || this.getClass().equals(EdgeDriverManager.class)) { break; } // Filter by OS if (!getDriverName().contains("IEDriverServer")) { candidateUrls = urlFilter.filterByOs(candidateUrls, config().getOs()); } // Filter by architecture candidateUrls = urlFilter.filterByArch(candidateUrls, arch, forcedArch); // Filter by distro candidateUrls = filterByDistro(candidateUrls); // Filter by ignored versions candidateUrls = filterByIgnoredVersions(candidateUrls); // Find out if driver version has been found or not continueSearchingVersion = candidateUrls.isEmpty() && getLatest; if (continueSearchingVersion) { String driverNameString = listToString(getDriverName()); log.info( "No binary found for {} {} ... seeking another version", driverNameString, versionToDownload); urls = removeFromList(urls, versionToDownload); versionToDownload = null; } } while (continueSearchingVersion); return candidateUrls; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest) { version = detectDriverVersionFromBrowser(); } // For Chromium snap if (getDriverManagerType() == CHROMIUM && isSnap && ((ChromiumDriverManager) this).snapDriverExists()) { return; } getLatest = isNullOrEmpty(version); // Check latest version if (getLatest && !config().isUseBetaVersions()) { Optional<String> lastVersion = getLatestVersion(); getLatest = !lastVersion.isPresent(); if (!getLatest) { version = lastVersion.get(); } } // For Edge if (checkPreInstalledVersion(version)) { return; } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", getDriverName(), latestVersion); version = latestVersion; cache = true; } Optional<String> driverInCache = handleCache(arch, version, os, getLatest, cache); String versionStr = getLatest ? "(latest version)" : version; if (driverInCache.isPresent() && !config().isOverride()) { storeVersionToDownload(version); downloadedVersion = version; log.debug("Driver {} {} found in cache", getDriverName(), versionStr); exportDriver(driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String errorMessage = getDriverName() + " " + versionStr + " for " + os + arch.toString() + " not found in " + getDriverUrl(); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { handleException(e, arch, version); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest) { version = detectDriverVersionFromBrowser(); } // Special case for Chromium snap packages if (getDriverManagerType() == CHROMIUM && isSnap && ((ChromiumDriverManager) this).snapDriverExists()) { return; } getLatest = isNullOrEmpty(version); // Check latest version if (getLatest && !config().isUseBetaVersions()) { Optional<String> lastVersion = getLatestVersion(); getLatest = !lastVersion.isPresent(); if (!getLatest) { version = lastVersion.get(); } } // Special case for Edge if (checkPreInstalledVersion(version)) { return; } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", getDriverName(), latestVersion); version = latestVersion; cache = true; } // Manage driver downloadAndExport(arch, version, getLatest, cache, os); } catch (Exception e) { handleException(e, arch, version); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected File postDownload(File archive) { log.trace("Post processing for Opera: {}", archive); File extractFolder = archive.getParentFile() .listFiles(getFolderFilter())[0]; if (!extractFolder.isFile()) { log.trace("Opera extract folder (to be deleted): {}", extractFolder); File operadriver = extractFolder.listFiles()[0]; log.trace("Operadriver binary: {}", operadriver); File target = new File(archive.getParentFile().getAbsolutePath(), operadriver.getName()); log.trace("Operadriver target: {}", target); downloader.renameFile(operadriver, target); downloader.deleteFolder(extractFolder); return target; } else { return super.postDownload(archive); } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected File postDownload(File archive) { log.trace("Post processing for Opera: {}", archive); File extractFolder = archive.getParentFile() .listFiles(getFolderFilter())[0]; if (!extractFolder.isFile()) { log.trace("Opera extract folder (to be deleted): {}", extractFolder); File[] listFiles = extractFolder.listFiles(); int i = 0; File operadriver; do { operadriver = listFiles[0]; i++; } while (!config().isExecutable(operadriver) || i >= listFiles.length); log.trace("Operadriver binary: {}", operadriver); File target = new File(archive.getParentFile().getAbsolutePath(), operadriver.getName()); log.trace("Operadriver target: {}", target); downloader.renameFile(operadriver, target); downloader.deleteFolder(extractFolder); return target; } else { return super.postDownload(archive); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); if (isUnknown(driverVersion)) { preferenceKey = getDriverManagerType().getNameInLowerCase(); Optional<String> browserVersion = empty(); if (usePreferences() && preferences.checkKeyInPreferences(preferenceKey)) { browserVersion = Optional.of( preferences.getValueFromPreferences(preferenceKey)); } if (!browserVersion.isPresent()) { browserVersion = detectBrowserVersion(); } if (browserVersion.isPresent()) { // Calculate driverVersion using browserVersion preferenceKey = getDriverManagerType().getNameInLowerCase() + browserVersion.get(); if (usePreferences() && preferences .checkKeyInPreferences(preferenceKey)) { driverVersion = preferences .getValueFromPreferences(preferenceKey); } if (isUnknown(driverVersion)) { Optional<String> driverVersionFromRepository = getDriverVersionFromRepository( browserVersion); if (driverVersionFromRepository.isPresent()) { driverVersion = driverVersionFromRepository.get(); } } if (isUnknown(driverVersion)) { Optional<String> driverVersionFromProperties = getDriverVersionFromProperties( preferenceKey); if (driverVersionFromProperties.isPresent()) { driverVersion = driverVersionFromProperties.get(); } } else { log.info( "Using {} {} (since {} {} is installed in your machine)", getDriverName(), driverVersion, getDriverManagerType(), browserVersion.get()); } if (usePreferences()) { preferences.putValueInPreferencesIfEmpty( getDriverManagerType().getNameInLowerCase(), browserVersion.get()); preferences.putValueInPreferencesIfEmpty(preferenceKey, driverVersion); } if (isUnknown(driverVersion)) { log.debug( "The driver version for {} {} is unknown ... trying with latest", getDriverManagerType(), browserVersion.get()); } } // if driverVersion is still unknown, try with latest if (isUnknown(driverVersion)) { Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository(); if (latestDriverVersionFromRepository.isPresent()) { driverVersion = latestDriverVersionFromRepository.get(); } } } downloadAndExport(driverVersion); } catch (Exception e) { handleException(e, driverVersion); } } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); if (isUnknown(driverVersion)) { driverVersion = resolveDriverVersion(driverVersion); } downloadAndExport(driverVersion); } catch (Exception e) { handleException(e, driverVersion); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected List<URL> getCandidateUrls(String driverVersion) throws IOException { List<URL> urls = getDrivers(); List<URL> candidateUrls; log.trace("All URLs: {}", urls); boolean getLatest = isUnknown(driverVersion); Architecture arch = config().getArchitecture(); boolean continueSearchingVersion; do { // Get the latest or concrete version String shortDriverName = getShortDriverName(); candidateUrls = getLatest ? checkLatest(urls, shortDriverName) : getVersion(urls, shortDriverName, driverVersion); log.trace("Candidate URLs: {}", candidateUrls); if (versionToDownload == null) { break; } // Filter by OS if (!getDriverName().equalsIgnoreCase("IEDriverServer") && !getDriverName() .equalsIgnoreCase("selenium-server-standalone")) { candidateUrls = urlFilter.filterByOs(candidateUrls, config().getOs()); } // Filter by architecture candidateUrls = urlFilter.filterByArch(candidateUrls, arch, forcedArch); // Filter by distro candidateUrls = filterByDistro(candidateUrls); // Filter by ignored versions candidateUrls = filterByIgnoredVersions(candidateUrls); // Filter by beta candidateUrls = urlFilter.filterByBeta(candidateUrls, config().isUseBetaVersions()); // Find out if driver version has been found or not continueSearchingVersion = candidateUrls.isEmpty() && getLatest; if (continueSearchingVersion) { log.info( "No proper driver found for {} {} ... seeking another version", getDriverName(), versionToDownload); urls = removeFromList(urls, versionToDownload); versionToDownload = null; } } while (continueSearchingVersion); return candidateUrls; } #location 49 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected List<URL> getCandidateUrls(String driverVersion) throws IOException { List<URL> urls = getDrivers(); List<URL> candidateUrls; log.trace("All URLs: {}", urls); boolean getLatest = isUnknown(driverVersion); Architecture arch = config().getArchitecture(); boolean continueSearchingVersion; do { // Get the latest or concrete driver version String shortDriverName = getShortDriverName(); candidateUrls = getLatest ? filterDriverListByLatest(urls, shortDriverName) : filterDriverListByVersion(urls, shortDriverName, driverVersion); log.trace("Candidate URLs: {}", candidateUrls); if (driverVersionToDownload == null) { break; } // Filter by OS if (!getDriverName().equalsIgnoreCase("IEDriverServer") && !getDriverName() .equalsIgnoreCase("selenium-server-standalone")) { candidateUrls = urlFilter.filterByOs(candidateUrls, config().getOs()); } // Filter by architecture candidateUrls = urlFilter.filterByArch(candidateUrls, arch, forcedArch); // Filter by distro candidateUrls = filterByDistro(candidateUrls); // Filter by ignored driver versions candidateUrls = filterByIgnoredDriverVersions(candidateUrls); // Filter by beta candidateUrls = urlFilter.filterByBeta(candidateUrls, config().isUseBetaVersions()); // Find out if driver version has been found or not continueSearchingVersion = candidateUrls.isEmpty() && getLatest; if (continueSearchingVersion) { log.info( "No proper driver found for {} {} ... seeking another version", getDriverName(), driverVersionToDownload); urls = removeFromList(urls, driverVersionToDownload); driverVersionToDownload = null; } } while (continueSearchingVersion); return candidateUrls; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest) { Optional<String> optionalBrowserVersion = config() .isAvoidAutoVersion() ? empty() : getBrowserVersion(); if (optionalBrowserVersion.isPresent()) { String browserVersion = optionalBrowserVersion.get(); preferenceKey = getDriverManagerType().name().toLowerCase() + browserVersion; if (getLatest && !config.isOverride() && !config().isAvoidAutoVersion() && !config().isAvoidPreferences() && preferences .checkKeyInPreferences(preferenceKey)) { version = preferences .getValueFromPreferences(preferenceKey); } else { version = getVersionForInstalledBrowser( getDriverManagerType()); } getLatest = version.isEmpty(); } } // For Edge if (checkInsiderVersion(version)) { return; } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", getDriverName(), latestVersion); version = latestVersion; cache = true; } Optional<String> driverInCache = handleCache(arch, version, os, getLatest, cache); String versionStr = getLatest ? "(latest version)" : version; if (driverInCache.isPresent() && !config().isOverride()) { storeVersionToDownload(version); downloadedVersion = version; log.debug("Driver {} {} found in cache", getDriverName(), versionStr); exportDriver(driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String errorMessage = getDriverName() + " " + versionStr + " for " + os + arch.toString() + " not found in " + getDriverUrl(); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { handleException(e, arch, version); } } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest) { version = detectDriverVersionFromBrowser(); } getLatest = isNullOrEmpty(version); // For Edge if (checkInsiderVersion(version)) { return; } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", getDriverName(), latestVersion); version = latestVersion; cache = true; } Optional<String> driverInCache = handleCache(arch, version, os, getLatest, cache); String versionStr = getLatest ? "(latest version)" : version; if (driverInCache.isPresent() && !config().isOverride()) { storeVersionToDownload(version); downloadedVersion = version; log.debug("Driver {} {} found in cache", getDriverName(), versionStr); exportDriver(driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String errorMessage = getDriverName() + " " + versionStr + " for " + os + arch.toString() + " not found in " + getDriverUrl(); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { handleException(e, arch, version); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config().getTimeout()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(driverManagerType); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest && !config().isAvoidAutoVersion()) { version = getVersionForInstalledBrowser(driverManagerType); getLatest = version.isEmpty(); } if (version.equals("insiders")) { String systemRoot = System.getenv("SystemRoot"); File microsoftWebDriverFile = new File( systemRoot + File.separator + "System32" + File.separator + "MicrosoftWebDriver.exe"); if (microsoftWebDriverFile.exists()) { exportDriver(microsoftWebDriverFile.toString()); return; } else { retry = false; throw new WebDriverManagerException( "MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: " + "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0"); } } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", driverName, arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", driverName, latestVersion); version = latestVersion; cache = true; } Optional<String> driverInCache = handleCache(arch, version, os, getLatest, cache); String versionStr = getLatest ? "(latest version)" : version; if (driverInCache.isPresent() && !config().isOverride()) { versionToDownload = version; downloadedVersion = version; log.debug("Driver {} {} found in cache", driverName, versionStr); exportDriver(driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String errorMessage = driverName + " " + versionStr + " for " + os + arch.toString() + " not found in " + config().getDriverUrl(driverUrlKey); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { handleException(e, arch, version); } } #location 46 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config().getTimeout()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(driverManagerType); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest && !config().isAvoidAutoVersion()) { version = getVersionForInstalledBrowser(driverManagerType); getLatest = version.isEmpty(); } if (version.equals("insiders")) { String systemRoot = System.getenv("SystemRoot"); File microsoftWebDriverFile = new File( systemRoot + File.separator + "System32" + File.separator + "MicrosoftWebDriver.exe"); if (microsoftWebDriverFile.exists()) { exportDriver(microsoftWebDriverFile.toString()); return; } else { retry = false; throw new WebDriverManagerException( "MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: " + "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0"); } } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", driverName, arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", driverName, latestVersion); version = latestVersion; cache = true; } Optional<String> driverInCache = handleCache(arch, version, os, getLatest, cache); String versionStr = getLatest ? "(latest version)" : version; if (driverInCache.isPresent() && !config().isOverride()) { storeVersionToDownload(version); downloadedVersion = version; log.debug("Driver {} {} found in cache", driverName, versionStr); exportDriver(driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String errorMessage = driverName + " " + versionStr + " for " + os + arch.toString() + " not found in " + config().getDriverUrl(driverUrlKey); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { handleException(e, arch, version); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void exportDriver(String variableValue) { downloadedVersion = versionToDownload; binaryPath = variableValue; Optional<String> exportParameter = getExportParameter(); if (!config.isAvoidExport() && exportParameter.isPresent()) { String variableName = exportParameter.get(); log.info("Exporting {} as {}", variableName, variableValue); System.setProperty(variableName, variableValue); } else { log.info("Resulting binary {}", variableValue); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void exportDriver(String variableValue) { downloadedDriverVersion = driverVersionToDownload; binaryPath = variableValue; Optional<String> exportParameter = getExportParameter(); if (!config.isAvoidExport() && exportParameter.isPresent()) { String variableName = exportParameter.get(); log.info("Exporting {} as {}", variableName, variableValue); System.setProperty(variableName, variableValue); } else { log.info("Resulting binary {}", variableValue); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest) { version = detectDriverVersionFromBrowser(); } // For Chromium snap if (getDriverManagerType() == CHROMIUM && isSnap && ((ChromiumDriverManager) this).snapDriverExists()) { return; } getLatest = isNullOrEmpty(version); // Check latest version if (getLatest && !config().isUseBetaVersions()) { Optional<String> lastVersion = getLatestVersion(); getLatest = !lastVersion.isPresent(); if (!getLatest) { version = lastVersion.get(); } } // For Edge if (checkPreInstalledVersion(version)) { return; } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", getDriverName(), latestVersion); version = latestVersion; cache = true; } Optional<String> driverInCache = handleCache(arch, version, os, getLatest, cache); String versionStr = getLatest ? "(latest version)" : version; if (driverInCache.isPresent() && !config().isOverride()) { storeVersionToDownload(version); downloadedVersion = version; log.debug("Driver {} {} found in cache", getDriverName(), versionStr); exportDriver(driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String errorMessage = getDriverName() + " " + versionStr + " for " + os + arch.toString() + " not found in " + getDriverUrl(); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { handleException(e, arch, version); } } #location 68 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest) { version = detectDriverVersionFromBrowser(); } // Special case for Chromium snap packages if (getDriverManagerType() == CHROMIUM && isSnap && ((ChromiumDriverManager) this).snapDriverExists()) { return; } getLatest = isNullOrEmpty(version); // Check latest version if (getLatest && !config().isUseBetaVersions()) { Optional<String> lastVersion = getLatestVersion(); getLatest = !lastVersion.isPresent(); if (!getLatest) { version = lastVersion.get(); } } // Special case for Edge if (checkPreInstalledVersion(version)) { return; } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", getDriverName(), latestVersion); version = latestVersion; cache = true; } // Manage driver downloadAndExport(arch, version, getLatest, cache, os); } catch (Exception e) { handleException(e, arch, version); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static File unBZip2(File archive, String export) throws IOException { Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.BZIP2); archiver.extract(archive, archive.getParentFile()); log.trace("Unbzip2 {}", archive); File target; String phantomjsName = "phantomjs"; if (export.contains(phantomjsName)) { String fileNoExtension = archive.getName().replace(".tar.bz2", ""); File phantomjs = new File(archive.getParentFile().getAbsolutePath() + File.separator + fileNoExtension + File.separator + "bin" + File.separator + phantomjsName); target = new File(archive.getParentFile().getAbsolutePath() + File.separator + phantomjsName); phantomjs.renameTo(target); File delete = new File(archive.getParentFile().getAbsolutePath() + File.separator + fileNoExtension); log.trace("Folder to be deleted: {}", delete); FileUtils.deleteDirectory(delete); } else { target = archive.getParentFile().listFiles()[0]; } return target; } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code public static File unBZip2(File archive, String export) throws IOException { Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.BZIP2); archiver.extract(archive, archive.getParentFile()); log.trace("Unbzip2 {}", archive); File target = checkPhantom(archive, export); return target; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected List<String> getBetaVersions() { List<String> betaVersions = new ArrayList<>(); DriverManagerType[] browsersWithBeta = { CHROME }; for (DriverManagerType driverManagerType : browsersWithBeta) { String key = driverManagerType.name().toLowerCase() + BETA; Optional<String> betaVersionString = getDriverVersionForBrowserFromProperties( key); if (betaVersionString.isPresent()) { betaVersions.addAll( Arrays.asList(betaVersionString.get().split(","))); } } return betaVersions; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected List<String> getBetaVersions() { List<String> betaVersions = new ArrayList<>(); DriverManagerType[] browsersWithBeta = { CHROME }; for (DriverManagerType driverManagerType : browsersWithBeta) { String key = driverManagerType.name().toLowerCase() + BETA; Optional<String> betaVersionString = getDriverVersionForBrowserFromProperties( key, true); if (betaVersionString.isPresent()) { betaVersions.addAll( Arrays.asList(betaVersionString.get().split(","))); } } return betaVersions; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); if (isUnknown(driverVersion)) { preferenceKey = getDriverManagerType().getNameInLowerCase(); Optional<String> browserVersion = empty(); if (usePreferences() && preferences.checkKeyInPreferences(preferenceKey)) { browserVersion = Optional.of( preferences.getValueFromPreferences(preferenceKey)); } if (!browserVersion.isPresent()) { browserVersion = detectBrowserVersion(); } if (browserVersion.isPresent()) { // Calculate driverVersion using browserVersion preferenceKey = getDriverManagerType().getNameInLowerCase() + browserVersion.get(); if (usePreferences() && preferences .checkKeyInPreferences(preferenceKey)) { driverVersion = preferences .getValueFromPreferences(preferenceKey); } if (isUnknown(driverVersion)) { Optional<String> driverVersionFromRepository = getDriverVersionFromRepository( browserVersion); if (driverVersionFromRepository.isPresent()) { driverVersion = driverVersionFromRepository.get(); } } if (isUnknown(driverVersion)) { Optional<String> driverVersionFromProperties = getDriverVersionFromProperties( preferenceKey); if (driverVersionFromProperties.isPresent()) { driverVersion = driverVersionFromProperties.get(); } } else { log.info( "Using {} {} (since {} {} is installed in your machine)", getDriverName(), driverVersion, getDriverManagerType(), browserVersion.get()); } if (usePreferences()) { preferences.putValueInPreferencesIfEmpty( getDriverManagerType().getNameInLowerCase(), browserVersion.get()); preferences.putValueInPreferencesIfEmpty(preferenceKey, driverVersion); } if (isUnknown(driverVersion)) { log.debug( "The driver version for {} {} is unknown ... trying with latest", getDriverManagerType(), browserVersion.get()); } } // if driverVersion is still unknown, try with latest if (isUnknown(driverVersion)) { Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository(); if (latestDriverVersionFromRepository.isPresent()) { driverVersion = latestDriverVersionFromRepository.get(); } } } downloadAndExport(driverVersion); } catch (Exception e) { handleException(e, driverVersion); } } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); if (isUnknown(driverVersion)) { driverVersion = resolveDriverVersion(driverVersion); } downloadAndExport(driverVersion); } catch (Exception e) { handleException(e, driverVersion); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized void download(URL url, String version, String export, List<String> driverName) throws IOException { File targetFile = new File(getTarget(version, url)); File binary = null; // Check if binary exists boolean download = !targetFile.getParentFile().exists() || (targetFile.getParentFile().exists() && targetFile.getParentFile().list().length == 0) || override; if (!download) { // Check if existing binary is valid Collection<File> listFiles = FileUtils .listFiles(targetFile.getParentFile(), null, true); for (File file : listFiles) { for (String s : driverName) { if (file.getName().startsWith(s) && file.canExecute()) { binary = file; log.debug( "Using binary driver previously downloaded {}", binary); download = false; break; } else { download = true; } } if (!download) { break; } } } if (download) { File temporaryFile = new File(targetFile.getParentFile(), UUID.randomUUID().toString()); log.info("Downloading {} to {}", url, temporaryFile); WdmHttpClient.Get get = new WdmHttpClient.Get(url) .addHeader("User-Agent", "Mozilla/5.0") .addHeader("Connection", "keep-alive"); try { FileUtils.copyInputStreamToFile( httpClient.execute(get).getContent(), temporaryFile); } catch (IOException e) { temporaryFile.delete(); throw e; } log.info("Renaming {} to {}", temporaryFile, targetFile); temporaryFile.renameTo(targetFile); if (!export.contains("edge")) { binary = extract(targetFile, export); } else { binary = targetFile; } if (targetFile.getName().toLowerCase().endsWith(".msi")) { binary = extractMsi(targetFile); } } if (export != null) { browserManager.exportDriver(export, binary.toString()); } } #location 66 #vulnerability type NULL_DEREFERENCE
#fixed code public synchronized void download(URL url, String version, String export, List<String> driverName) throws IOException { File targetFile = new File(getTarget(version, url)); File binary = null; // Check if binary exists boolean download = !targetFile.getParentFile().exists() || (targetFile.getParentFile().exists() && targetFile.getParentFile().list().length == 0) || override; if (download) { File temporaryFile = new File(targetFile.getParentFile(), randomUUID().toString()); log.info("Downloading {} to {}", url, temporaryFile); WdmHttpClient.Get get = new WdmHttpClient.Get(url) .addHeader("User-Agent", "Mozilla/5.0") .addHeader("Connection", "keep-alive"); try { copyInputStreamToFile(httpClient.execute(get).getContent(), temporaryFile); } catch (IOException e) { temporaryFile.delete(); throw e; } log.info("Renaming {} to {}", temporaryFile, targetFile); temporaryFile.renameTo(targetFile); if (!export.contains("edge")) { binary = extract(targetFile, export); } else { binary = targetFile; } if (targetFile.getName().toLowerCase().endsWith(".msi")) { binary = extractMsi(targetFile); } } else { // Check if existing binary is valid Collection<File> listFiles = listFiles(targetFile.getParentFile(), null, true); for (File file : listFiles) { for (String s : driverName) { if (file.getName().startsWith(s) && file.canExecute()) { binary = file; log.debug( "Using binary driver previously downloaded {}", binary); download = false; break; } else { download = true; } } if (!download) { break; } } } if (export != null && binary != null) { browserManager.exportDriver(export, binary.toString()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void reset() { useBetaVersions = getBoolean("wdm.useBetaVersions"); mirrorLog = false; isForcingCache = false; isForcingDownload = false; listVersions = null; architecture = null; driverUrl = null; versionToDownload = null; version = null; proxyValue = null; binaryPath = null; proxyUser = null; proxyPass = null; ignoredVersions = null; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void reset() { useBetaVersions = false; mirrorLog = false; isForcingCache = false; isForcingDownload = false; listVersions = null; architecture = null; driverUrl = null; version = null; proxyValue = null; proxyUser = null; proxyPass = null; ignoredVersions = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void handleDriver(URL url, String driver, List<URL> out) { if (!useBeta && url.getFile().toLowerCase().contains("beta")) { return; } if (url.getFile().contains(driver)) { String currentVersion = getCurrentVersion(url, driver); if (currentVersion.equalsIgnoreCase(driver)) { return; } if (versionToDownload == null) { versionToDownload = currentVersion; } if (versionCompare(currentVersion, versionToDownload) > 0) { versionToDownload = currentVersion; out.clear(); } if (url.getFile().contains(versionToDownload)) { out.add(url); } } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void handleDriver(URL url, String driver, List<URL> out) { if (!config().isUseBetaVersions() && url.getFile().toLowerCase().contains("beta")) { return; } if (url.getFile().contains(driver)) { String currentVersion = getCurrentVersion(url, driver); if (currentVersion.equalsIgnoreCase(driver)) { return; } if (versionToDownload == null) { versionToDownload = currentVersion; } if (versionCompare(currentVersion, versionToDownload) > 0) { versionToDownload = currentVersion; out.clear(); } if (url.getFile().contains(versionToDownload)) { out.add(url); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public BrowserManager useTaobaoMirror() { String taobaoUrl = null; try { taobaoUrl = getString(getString("wdm.operaDriverTaobaoUrl")); driverUrl = new URL(taobaoUrl); } catch (MalformedURLException e) { String errorMessage = "Malformed URL " + taobaoUrl; log.error(errorMessage, e); throw new WebDriverManagerException(errorMessage, e); } return instance; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public BrowserManager useTaobaoMirror() { return useTaobaoMirror("wdm.operaDriverTaobaoUrl"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected Optional<String> handleCache(Architecture arch, String version, String os, boolean getLatest, boolean cache) { Optional<String> driverInCache = empty(); if (cache || !getLatest) { driverInCache = getDriverFromCache(version, arch, os); } if (!version.isEmpty()) { versionToDownload = version; } return driverInCache; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected Optional<String> handleCache(Architecture arch, String version, String os, boolean getLatest, boolean cache) { Optional<String> driverInCache = empty(); if (cache || !getLatest) { driverInCache = getDriverFromCache(version, arch, os); } if (!version.isEmpty()) { storeVersionToDownload(version); } return driverInCache; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void reset() { config().reset(); mirrorLog = false; listVersions = null; versionToDownload = null; downloadedVersion = null; driverManagerType = null; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void reset() { config().reset(); mirrorLog = false; listVersions = null; versionToDownload = null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config().getProxyValue(), config().getProxyUser(), config().getProxyPass()); httpClient.setTimeout(config().getTimeout()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(driverManagerType); urlFilter = new UrlFilter(); boolean getLatest = version == null || version.isEmpty() || version.equalsIgnoreCase(LATEST.name()) || version.equalsIgnoreCase(NOT_SPECIFIED.name()); boolean cache = config().isForcingCache() || !isNetAvailable(); log.trace(">> Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); Optional<String> driverInCache = handleCache(arch, version, getLatest, cache); if (driverInCache.isPresent()) { versionToDownload = version; downloadedVersion = version; log.debug("Driver for {} {} found in cache {}", getDriverName(), version, driverInCache.get()); exportDriver(config().getExportParameter(exportParameterKey), driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String versionStr = getLatest ? "(latest version)" : version; String errorMessage = getDriverName() + " " + versionStr + " for " + config().getMyOsName() + arch.toString() + " not found in " + config().getDriverUrl(driverUrlKey); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { e.printStackTrace(); handleException(e, arch, version); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config().getProxyValue(), config().getProxyUser(), config().getProxyPass()); httpClient.setTimeout(config().getTimeout()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(driverManagerType); urlFilter = new UrlFilter(); boolean getLatest = version == null || version.isEmpty() || version.equalsIgnoreCase(LATEST.name()) || version.equalsIgnoreCase(NOT_SPECIFIED.name()); boolean cache = config().isForcingCache() || !isNetAvailable(); log.trace(">> Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); Optional<String> driverInCache = handleCache(arch, version, getLatest, cache); if (driverInCache.isPresent()) { versionToDownload = version; downloadedVersion = version; log.debug("Driver for {} {} found in cache {}", getDriverName(), version, driverInCache.get()); exportDriver(config().getExportParameter(exportParameterKey), driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String versionStr = getLatest ? "(latest version)" : version; String errorMessage = getDriverName() + " " + versionStr + " for " + config().getMyOsName() + arch.toString() + " not found in " + config().getDriverUrl(driverUrlKey); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { handleException(e, arch, version); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void exportDriver(String variableValue) { binaryPath = variableValue; Optional<String> exportParameter = getExportParameter(); if (!config.isAvoidExport() && exportParameter.isPresent()) { String variableName = exportParameter.get(); log.info("Exporting {} as {}", variableName, variableValue); System.setProperty(variableName, variableValue); } else { log.info("Driver location: {}", variableValue); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void exportDriver(String variableValue) { driverPath = variableValue; Optional<String> exportParameter = getExportParameter(); if (!config.isAvoidExport() && exportParameter.isPresent()) { String variableName = exportParameter.get(); log.info("Exporting {} as {}", variableName, variableValue); System.setProperty(variableName, variableValue); } else { log.info("Driver location: {}", variableValue); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); if (isUnknown(driverVersion)) { preferenceKey = getDriverManagerType().getNameInLowerCase(); Optional<String> browserVersion = empty(); if (usePreferences() && preferences.checkKeyInPreferences(preferenceKey)) { browserVersion = Optional.of( preferences.getValueFromPreferences(preferenceKey)); } if (!browserVersion.isPresent()) { browserVersion = detectBrowserVersion(); } if (browserVersion.isPresent()) { // Calculate driverVersion using browserVersion preferenceKey = getDriverManagerType().getNameInLowerCase() + browserVersion.get(); if (usePreferences() && preferences .checkKeyInPreferences(preferenceKey)) { driverVersion = preferences .getValueFromPreferences(preferenceKey); } if (isUnknown(driverVersion)) { Optional<String> driverVersionFromRepository = getDriverVersionFromRepository( browserVersion); if (driverVersionFromRepository.isPresent()) { driverVersion = driverVersionFromRepository.get(); } } if (isUnknown(driverVersion)) { Optional<String> driverVersionFromProperties = getDriverVersionFromProperties( preferenceKey); if (driverVersionFromProperties.isPresent()) { driverVersion = driverVersionFromProperties.get(); } } else { log.info( "Using {} {} (since {} {} is installed in your machine)", getDriverName(), driverVersion, getDriverManagerType(), browserVersion.get()); } if (usePreferences()) { preferences.putValueInPreferencesIfEmpty( getDriverManagerType().getNameInLowerCase(), browserVersion.get()); preferences.putValueInPreferencesIfEmpty(preferenceKey, driverVersion); } if (isUnknown(driverVersion)) { log.debug( "The driver version for {} {} is unknown ... trying with latest", getDriverManagerType(), browserVersion.get()); } } // if driverVersion is still unknown, try with latest if (isUnknown(driverVersion)) { Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository(); if (latestDriverVersionFromRepository.isPresent()) { driverVersion = latestDriverVersionFromRepository.get(); } } } downloadAndExport(driverVersion); } catch (Exception e) { handleException(e, driverVersion); } } #location 51 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); if (isUnknown(driverVersion)) { driverVersion = resolveDriverVersion(driverVersion); } downloadAndExport(driverVersion); } catch (Exception e) { handleException(e, driverVersion); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest) { version = detectDriverVersionFromBrowser(); } // For Chromium snap if (getDriverManagerType() == CHROMIUM && isSnap && ((ChromiumDriverManager) this).snapDriverExists()) { return; } getLatest = isNullOrEmpty(version); // Check latest version if (getLatest && !config().isUseBetaVersions()) { Optional<String> lastVersion = getLatestVersion(); getLatest = !lastVersion.isPresent(); if (!getLatest) { version = lastVersion.get(); } } // For Edge if (checkPreInstalledVersion(version)) { return; } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", getDriverName(), latestVersion); version = latestVersion; cache = true; } Optional<String> driverInCache = handleCache(arch, version, os, getLatest, cache); String versionStr = getLatest ? "(latest version)" : version; if (driverInCache.isPresent() && !config().isOverride()) { storeVersionToDownload(version); downloadedVersion = version; log.debug("Driver {} {} found in cache", getDriverName(), versionStr); exportDriver(driverInCache.get()); } else { List<URL> candidateUrls = filterCandidateUrls(arch, version, getLatest); if (candidateUrls.isEmpty()) { String errorMessage = getDriverName() + " " + versionStr + " for " + os + arch.toString() + " not found in " + getDriverUrl(); log.error(errorMessage); throw new WebDriverManagerException(errorMessage); } downloadCandidateUrls(candidateUrls); } } catch (Exception e) { handleException(e, arch, version); } } #location 53 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest) { version = detectDriverVersionFromBrowser(); } // Special case for Chromium snap packages if (getDriverManagerType() == CHROMIUM && isSnap && ((ChromiumDriverManager) this).snapDriverExists()) { return; } getLatest = isNullOrEmpty(version); // Check latest version if (getLatest && !config().isUseBetaVersions()) { Optional<String> lastVersion = getLatestVersion(); getLatest = !lastVersion.isPresent(); if (!getLatest) { version = lastVersion.get(); } } // Special case for Edge if (checkPreInstalledVersion(version)) { return; } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", getDriverName(), latestVersion); version = latestVersion; cache = true; } // Manage driver downloadAndExport(arch, version, getLatest, cache, os); } catch (Exception e) { handleException(e, arch, version); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected List<URL> checkLatest(List<URL> list, String driver) { log.trace("Checking the lastest version of {} with URL list {}", driver, list); List<URL> out = new ArrayList<>(); List<URL> copyOfList = new ArrayList<>(list); List<String> betaVersions = getBetaVersions(); for (URL url : copyOfList) { try { handleDriver(url, driver, out, betaVersions); } catch (Exception e) { log.trace("There was a problem with URL {} : {}", url, e.getMessage()); list.remove(url); } } storeVersionToDownload(versionToDownload); latestVersion = versionToDownload; log.info("Latest version of {} is {}", driver, versionToDownload); return out; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected List<URL> checkLatest(List<URL> list, String driver) { log.trace("Checking the lastest version of {} with URL list {}", driver, list); List<URL> out = new ArrayList<>(); List<URL> copyOfList = new ArrayList<>(list); for (URL url : copyOfList) { try { handleDriver(url, driver, out); } catch (Exception e) { log.trace("There was a problem with URL {} : {}", url, e.getMessage()); list.remove(url); } } storeVersionToDownload(versionToDownload); latestVersion = versionToDownload; log.info("Latest version of {} is {}", driver, versionToDownload); return out; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void handleDriver(URL url, String driver, List<URL> out) { if (!useBetaVersions && url.getFile().toLowerCase().contains("beta")) { return; } if (url.getFile().contains(driver)) { String currentVersion = getCurrentVersion(url, driver); if (currentVersion.equalsIgnoreCase(driver)) { return; } if (versionToDownload == null) { versionToDownload = currentVersion; } if (versionCompare(currentVersion, versionToDownload) > 0) { versionToDownload = currentVersion; out.clear(); } if (url.getFile().contains(versionToDownload)) { out.add(url); } } } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void handleDriver(URL url, String driver, List<URL> out) { if (!useBetaVersions && !getBoolean("wdm.useBetaVersions") && url.getFile().toLowerCase().contains("beta")) { return; } if (url.getFile().contains(driver)) { String currentVersion = getCurrentVersion(url, driver); if (currentVersion.equalsIgnoreCase(driver)) { return; } if (versionToDownload == null) { versionToDownload = currentVersion; } if (versionCompare(currentVersion, versionToDownload) > 0) { versionToDownload = currentVersion; out.clear(); } if (url.getFile().contains(versionToDownload)) { out.add(url); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<URL> getDrivers() throws IOException { URL driverUrl = getDriverUrl(); String driverVersion = versionToDownload; BufferedReader reader = new BufferedReader( new InputStreamReader(openGitHubConnection(driverUrl))); GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class); GitHubApi release; if (driverVersion == null || driverVersion.isEmpty() || driverVersion .equalsIgnoreCase(DriverVersion.LATEST.name())) { log.debug("Connecting to {} to check latest OperaDriver release", driverUrl); driverVersion = releaseArray[0].getName(); log.debug("Latest driver version: {}", driverVersion); release = releaseArray[0]; } else { release = getVersion(releaseArray, driverVersion); } if (release == null) { throw new RuntimeException("Version " + driverVersion + " is not available for OperaDriver"); } List<LinkedTreeMap<String, Object>> assets = release.getAssets(); List<URL> urls = new ArrayList<>(); for (LinkedTreeMap<String, Object> asset : assets) { urls.add(new URL(asset.get("browser_download_url").toString())); } reader.close(); return urls; } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code @Override public List<URL> getDrivers() throws IOException { URL driverUrl = getDriverUrl(); String driverVersion = versionToDownload; BufferedReader reader = new BufferedReader( new InputStreamReader(openGitHubConnection(driverUrl))); GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class); if (driverVersion != null) { releaseArray = new GitHubApi[] { getVersion(releaseArray, driverVersion) }; } List<URL> urls = new ArrayList<>(); for (GitHubApi release : releaseArray) { if (release != null) { List<LinkedTreeMap<String, Object>> assets = release .getAssets(); for (LinkedTreeMap<String, Object> asset : assets) { urls.add(new URL( asset.get("browser_download_url").toString())); } } } reader.close(); return urls; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void handleException(Exception e, Architecture arch, String version) { if (!config().isForcingCache()) { config().setForcingCache(true); log.warn( "There was an error managing {} {} ({}) ... trying again forcing to use cache", getDriverName(), version, e.getMessage()); manage(arch, version); } else { throw new WebDriverManagerException(e); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void handleException(Exception e, Architecture arch, String version) { String errorMessage = String.format( "There was an error managing %s %s (%s)", getDriverName(), version, e.getMessage()); if (!config().isForcingCache()) { config().setForcingCache(true); log.warn("{} ... trying again forcing to use cache", errorMessage); manage(arch, version); } else { log.error("{}", errorMessage, e); throw new WebDriverManagerException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected List<URL> getVersion(List<URL> list, String driver, String version) { List<URL> out = new ArrayList<>(); if (getDriverName().contains("msedgedriver")) { int i = listVersions.indexOf(version); if (i != -1) { out.add(list.get(i)); } } for (URL url : list) { if (url.getFile().contains(driver) && url.getFile().contains(version) && !url.getFile().contains("-symbols")) { out.add(url); } } if (versionToDownload != null && !versionToDownload.equals(version)) { versionToDownload = version; log.info("Using {} {}", driver, version); } return out; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected List<URL> getVersion(List<URL> list, String driver, String version) { List<URL> out = new ArrayList<>(); for (URL url : list) { if (url.getFile().contains(driver) && url.getFile().contains(version) && !url.getFile().contains("-symbols")) { out.add(url); } } if (versionToDownload != null && !versionToDownload.equals(version)) { versionToDownload = version; log.info("Using {} {}", driver, version); } return out; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void reset() { config().reset(); mirrorLog = false; listVersions = null; versionToDownload = null; forcedArch = false; retry = true; isLatest = true; browserBinaryPath = null; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void reset() { config().reset(); mirrorLog = false; listVersions = null; versionToDownload = null; forcedArch = false; retry = true; isLatest = true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public WebDriverManager useTaobaoMirror(String taobaoUrl) { driverUrl = getUrl(taobaoUrl); return instance; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public WebDriverManager useTaobaoMirror(String taobaoUrl) { driverUrl = getUrl(taobaoUrl); return instanceMap.get(driverManagerType); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void handleException(Exception e, Architecture arch, String version) { String versionStr = isNullOrEmpty(version) ? "(latest version)" : version; String errorMessage = String.format( "There was an error managing %s %s (%s)", getDriverName(), versionStr, e.getMessage()); if (!config().isForceCache() && retry) { config().setForceCache(true); config().setUseMirror(true); retry = false; log.warn("{} ... trying again using cache and mirror", errorMessage); manage(arch, version); } else { log.error("{}", errorMessage, e); throw new WebDriverManagerException(e); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void handleException(Exception e, Architecture arch, String version) { String versionStr = isNullOrEmpty(version) ? "(latest version)" : version; String errorMessage = String.format( "There was an error managing %s %s (%s)", getDriverName(), versionStr, e.getMessage()); if (!config().isForceCache() && retryCount == 0) { config().setForceCache(true); config().setUseMirror(true); retryCount++; log.warn("{} ... trying again using mirror", errorMessage); manage(arch, version); } else if (retryCount == 1) { config().setAvoidAutoVersion(true); version = ""; retryCount++; log.warn("{} ... trying again using latest from cache", errorMessage); manage(arch, version); } else { log.error("{}", errorMessage, e); throw new WebDriverManagerException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected List<URL> getDriversFromGitHub() throws IOException { List<URL> urls; URL driverUrl = getDriverUrl(); log.info("Reading {} to seek {}", driverUrl, getDriverName()); Optional<URL> mirrorUrl = getMirrorUrl(); if (mirrorUrl.isPresent() && config.isUseMirror()) { urls = getDriversFromMirror(mirrorUrl.get()); } else { String driverVersion = versionToDownload; try (BufferedReader reader = new BufferedReader( new InputStreamReader(openGitHubConnection(driverUrl)))) { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class); if (driverVersion != null) { releaseArray = new GitHubApi[] { getVersion(releaseArray, driverVersion) }; } urls = new ArrayList<>(); for (GitHubApi release : releaseArray) { if (release != null) { List<LinkedTreeMap<String, Object>> assets = release .getAssets(); for (LinkedTreeMap<String, Object> asset : assets) { urls.add(new URL(asset.get("browser_download_url") .toString())); } } } } } return urls; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected List<URL> getDriversFromGitHub() throws IOException { List<URL> urls; URL driverUrl = getDriverUrl(); log.info("Reading {} to seek {}", driverUrl, getDriverName()); Optional<URL> mirrorUrl = getMirrorUrl(); if (mirrorUrl.isPresent() && config.isUseMirror()) { urls = getDriversFromMirror(mirrorUrl.get()); } else { String driverVersion = driverVersionToDownload; try (BufferedReader reader = new BufferedReader( new InputStreamReader(openGitHubConnection(driverUrl)))) { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class); if (driverVersion != null) { releaseArray = new GitHubApi[] { getVersionFromGitHub(releaseArray, driverVersion) }; } urls = new ArrayList<>(); for (GitHubApi release : releaseArray) { if (release != null) { List<LinkedTreeMap<String, Object>> assets = release .getAssets(); for (LinkedTreeMap<String, Object> asset : assets) { urls.add(new URL(asset.get("browser_download_url") .toString())); } } } } } return urls; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest) { version = detectDriverVersionFromBrowser(); } // Special case for Chromium snap packages if (getDriverManagerType() == CHROMIUM && isSnap && ((ChromiumDriverManager) this).snapDriverExists()) { return; } getLatest = isNullOrEmpty(version); // Check latest version if (getLatest && !config().isUseBetaVersions()) { Optional<String> lastVersion = getLatestVersion(); getLatest = !lastVersion.isPresent(); if (!getLatest) { version = lastVersion.get(); } } // Special case for Edge if (checkPreInstalledVersion(version)) { return; } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", getDriverName(), latestVersion); version = latestVersion; cache = true; } // Manage driver downloadAndExport(arch, version, getLatest, cache, os); } catch (Exception e) { handleException(e, arch, version); } } #location 32 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(Architecture arch, String version) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); boolean getLatest = isVersionLatest(version); boolean cache = config().isForceCache(); if (getLatest) { version = detectDriverVersionFromBrowser(); } // Special case for Chromium snap packages if (getDriverManagerType() == CHROMIUM && isSnap && ((ChromiumDriverManager) this).snapDriverExists()) { return; } getLatest = isNullOrEmpty(version); // Check latest version if (getLatest && !config().isUseBetaVersions()) { Optional<String> lastVersion = getLatestVersion(); getLatest = !lastVersion.isPresent(); if (!getLatest) { version = lastVersion.get(); } } String os = config().getOs(); log.trace("Managing {} arch={} version={} getLatest={} cache={}", getDriverName(), arch, version, getLatest, cache); if (getLatest && latestVersion != null) { log.debug("Latest version of {} is {} (recently resolved)", getDriverName(), latestVersion); version = latestVersion; cache = true; } // Manage driver downloadAndExport(arch, version, getLatest, cache, os); } catch (Exception e) { handleException(e, arch, version); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public BrowserManager useTaobaoMirror() { String taobaoUrl = null; try { taobaoUrl = getString(getString("wdm.phantomjsDriverTaobaoUrl")); driverUrl = new URL(taobaoUrl); } catch (MalformedURLException e) { String errorMessage = "Malformed URL " + taobaoUrl; log.error(errorMessage, e); throw new WebDriverManagerException(errorMessage, e); } return instance; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public BrowserManager useTaobaoMirror() { return useTaobaoMirror("wdm.phantomjsDriverTaobaoUrl"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected File postDownload(File archive) { log.trace("Post processing for Opera: {}", archive); File extractFolder = archive.getParentFile().listFiles()[0]; if (!extractFolder.isFile()) { log.trace("Opera extract folder (to be deleted): {}", extractFolder); File operadriver = extractFolder.listFiles()[0]; log.trace("Operadriver binary: {}", operadriver); File target = new File(archive.getParentFile().getAbsolutePath(), operadriver.getName()); log.trace("Operadriver target: {}", target); downloader.renameFile(operadriver, target); downloader.deleteFolder(extractFolder); return target; } else { return super.postDownload(archive); } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected File postDownload(File archive) { log.trace("Post processing for Opera: {}", archive); final String operaDriverName = getDriverName().get(0); FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return dir.isDirectory() && name.toLowerCase().startsWith(operaDriverName + "_"); } }; File extractFolder = archive.getParentFile().listFiles(filter)[0]; if (!extractFolder.isFile()) { log.trace("Opera extract folder (to be deleted): {}", extractFolder); File operadriver = extractFolder.listFiles()[0]; log.trace("Operadriver binary: {}", operadriver); File target = new File(archive.getParentFile().getAbsolutePath(), operadriver.getName()); log.trace("Operadriver target: {}", target); downloader.renameFile(operadriver, target); downloader.deleteFolder(extractFolder); return target; } else { return super.postDownload(archive); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public WebDriverManager browserPath(String browserPath) { browserBinaryPath = browserPath; return instanceMap.get(driverManagerType); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public WebDriverManager browserPath(String browserPath) { config().setBinaryPath(browserPath); return instanceMap.get(driverManagerType); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected String resolveDriverVersion(String driverVersion) { preferenceKey = getKeyForPreferences(); Optional<String> browserVersion = empty(); browserVersion = getValueFromPreferences(browserVersion); if (!browserVersion.isPresent()) { browserVersion = detectBrowserVersion(); } if (browserVersion.isPresent()) { preferenceKey = getKeyForPreferences() + browserVersion.get(); driverVersion = preferences.getValueFromPreferences(preferenceKey); Optional<String> optionalDriverVersion = empty(); if (isUnknown(driverVersion)) { optionalDriverVersion = getDriverVersionFromRepository( browserVersion); } if (isUnknown(driverVersion)) { optionalDriverVersion = getDriverVersionFromProperties( preferenceKey); } if (optionalDriverVersion.isPresent()) { driverVersion = optionalDriverVersion.get(); } if (isUnknown(driverVersion)) { log.debug( "The driver version for {} {} is unknown ... trying with latest", getDriverManagerType(), browserVersion.get()); } else if (!isUnknown(driverVersion)) { log.info( "Using {} {} (since {} {} is installed in your machine)", getDriverName(), driverVersion, getDriverManagerType(), browserVersion.get()); storeInPreferences(driverVersion, browserVersion.get()); } } // if driverVersion is still unknown, try with latest if (isUnknown(driverVersion)) { Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository(); if (latestDriverVersionFromRepository.isPresent()) { driverVersion = latestDriverVersionFromRepository.get(); } } return driverVersion; } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected String resolveDriverVersion(String driverVersion) { String preferenceKey = getKeyForPreferences(); Optional<String> browserVersion = empty(); browserVersion = getValueFromPreferences(preferenceKey, browserVersion); if (!browserVersion.isPresent()) { browserVersion = detectBrowserVersion(); } if (browserVersion.isPresent()) { preferenceKey = getKeyForPreferences() + browserVersion.get(); driverVersion = preferences.getValueFromPreferences(preferenceKey); Optional<String> optionalDriverVersion = empty(); if (isUnknown(driverVersion)) { optionalDriverVersion = getDriverVersionFromRepository( browserVersion); } if (isUnknown(driverVersion)) { optionalDriverVersion = getDriverVersionFromProperties( preferenceKey); } if (optionalDriverVersion.isPresent()) { driverVersion = optionalDriverVersion.get(); } if (isUnknown(driverVersion)) { log.debug( "The driver version for {} {} is unknown ... trying with latest", getDriverManagerType(), browserVersion.get()); } else if (!isUnknown(driverVersion)) { log.info( "Using {} {} (since {} {} is installed in your machine)", getDriverName(), driverVersion, getDriverManagerType(), browserVersion.get()); storeInPreferences(preferenceKey, driverVersion, browserVersion.get()); } } // if driverVersion is still unknown, try with latest if (isUnknown(driverVersion)) { Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository(); if (latestDriverVersionFromRepository.isPresent()) { driverVersion = latestDriverVersionFromRepository.get(); } } return driverVersion; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); if (isUnknown(driverVersion)) { driverVersion = resolveDriverVersion(driverVersion); } downloadAndExport(driverVersion); } catch (Exception e) { handleException(e, driverVersion); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); if (isUnknown(driverVersion)) { driverVersion = resolveDriverVersion(driverVersion); } downloadAndExport(driverVersion); } catch (Exception e) { handleException(e, driverVersion); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); if (isUnknown(driverVersion)) { driverVersion = resolveDriverVersion(driverVersion); } Optional<String> driverInCache = searchDriverInCache(driverVersion); String exportValue; if (driverInCache.isPresent() && !config().isOverride()) { log.debug("Driver {} {} found in cache", getDriverName(), getLabel(driverVersion)); storeVersionToDownload(driverVersion); exportValue = driverInCache.get(); } else { exportValue = download(driverVersion); } exportDriver(exportValue); } catch (Exception e) { handleException(e, driverVersion); } } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); if (isUnknown(driverVersion)) { driverVersion = resolveDriverVersion(driverVersion); } Optional<String> driverInCache = searchDriverInCache(driverVersion); String exportValue; if (driverInCache.isPresent() && !config().isOverride()) { log.debug("Driver {} {} found in cache", getDriverName(), getDriverVersionLabel(driverVersion)); storeVersionToDownload(driverVersion); exportValue = driverInCache.get(); } else { exportValue = download(driverVersion); } exportDriver(exportValue); } catch (Exception e) { handleException(e, driverVersion); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void handleException(Exception e, Architecture arch, String version) { String versionStr = isNullOrEmpty(version) ? "(latest version)" : version; String errorMessage = String.format( "There was an error managing %s %s (%s)", getDriverName(), versionStr, e.getMessage()); if (!config().isForceCache() && retry) { config().setForceCache(true); config().setUseMirror(true); retry = false; log.warn("{} ... trying again using cache and mirror", errorMessage); manage(arch, version); } else { log.error("{}", errorMessage, e); throw new WebDriverManagerException(e); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void handleException(Exception e, Architecture arch, String version) { String versionStr = isNullOrEmpty(version) ? "(latest version)" : version; String errorMessage = String.format( "There was an error managing %s %s (%s)", getDriverName(), versionStr, e.getMessage()); if (!config().isForceCache() && retryCount == 0) { config().setForceCache(true); config().setUseMirror(true); retryCount++; log.warn("{} ... trying again using mirror", errorMessage); manage(arch, version); } else if (retryCount == 1) { config().setAvoidAutoVersion(true); version = ""; retryCount++; log.warn("{} ... trying again using latest from cache", errorMessage); manage(arch, version); } else { log.error("{}", errorMessage, e); throw new WebDriverManagerException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected List<URL> filterCandidateUrls(Architecture arch, String version, boolean getLatest) throws IOException { List<URL> urls = getDrivers(); List<URL> candidateUrls; log.trace("All URLs: {}", urls); boolean continueSearchingVersion; do { // Get the latest or concrete version candidateUrls = getLatest ? checkLatest(urls, getDriverName()) : getVersion(urls, getDriverName(), version); log.trace("Candidate URLs: {}", candidateUrls); if (versionToDownload == null || this.getClass().equals(EdgeDriverManager.class)) { break; } // Filter by OS if (!getDriverName().equalsIgnoreCase("IEDriverServer") && !getDriverName() .equalsIgnoreCase("selenium-server-standalone")) { candidateUrls = urlFilter.filterByOs(candidateUrls, config().getOs()); } // Filter by architecture candidateUrls = urlFilter.filterByArch(candidateUrls, arch, forcedArch); // Filter by distro candidateUrls = filterByDistro(candidateUrls); // Filter by ignored versions candidateUrls = filterByIgnoredVersions(candidateUrls); // Find out if driver version has been found or not continueSearchingVersion = candidateUrls.isEmpty() && getLatest; if (continueSearchingVersion) { log.info( "No binary found for {} {} ... seeking another version", getDriverName(), versionToDownload); urls = removeFromList(urls, versionToDownload); versionToDownload = null; } } while (continueSearchingVersion); return candidateUrls; } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected List<URL> filterCandidateUrls(Architecture arch, String version, boolean getLatest) throws IOException { List<URL> urls = getDrivers(); List<URL> candidateUrls; log.trace("All URLs: {}", urls); boolean continueSearchingVersion; do { // Get the latest or concrete version String filterName = getDriverName().equalsIgnoreCase("msedgedriver") ? "edgedriver" : getDriverName(); candidateUrls = getLatest ? checkLatest(urls, filterName) : getVersion(urls, filterName, version); log.trace("Candidate URLs: {}", candidateUrls); if (versionToDownload == null) { break; } // Filter by OS if (!getDriverName().equalsIgnoreCase("IEDriverServer") && !getDriverName() .equalsIgnoreCase("selenium-server-standalone")) { candidateUrls = urlFilter.filterByOs(candidateUrls, config().getOs()); } // Filter by architecture candidateUrls = urlFilter.filterByArch(candidateUrls, arch, forcedArch); // Filter by distro candidateUrls = filterByDistro(candidateUrls); // Filter by ignored versions candidateUrls = filterByIgnoredVersions(candidateUrls); // Find out if driver version has been found or not continueSearchingVersion = candidateUrls.isEmpty() && getLatest; if (continueSearchingVersion) { log.info( "No binary found for {} {} ... seeking another version", getDriverName(), versionToDownload); urls = removeFromList(urls, versionToDownload); versionToDownload = null; } } while (continueSearchingVersion); return candidateUrls; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected Optional<String> getDriverVersionFromProperties(String key) { boolean online = config().getVersionsPropertiesOnlineFirst(); String onlineMessage = online ? ONLINE : LOCAL; log.debug("Getting driver version for {} from {} versions.properties", key, onlineMessage); String value = getVersionFromProperties(online).getProperty(key); if (value == null) { String notOnlineMessage = online ? LOCAL : ONLINE; log.debug( "Driver for {} not found in {} properties (using {} version)", key, onlineMessage, notOnlineMessage); versionsProperties = null; value = getVersionFromProperties(!online).getProperty(key); } return value == null ? empty() : Optional.of(value); } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected Optional<String> getDriverVersionFromProperties(String key) { // Chromium values are the same than Chrome if (key.contains("chromium")) { key = key.replace("chromium", "chrome"); } boolean online = config().getVersionsPropertiesOnlineFirst(); String onlineMessage = online ? ONLINE : LOCAL; log.debug("Getting driver version for {} from {} versions.properties", key, onlineMessage); String value = getVersionFromProperties(online).getProperty(key); if (value == null) { String notOnlineMessage = online ? LOCAL : ONLINE; log.debug( "Driver for {} not found in {} properties (using {} version)", key, onlineMessage, notOnlineMessage); versionsProperties = null; value = getVersionFromProperties(!online).getProperty(key); } return value == null ? empty() : Optional.of(value); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void handleDriver(URL url, String driver, List<URL> out) { if (!useBetaVersions && url.getFile().toLowerCase().contains("beta")) { return; } if (url.getFile().contains(driver)) { String currentVersion = getCurrentVersion(url, driver); if (currentVersion.equalsIgnoreCase(driver)) { return; } if (versionToDownload == null) { versionToDownload = currentVersion; } if (versionCompare(currentVersion, versionToDownload) > 0) { versionToDownload = currentVersion; out.clear(); } if (url.getFile().contains(versionToDownload)) { out.add(url); } } } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void handleDriver(URL url, String driver, List<URL> out) { if (!useBetaVersions && !getBoolean("wdm.useBetaVersions") && url.getFile().toLowerCase().contains("beta")) { return; } if (url.getFile().contains(driver)) { String currentVersion = getCurrentVersion(url, driver); if (currentVersion.equalsIgnoreCase(driver)) { return; } if (versionToDownload == null) { versionToDownload = currentVersion; } if (versionCompare(currentVersion, versionToDownload) > 0) { versionToDownload = currentVersion; out.clear(); } if (url.getFile().contains(versionToDownload)) { out.add(url); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCache() throws Exception { BrowserManager browserManager = null; if (browserManagerClass.equals(ChromeDriverManager.class)) { browserManager = ChromeDriverManager.getInstance(); } else if (browserManagerClass.equals(OperaDriverManager.class)) { browserManager = OperaDriverManager.getInstance(); } else if (browserManagerClass.equals(PhantomJsDriverManager.class)) { browserManager = PhantomJsDriverManager.getInstance(); } else if (browserManagerClass.equals(FirefoxDriverManager.class)) { browserManager = FirefoxDriverManager.getInstance(); } browserManager.architecture(architecture).version(driverVersion) .setup(); Downloader downloader = new Downloader(browserManager); Method method = BrowserManager.class.getDeclaredMethod( "existsDriverInCache", String.class, String.class, Architecture.class); method.setAccessible(true); String driverInChachePath = (String) method.invoke(browserManager, downloader.getTargetPath(), driverVersion, architecture); assertThat(driverInChachePath, notNullValue()); } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testCache() throws Exception { BrowserManager browserManager = WebDriverManager .getInstance(driverClass); browserManager.architecture(architecture).version(driverVersion) .setup(); Downloader downloader = new Downloader(browserManager); Method method = BrowserManager.class.getDeclaredMethod( "existsDriverInCache", String.class, String.class, Architecture.class); method.setAccessible(true); String driverInChachePath = (String) method.invoke(browserManager, downloader.getTargetPath(), driverVersion, architecture); assertThat(driverInChachePath, notNullValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected List<URL> getCandidateUrls(String driverVersion) throws IOException { List<URL> urls = getDrivers(); List<URL> candidateUrls; log.trace("All URLs: {}", urls); boolean getLatest = isUnknown(driverVersion); Architecture arch = config().getArchitecture(); boolean continueSearchingVersion; do { // Get the latest or concrete version String shortDriverName = getShortDriverName(); candidateUrls = getLatest ? checkLatest(urls, shortDriverName) : getVersion(urls, shortDriverName, driverVersion); log.trace("Candidate URLs: {}", candidateUrls); if (versionToDownload == null) { break; } // Filter by OS if (!getDriverName().equalsIgnoreCase("IEDriverServer") && !getDriverName() .equalsIgnoreCase("selenium-server-standalone")) { candidateUrls = urlFilter.filterByOs(candidateUrls, config().getOs()); } // Filter by architecture candidateUrls = urlFilter.filterByArch(candidateUrls, arch, forcedArch); // Filter by distro candidateUrls = filterByDistro(candidateUrls); // Filter by ignored versions candidateUrls = filterByIgnoredVersions(candidateUrls); // Filter by beta candidateUrls = urlFilter.filterByBeta(candidateUrls, config().isUseBetaVersions()); // Find out if driver version has been found or not continueSearchingVersion = candidateUrls.isEmpty() && getLatest; if (continueSearchingVersion) { log.info( "No proper driver found for {} {} ... seeking another version", getDriverName(), versionToDownload); urls = removeFromList(urls, versionToDownload); versionToDownload = null; } } while (continueSearchingVersion); return candidateUrls; } #location 48 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected List<URL> getCandidateUrls(String driverVersion) throws IOException { List<URL> urls = getDrivers(); List<URL> candidateUrls; log.trace("All URLs: {}", urls); boolean getLatest = isUnknown(driverVersion); Architecture arch = config().getArchitecture(); boolean continueSearchingVersion; do { // Get the latest or concrete driver version String shortDriverName = getShortDriverName(); candidateUrls = getLatest ? filterDriverListByLatest(urls, shortDriverName) : filterDriverListByVersion(urls, shortDriverName, driverVersion); log.trace("Candidate URLs: {}", candidateUrls); if (driverVersionToDownload == null) { break; } // Filter by OS if (!getDriverName().equalsIgnoreCase("IEDriverServer") && !getDriverName() .equalsIgnoreCase("selenium-server-standalone")) { candidateUrls = urlFilter.filterByOs(candidateUrls, config().getOs()); } // Filter by architecture candidateUrls = urlFilter.filterByArch(candidateUrls, arch, forcedArch); // Filter by distro candidateUrls = filterByDistro(candidateUrls); // Filter by ignored driver versions candidateUrls = filterByIgnoredDriverVersions(candidateUrls); // Filter by beta candidateUrls = urlFilter.filterByBeta(candidateUrls, config().isUseBetaVersions()); // Find out if driver version has been found or not continueSearchingVersion = candidateUrls.isEmpty() && getLatest; if (continueSearchingVersion) { log.info( "No proper driver found for {} {} ... seeking another version", getDriverName(), driverVersionToDownload); urls = removeFromList(urls, driverVersionToDownload); driverVersionToDownload = null; } } while (continueSearchingVersion); return candidateUrls; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); if (isUnknown(driverVersion)) { preferenceKey = getDriverManagerType().getNameInLowerCase(); Optional<String> browserVersion = empty(); if (usePreferences() && preferences.checkKeyInPreferences(preferenceKey)) { browserVersion = Optional.of( preferences.getValueFromPreferences(preferenceKey)); } if (!browserVersion.isPresent()) { browserVersion = detectBrowserVersion(); } if (browserVersion.isPresent()) { // Calculate driverVersion using browserVersion preferenceKey = getDriverManagerType().getNameInLowerCase() + browserVersion.get(); if (usePreferences() && preferences .checkKeyInPreferences(preferenceKey)) { driverVersion = preferences .getValueFromPreferences(preferenceKey); } if (isUnknown(driverVersion)) { Optional<String> driverVersionFromRepository = getDriverVersionFromRepository( browserVersion); if (driverVersionFromRepository.isPresent()) { driverVersion = driverVersionFromRepository.get(); } } if (isUnknown(driverVersion)) { Optional<String> driverVersionFromProperties = getDriverVersionFromProperties( preferenceKey); if (driverVersionFromProperties.isPresent()) { driverVersion = driverVersionFromProperties.get(); } } else { log.info( "Using {} {} (since {} {} is installed in your machine)", getDriverName(), driverVersion, getDriverManagerType(), browserVersion.get()); } if (usePreferences()) { preferences.putValueInPreferencesIfEmpty( getDriverManagerType().getNameInLowerCase(), browserVersion.get()); preferences.putValueInPreferencesIfEmpty(preferenceKey, driverVersion); } if (isUnknown(driverVersion)) { log.debug( "The driver version for {} {} is unknown ... trying with latest", getDriverManagerType(), browserVersion.get()); } } // if driverVersion is still unknown, try with latest if (isUnknown(driverVersion)) { Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository(); if (latestDriverVersionFromRepository.isPresent()) { driverVersion = latestDriverVersionFromRepository.get(); } } } downloadAndExport(driverVersion); } catch (Exception e) { handleException(e, driverVersion); } } #location 36 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void manage(String driverVersion) { httpClient = new HttpClient(config()); try (HttpClient wdmHttpClient = httpClient) { downloader = new Downloader(getDriverManagerType()); urlFilter = new UrlFilter(); if (isUnknown(driverVersion)) { driverVersion = resolveDriverVersion(driverVersion); } downloadAndExport(driverVersion); } catch (Exception e) { handleException(e, driverVersion); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected File postDownload(File archive) { log.trace("PhatomJS package name: {}", archive); File extractFolder = archive.getParentFile().listFiles()[0]; log.trace("PhatomJS extract folder (to be deleted): {}", extractFolder); File binFolder = new File( extractFolder.getAbsoluteFile() + separator + "bin"); // Exception for older version of PhantomJS int binaryIndex = 0; if (!binFolder.exists()) { binFolder = extractFolder; binaryIndex = 3; } log.trace("PhatomJS bin folder: {} (index {})", binFolder, binaryIndex); File phantomjs = binFolder.listFiles()[binaryIndex]; log.trace("PhatomJS binary: {}", phantomjs); File target = new File(archive.getParentFile().getAbsolutePath(), phantomjs.getName()); log.trace("PhatomJS target: {}", target); downloader.renameFile(phantomjs, target); downloader.deleteFolder(extractFolder); return target; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected File postDownload(File archive) { log.trace("PhatomJS package name: {}", archive); File extractFolder = archive.getParentFile() .listFiles(getFolderFilter())[0]; log.trace("PhatomJS extract folder (to be deleted): {}", extractFolder); File binFolder = new File( extractFolder.getAbsoluteFile() + separator + "bin"); // Exception for older version of PhantomJS int binaryIndex = 0; if (!binFolder.exists()) { binFolder = extractFolder; binaryIndex = 3; } log.trace("PhatomJS bin folder: {} (index {})", binFolder, binaryIndex); File phantomjs = binFolder.listFiles()[binaryIndex]; log.trace("PhatomJS binary: {}", phantomjs); File target = new File(archive.getParentFile().getAbsolutePath(), phantomjs.getName()); log.trace("PhatomJS target: {}", target); downloader.renameFile(phantomjs, target); downloader.deleteFolder(extractFolder); return target; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected Optional<String> getLatestVersion() { String url = config().getChromeDriverUrl() + "LATEST_RELEASE"; HttpGet request = new HttpGet(url); request.addHeader("User-Agent", USER_AGENT); HttpResponse response; Optional<String> version = Optional.empty(); try { response = httpClient.execute(request); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); version = Optional.of(IOUtils.toString(rd)); } catch (IOException e) { log.warn("Exception reading {} to get latest version of {}", url, getDriverName(), e); } log.debug("Latest version of {} according to {} is {}", getDriverName(), url, version); return version; } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code @Override protected Optional<String> getLatestVersion() { String url = config().getChromeDriverUrl() + "LATEST_RELEASE"; Optional<String> version = Optional.empty(); try { InputStream response = httpClient .execute(httpClient.createHttpGet(new URL(url))).getEntity() .getContent(); version = Optional.of(IOUtils.toString(response, defaultCharset())); } catch (Exception e) { log.warn("Exception reading {} to get latest version of {}", url, getDriverName(), e); } if (version.isPresent()) { log.debug("Latest version of {} according to {} is {}", getDriverName(), url, version.get()); } return version; }
Below is the vulnerable code, please generate the patch based on the following information.