input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code public void prepareIoc() throws Exception { if (ctx.getComboIocLoader() == null) { int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); List<String> args = new ArrayList<>(); args.add("*js"); args.add("ioc/"); args.add("*tx"); args.add("*async"); args.add(""+asyncPoolSize); args.add("*anno"); args.add(ctx.getPackage()); IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); if (iocBy != null) { String[] tmp = iocBy.args(); ArrayList<String> _args = new ArrayList<>(); for (int i=0;i<tmp.length;i++) { if (tmp[i].startsWith("*")) { if (!_args.isEmpty()) { switch (_args.get(0)) { case "*tx": case "*async": case "*anno": case "*js": break; default: args.addAll(_args); } _args.clear(); } } _args.add(tmp[i]); } if (_args.size() > 0) { switch (_args.get(0)) { case "*tx": case "*async": case "*anno": case "*js": break; default: args.addAll(_args); } } } ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); } // 用于加载Starter的IocLoader starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); ctx.getComboIocLoader().addLoader(starterIocLoader); if (ctx.getIoc() == null) { ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); } // 把核心对象放进ioc容器 if (!ctx.ioc.has("appContext")){ Ioc2 ioc2 = (Ioc2)ctx.getIoc(); ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx)); ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConfigureLoader().get())); } } #location 57 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void prepareIoc() throws Exception { if (ctx.getComboIocLoader() == null) { int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); List<String> args = new ArrayList<>(); args.add("*js"); args.add("ioc/"); args.add("*tx"); args.add("*async"); args.add(""+asyncPoolSize); args.add("*anno"); args.add(ctx.getPackage()); IocBy iocBy = ctx.getMainClass().getAnnotation(IocBy.class); if (iocBy != null) { String[] tmp = iocBy.args(); ArrayList<String> _args = new ArrayList<>(); for (int i=0;i<tmp.length;i++) { if (tmp[i].startsWith("*")) { if (!_args.isEmpty()) { switch (_args.get(0)) { case "*tx": case "*async": case "*anno": case "*js": break; default: args.addAll(_args); } _args.clear(); } } _args.add(tmp[i]); } if (_args.size() > 0) { switch (_args.get(0)) { case "*tx": case "*async": case "*anno": case "*js": break; default: args.addAll(_args); } } } ctx.setComboIocLoader(new ComboIocLoader(args.toArray(new String[args.size()]))); } // 用于加载Starter的IocLoader starterIocLoader = new AnnotationIocLoader(NbApp.class.getPackage().getName() + ".starter"); ctx.getComboIocLoader().addLoader(starterIocLoader); if (ctx.getIoc() == null) { ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); } // 把核心对象放进ioc容器 if (!ctx.ioc.has("appContext")){ Ioc2 ioc2 = (Ioc2)ctx.getIoc(); ioc2.getIocContext().save("app", "appContext", new ObjectProxy(ctx)); ioc2.getIocContext().save("app", "conf", new ObjectProxy(ctx.getConf())); ioc2.getIocContext().save("app", "nbApp", new ObjectProxy(this)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void prepareBasic() throws Exception { if (this.ctx == null) { ctx = AppContext.getDefault(); } if (ctx.getMainClass() == null && mainClass != null) ctx.setMainClass(mainClass); // 检查ClassLoader的情况 if (ctx.getClassLoader() == null) ctx.setClassLoader(NbApp.class.getClassLoader()); if (ctx.getEnvHolder() == null) { ctx.setEnvHolder(new SystemPropertiesEnvHolder()); } // 看看日志应该用哪个 String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); if (!Strings.isBlank(logAdapter)) { Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); } log = Logs.get(); // 资源加载器 if (ctx.getResourceLoader() == null) { ResourceLoader resourceLoader = new SimpleResourceLoader(); aware(resourceLoader); ctx.setResourceLoader(resourceLoader); } } #location 16 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void prepareBasic() throws Exception { // 检查ClassLoader的情况 if (ctx.getClassLoader() == null) ctx.setClassLoader(NbApp.class.getClassLoader()); if (ctx.getEnvHolder() == null) { ctx.setEnvHolder(new SystemPropertiesEnvHolder()); } // 看看日志应该用哪个 String logAdapter = ctx.getEnvHolder().get("nutz.boot.base.LogAdapter"); if (!Strings.isBlank(logAdapter)) { Logs.setAdapter((LogAdapter) ctx.getClassLoader().loadClass(logAdapter).newInstance()); } log = Logs.get(); // 资源加载器 if (ctx.getResourceLoader() == null) { ResourceLoader resourceLoader = new SimpleResourceLoader(); aware(resourceLoader); ctx.setResourceLoader(resourceLoader); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void _run() throws Exception { Stopwatch sw = Stopwatch.begin(); // 各种预备操作 this.prepare(); if (printProcDoc) { PropDocReader docReader = new PropDocReader(ctx); docReader.load(); Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); } // 依次启动 try { ctx.init(); ctx.startServers(); if (ctx.getMainClass().getAnnotation(IocBean.class) != null) ctx.getIoc().get(ctx.getMainClass()); sw.stop(); log.infof("NB started : %sms", sw.du()); synchronized (lock) { lock.wait(); } } catch (Throwable e) { log.error("something happen!!", e); } // 收尾 ctx.stopServers(); ctx.depose(); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void _run() throws Exception { Stopwatch sw = Stopwatch.begin(); // 各种预备操作 this.prepare(); // 依次启动 try { ctx.init(); ctx.startServers(); if (ctx.getMainClass().getAnnotation(IocBean.class) != null) ctx.getIoc().get(ctx.getMainClass()); sw.stop(); log.infof("NB started : %sms", sw.du()); synchronized (lock) { lock.wait(); } } catch (Throwable e) { log.error("something happen!!", e); } // 收尾 ctx.stopServers(); ctx.depose(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void shutdown() { log.info("ok, shutting down ..."); synchronized (lock) { lock.notify(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void shutdown() { log.info("ok, shutting down ..."); if (lock == null) { _shutdown(); } else { synchronized (lock) { lock.notify(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void _run() throws Exception { Stopwatch sw = Stopwatch.begin(); // 各种预备操作 this.prepare(); if (printProcDoc) { PropDocReader docReader = new PropDocReader(ctx); docReader.load(); Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); } // 依次启动 try { ctx.init(); ctx.startServers(); if (mainClass.getAnnotation(IocBean.class) != null) ctx.getIoc().get(mainClass); sw.stop(); log.infof("NB started : %sms", sw.du()); synchronized (lock) { lock.wait(); } } catch (Throwable e) { log.error("something happen!!", e); } // 收尾 ctx.stopServers(); ctx.depose(); } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void _run() throws Exception { Stopwatch sw = Stopwatch.begin(); // 各种预备操作 this.prepare(); if (printProcDoc) { PropDocReader docReader = new PropDocReader(ctx); docReader.load(); Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); } // 依次启动 try { ctx.init(); ctx.startServers(); if (ctx.getMainClass().getAnnotation(IocBean.class) != null) ctx.getIoc().get(ctx.getMainClass()); sw.stop(); log.infof("NB started : %sms", sw.du()); synchronized (lock) { lock.wait(); } } catch (Throwable e) { log.error("something happen!!", e); } // 收尾 ctx.stopServers(); ctx.depose(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void prepare() throws Exception { if (prepared) return; // 初始化上下文 listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before)); this.prepareBasic(); listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after)); // 打印Banner,暂时不可配置具体的类 new SimpleBannerPrinter().printBanner(ctx); // 配置信息要准备好 listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before)); this.prepareConfigureLoader(); listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after)); // 创建IocLoader体系 listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before)); prepareIocLoader(); listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after)); // 加载各种starter listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before)); prepareStarterClassList(); listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after)); // 打印配置文档 if (printProcDoc) { PropDocReader docReader = new PropDocReader(); docReader.load(starterClasses); Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); } // 创建Ioc容器 listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before)); prepareIoc(); listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after)); // 生成Starter实例 listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before)); prepareStarterInstance(); listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after)); // 从Ioc容器检索Listener listeners.addAll(ctx.getBeans(NbAppEventListener.class)); prepared = true; } #location 37 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void prepare() throws Exception { if (prepared) return; // 初始化上下文 listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before)); this.prepareBasic(); listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.after)); // 打印Banner,暂时不可配置具体的类 new SimpleBannerPrinter().printBanner(ctx); // 配置信息要准备好 listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.before)); this.prepareConfigureLoader(); listeners.forEach((listener)->listener.whenPrepareConfigureLoader(this, EventType.after)); // 创建IocLoader体系 listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.before)); prepareIocLoader(); listeners.forEach((listener)->listener.whenPrepareIocLoader(this, EventType.after)); // 加载各种starter listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.before)); prepareStarterClassList(); listeners.forEach((listener)->listener.whenPrepareStarterClassList(this, EventType.after)); // 打印配置文档 if (printProcDoc) { PropDocReader docReader = new PropDocReader(); docReader.load(starterClasses); if (getAppContext().getConf().get("nutz.propdoc.packages") != null) { for (String pkg : Strings.splitIgnoreBlank(getAppContext().getConf().get("nutz.propdoc.packages"))) { for (Class<?> klass : Scans.me().scanPackage(pkg)) { if (klass.isInterface()) continue; docReader.addClass(klass); } } } Logs.get().info("Configure Manual:\r\n" + docReader.toMarkdown()); } // 创建Ioc容器 listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.before)); prepareIoc(); listeners.forEach((listener)->listener.whenPrepareIoc(this, EventType.after)); // 生成Starter实例 listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.before)); prepareStarterInstance(); listeners.forEach((listener)->listener.whenPrepareStarterInstance(this, EventType.after)); // 从Ioc容器检索Listener listeners.addAll(ctx.getBeans(NbAppEventListener.class)); prepared = true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping("/logout") public String logout(HttpServletRequest request) { HttpSession session = request.getSession(); // 注销本地会话 if (session != null) { session.invalidate(); } // 如果是客户端发起的注销请求 String token = (String) session.getAttribute(AuthConst.TOKEN); List<String> clientUrls = authService.remove(token); if (clientUrls != null && clientUrls.size() > 0) { Map<String, String> params = new HashMap<String, String>(); params.put(AuthConst.LOGOUT_REQUEST, AuthConst.LOGOUT_REQUEST); params.put(AuthConst.TOKEN, token); for (String url : clientUrls) { AuthUtil.post(url, params); } } // 重定向到登录页面 return "redirect:/"; } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping("/logout") public String logout(HttpServletRequest request) { HttpSession session = request.getSession(); if (session != null) { session.invalidate(); } return "redirect:/"; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBugSentences() throws IOException { String[] bugSentences = new String[] { "干脆就把那部蒙人的闲法给废了拉倒!RT @laoshipukong : 27日,全国人大常委会第三次审议侵权责任法草案,删除了有关医疗损害责任“举证倒置”的规定。在医患纠纷中本已处于弱势地位的消费者由此将陷入万劫不复的境地。 " }; JiebaAnalyzer analyzer = new JiebaAnalyzer("index", new File("data"), true); for (String sentence : bugSentences) { TokenStream tokenStream = analyzer.tokenStream(null, new StringReader(sentence)); tokenStream.reset(); while (tokenStream.incrementToken()) { CharTermAttribute termAtt = tokenStream .getAttribute(CharTermAttribute.class); OffsetAttribute offsetAtt = tokenStream .getAttribute(OffsetAttribute.class); System.out .println(termAtt.toString() + "," + offsetAtt.startOffset() + "," + offsetAtt.endOffset()); } tokenStream.reset(); } } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testBugSentences() throws IOException { String[] bugSentences = new String[] { "干脆就把那部蒙人的闲法给废了拉倒!RT @laoshipukong : 27日,全国人大常委会第三次审议侵权责任法草案,删除了有关医疗损害责任“举证倒置”的规定。在医患纠纷中本已处于弱势地位的消费者由此将陷入万劫不复的境地。 " }; JiebaAnalyzer analyzer = new JiebaAnalyzer("index", new File("data"), true); for (String sentence : bugSentences) { TokenStream tokenStream = analyzer.tokenStream(null, new StringReader(sentence)); tokenStream.reset(); while (tokenStream.incrementToken()) { CharTermAttribute termAtt = tokenStream .getAttribute(CharTermAttribute.class); OffsetAttribute offsetAtt = tokenStream .getAttribute(OffsetAttribute.class); System.out .println(termAtt.toString() + "," + offsetAtt.startOffset() + "," + offsetAtt.endOffset()); } tokenStream.reset(); } analyzer.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test() throws IOException { JiebaAnalyzer analyzer = new JiebaAnalyzer("index", new File("data"), true); for (String sentence : sentences) { TokenStream tokenStream = analyzer.tokenStream(null, new StringReader(sentence)); tokenStream.reset(); while (tokenStream.incrementToken()) { CharTermAttribute termAtt = tokenStream .getAttribute(CharTermAttribute.class); OffsetAttribute offsetAtt = tokenStream .getAttribute(OffsetAttribute.class); System.out .println(termAtt.toString() + "," + offsetAtt.startOffset() + "," + offsetAtt.endOffset()); } tokenStream.reset(); } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void test() throws IOException { JiebaAnalyzer analyzer = new JiebaAnalyzer("index", new File("data"), true); for (String sentence : sentences) { TokenStream tokenStream = analyzer.tokenStream(null, new StringReader(sentence)); tokenStream.reset(); while (tokenStream.incrementToken()) { CharTermAttribute termAtt = tokenStream .getAttribute(CharTermAttribute.class); OffsetAttribute offsetAtt = tokenStream .getAttribute(OffsetAttribute.class); System.out .println(termAtt.toString() + "," + offsetAtt.startOffset() + "," + offsetAtt.endOffset()); } tokenStream.reset(); } analyzer.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSegModeOther() throws IOException { JiebaAnalyzer analyzer = new JiebaAnalyzer("other", new File("data"), true); for (String sentence : sentences) { TokenStream tokenStream = analyzer.tokenStream(null, new StringReader(sentence)); tokenStream.reset(); while (tokenStream.incrementToken()) { CharTermAttribute termAtt = tokenStream .getAttribute(CharTermAttribute.class); OffsetAttribute offsetAtt = tokenStream .getAttribute(OffsetAttribute.class); System.out .println(termAtt.toString() + "," + offsetAtt.startOffset() + "," + offsetAtt.endOffset()); } tokenStream.reset(); } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testSegModeOther() throws IOException { JiebaAnalyzer analyzer = new JiebaAnalyzer("other", new File("data"), true); for (String sentence : sentences) { TokenStream tokenStream = analyzer.tokenStream(null, new StringReader(sentence)); tokenStream.reset(); while (tokenStream.incrementToken()) { CharTermAttribute termAtt = tokenStream .getAttribute(CharTermAttribute.class); OffsetAttribute offsetAtt = tokenStream .getAttribute(OffsetAttribute.class); System.out .println(termAtt.toString() + "," + offsetAtt.startOffset() + "," + offsetAtt.endOffset()); } tokenStream.reset(); } analyzer.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/cluster/info/ajax", method = RequestMethod.GET) public void clusterAjax(HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Charset", "utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Encoding", "gzip"); String ip = request.getHeader("x-forwarded-for"); LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip)); try { byte[] output = GzipUtils.compressToByte(ClusterService.getCluster()); response.setContentLength(output.length); OutputStream out = response.getOutputStream(); out.write(output); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = "/cluster/info/ajax", method = RequestMethod.GET) public void clusterAjax(HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Charset", "utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Encoding", "gzip"); String ip = request.getHeader("x-forwarded-for"); LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip)); try { byte[] output = GzipUtils.compressToByte(ClusterService.getCluster()); response.setContentLength(output == null ? "NULL".toCharArray().length :output.length); OutputStream out = response.getOutputStream(); out.write(output); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/consumer/offset/{group}/{topic}/ajax", method = RequestMethod.GET) public void offsetDetailAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Charset", "utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Encoding", "gzip"); String ip = request.getHeader("x-forwarded-for"); LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip)); String aoData = request.getParameter("aoData"); JSONArray jsonArray = JSON.parseArray(aoData); int sEcho = 0, iDisplayStart = 0, iDisplayLength = 0; for (Object obj : jsonArray) { JSONObject jsonObj = (JSONObject) obj; if ("sEcho".equals(jsonObj.getString("name"))) { sEcho = jsonObj.getIntValue("value"); } else if ("iDisplayStart".equals(jsonObj.getString("name"))) { iDisplayStart = jsonObj.getIntValue("value"); } else if ("iDisplayLength".equals(jsonObj.getString("name"))) { iDisplayLength = jsonObj.getIntValue("value"); } } JSONArray ret = JSON.parseArray(OffsetService.getLogSize(topic, group, ip)); int offset = 0; JSONArray retArr = new JSONArray(); for (Object tmp : ret) { JSONObject tmp2 = (JSONObject) tmp; if (offset < (iDisplayLength + iDisplayStart) && offset >= iDisplayStart) { JSONObject obj = new JSONObject(); obj.put("partition", tmp2.getInteger("partition")); if (tmp2.getLong("logSize") == 0) { obj.put("logsize", "<a class='btn btn-warning btn-xs'>0</a>"); } else { obj.put("logsize", tmp2.getLong("logSize")); } if (tmp2.getLong("offset") == -1) { obj.put("offset", "<a class='btn btn-warning btn-xs'>0</a>"); } else { obj.put("offset", "<a class='btn btn-success btn-xs'>" + tmp2.getLong("offset") + "</a>"); } obj.put("lag", "<a class='btn btn-danger btn-xs'>" + tmp2.getLong("lag") + "</a>"); obj.put("owner", tmp2.getString("owner")); obj.put("created", tmp2.getString("create")); obj.put("modify", tmp2.getString("modify")); retArr.add(obj); } offset++; } JSONObject obj = new JSONObject(); obj.put("sEcho", sEcho); obj.put("iTotalRecords", ret.size()); obj.put("iTotalDisplayRecords", ret.size()); obj.put("aaData", retArr); try { byte[] output = GzipUtils.compressToByte(obj.toJSONString()); response.setContentLength(output.length); OutputStream out = response.getOutputStream(); out.write(output); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } #location 60 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = "/consumer/offset/{group}/{topic}/ajax", method = RequestMethod.GET) public void offsetDetailAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Charset", "utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Encoding", "gzip"); String ip = request.getHeader("x-forwarded-for"); LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip)); String aoData = request.getParameter("aoData"); JSONArray jsonArray = JSON.parseArray(aoData); int sEcho = 0, iDisplayStart = 0, iDisplayLength = 0; for (Object obj : jsonArray) { JSONObject jsonObj = (JSONObject) obj; if ("sEcho".equals(jsonObj.getString("name"))) { sEcho = jsonObj.getIntValue("value"); } else if ("iDisplayStart".equals(jsonObj.getString("name"))) { iDisplayStart = jsonObj.getIntValue("value"); } else if ("iDisplayLength".equals(jsonObj.getString("name"))) { iDisplayLength = jsonObj.getIntValue("value"); } } JSONArray ret = JSON.parseArray(OffsetService.getLogSize(topic, group, ip)); int offset = 0; JSONArray retArr = new JSONArray(); for (Object tmp : ret) { JSONObject tmp2 = (JSONObject) tmp; if (offset < (iDisplayLength + iDisplayStart) && offset >= iDisplayStart) { JSONObject obj = new JSONObject(); obj.put("partition", tmp2.getInteger("partition")); if (tmp2.getLong("logSize") == 0) { obj.put("logsize", "<a class='btn btn-warning btn-xs'>0</a>"); } else { obj.put("logsize", tmp2.getLong("logSize")); } if (tmp2.getLong("offset") == -1) { obj.put("offset", "<a class='btn btn-warning btn-xs'>0</a>"); } else { obj.put("offset", "<a class='btn btn-success btn-xs'>" + tmp2.getLong("offset") + "</a>"); } obj.put("lag", "<a class='btn btn-danger btn-xs'>" + tmp2.getLong("lag") + "</a>"); obj.put("owner", tmp2.getString("owner")); obj.put("created", tmp2.getString("create")); obj.put("modify", tmp2.getString("modify")); retArr.add(obj); } offset++; } JSONObject obj = new JSONObject(); obj.put("sEcho", sEcho); obj.put("iTotalRecords", ret.size()); obj.put("iTotalDisplayRecords", ret.size()); obj.put("aaData", retArr); try { byte[] output = GzipUtils.compressToByte(obj.toJSONString()); response.setContentLength(output == null ? "NULL".toCharArray().length : output.length); OutputStream out = response.getOutputStream(); out.write(output); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static long getLogSize(List<String> hosts, String topic, int partition) { LOG.info("Find leader hosts [" + hosts + "]"); PartitionMetadata metadata = findLeader(hosts, topic, partition); if (metadata == null) { LOG.error("[KafkaClusterUtils.getLogSize()] - Can't find metadata for Topic and Partition. Exiting"); } if (metadata.leader() == null) { LOG.error("[KafkaClusterUtils.getLogSize()] - Can't find Leader for Topic and Partition. Exiting"); } String clientName = "Client_" + topic + "_" + partition; String reaHost = metadata.leader().host(); int port = metadata.leader().port(); long ret = 0L; try { SimpleConsumer simpleConsumer = new SimpleConsumer(reaHost, port, 100000, 64 * 1024, clientName); TopicAndPartition topicAndPartition = new TopicAndPartition(topic, partition); Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>(); requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(OffsetRequest.LatestTime(), 1)); kafka.javaapi.OffsetRequest request = new kafka.javaapi.OffsetRequest(requestInfo, OffsetRequest.CurrentVersion(), clientName); OffsetResponse response = simpleConsumer.getOffsetsBefore(request); if (response.hasError()) { System.out.println("Error fetching data Offset , Reason: " + response.errorCode(topic, partition)); LOG.error("Error fetching data Offset , Reason: " + response.errorCode(topic, partition)); return 0; } long[] offsets = response.offsets(topic, partition); ret = offsets[0]; } catch (Exception ex) { LOG.error(ex.getMessage()); } return ret; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public static long getLogSize(List<String> hosts, String topic, int partition) { LOG.info("Find leader hosts [" + hosts + "]"); PartitionMetadata metadata = findLeader(hosts, topic, partition); if (metadata == null) { LOG.error("[KafkaClusterUtils.getLogSize()] - Can't find metadata for Topic and Partition. Exiting"); return 0L; } if (metadata.leader() == null) { LOG.error("[KafkaClusterUtils.getLogSize()] - Can't find Leader for Topic and Partition. Exiting"); return 0L; } String clientName = "Client_" + topic + "_" + partition; String reaHost = metadata.leader().host(); int port = metadata.leader().port(); long ret = 0L; try { SimpleConsumer simpleConsumer = new SimpleConsumer(reaHost, port, 100000, 64 * 1024, clientName); TopicAndPartition topicAndPartition = new TopicAndPartition(topic, partition); Map<TopicAndPartition, PartitionOffsetRequestInfo> requestInfo = new HashMap<TopicAndPartition, PartitionOffsetRequestInfo>(); requestInfo.put(topicAndPartition, new PartitionOffsetRequestInfo(OffsetRequest.LatestTime(), 1)); kafka.javaapi.OffsetRequest request = new kafka.javaapi.OffsetRequest(requestInfo, OffsetRequest.CurrentVersion(), clientName); OffsetResponse response = simpleConsumer.getOffsetsBefore(request); if (response.hasError()) { System.out.println("Error fetching data Offset , Reason: " + response.errorCode(topic, partition)); LOG.error("Error fetching data Offset , Reason: " + response.errorCode(topic, partition)); return 0; } long[] offsets = response.offsets(topic, partition); ret = offsets[0]; } catch (Exception ex) { LOG.error(ex.getMessage()); } return ret; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/dash/kafka/ajax", method = RequestMethod.GET) public void dashboardAjax(HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Charset", "utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Encoding", "gzip"); String ip = request.getHeader("x-forwarded-for"); LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip)); try { byte[] output = GzipUtils.compressToByte(DashboardService.getDashboard()); // byte[] output = GzipUtils.compressToByte(kafkaCluster()); response.setContentLength(output.length); OutputStream out = response.getOutputStream(); out.write(output); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = "/dash/kafka/ajax", method = RequestMethod.GET) public void dashboardAjax(HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Charset", "utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Encoding", "gzip"); String ip = request.getHeader("x-forwarded-for"); LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip)); try { byte[] output = GzipUtils.compressToByte(DashboardService.getDashboard()); response.setContentLength(output == null ? "NULL".toCharArray().length :output.length); OutputStream out = response.getOutputStream(); out.write(output); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/topic/meta/{tname}/ajax", method = RequestMethod.GET) public void topicMetaAjax(@PathVariable("tname") String tname, HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Charset", "utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Encoding", "gzip"); String ip = request.getHeader("x-forwarded-for"); LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip)); String aoData = request.getParameter("aoData"); JSONArray jsonArray = JSON.parseArray(aoData); int sEcho = 0, iDisplayStart = 0, iDisplayLength = 0; for (Object obj : jsonArray) { JSONObject jsonObj = (JSONObject) obj; if ("sEcho".equals(jsonObj.getString("name"))) { sEcho = jsonObj.getIntValue("value"); } else if ("iDisplayStart".equals(jsonObj.getString("name"))) { iDisplayStart = jsonObj.getIntValue("value"); } else if ("iDisplayLength".equals(jsonObj.getString("name"))) { iDisplayLength = jsonObj.getIntValue("value"); } } String str = TopicService.topicMeta(tname, ip); JSONArray ret = JSON.parseArray(str); int offset = 0; JSONArray retArr = new JSONArray(); for (Object tmp : ret) { JSONObject tmp2 = (JSONObject) tmp; if (offset < (iDisplayLength + iDisplayStart) && offset >= iDisplayStart) { JSONObject obj = new JSONObject(); obj.put("topic", tname); obj.put("partition", tmp2.getInteger("partitionId")); obj.put("leader", tmp2.getInteger("leader")); obj.put("replicas", tmp2.getString("replicas")); obj.put("isr", tmp2.getString("isr")); retArr.add(obj); } offset++; } JSONObject obj = new JSONObject(); obj.put("sEcho", sEcho); obj.put("iTotalRecords", ret.size()); obj.put("iTotalDisplayRecords", ret.size()); obj.put("aaData", retArr); try { byte[] output = GzipUtils.compressToByte(obj.toJSONString()); response.setContentLength(output.length); OutputStream out = response.getOutputStream(); out.write(output); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } #location 51 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = "/topic/meta/{tname}/ajax", method = RequestMethod.GET) public void topicMetaAjax(@PathVariable("tname") String tname, HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Charset", "utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Encoding", "gzip"); String ip = request.getHeader("x-forwarded-for"); LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip)); String aoData = request.getParameter("aoData"); JSONArray jsonArray = JSON.parseArray(aoData); int sEcho = 0, iDisplayStart = 0, iDisplayLength = 0; for (Object obj : jsonArray) { JSONObject jsonObj = (JSONObject) obj; if ("sEcho".equals(jsonObj.getString("name"))) { sEcho = jsonObj.getIntValue("value"); } else if ("iDisplayStart".equals(jsonObj.getString("name"))) { iDisplayStart = jsonObj.getIntValue("value"); } else if ("iDisplayLength".equals(jsonObj.getString("name"))) { iDisplayLength = jsonObj.getIntValue("value"); } } String str = TopicService.topicMeta(tname, ip); JSONArray ret = JSON.parseArray(str); int offset = 0; JSONArray retArr = new JSONArray(); for (Object tmp : ret) { JSONObject tmp2 = (JSONObject) tmp; if (offset < (iDisplayLength + iDisplayStart) && offset >= iDisplayStart) { JSONObject obj = new JSONObject(); obj.put("topic", tname); obj.put("partition", tmp2.getInteger("partitionId")); obj.put("leader", tmp2.getInteger("leader")); obj.put("replicas", tmp2.getString("replicas")); obj.put("isr", tmp2.getString("isr")); retArr.add(obj); } offset++; } JSONObject obj = new JSONObject(); obj.put("sEcho", sEcho); obj.put("iTotalRecords", ret.size()); obj.put("iTotalDisplayRecords", ret.size()); obj.put("aaData", retArr); try { byte[] output = GzipUtils.compressToByte(obj.toJSONString()); response.setContentLength(output == null ? "NULL".toCharArray().length : output.length); OutputStream out = response.getOutputStream(); out.write(output); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/consumer/offset/{group}/{topic}/realtime/ajax", method = RequestMethod.GET) public void offsetGraphAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Charset", "utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Encoding", "gzip"); String ip = request.getHeader("x-forwarded-for"); LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip)); try { byte[] output = GzipUtils.compressToByte(OffsetService.getOffsetsGraph(group, topic)); response.setContentLength(output.length); OutputStream out = response.getOutputStream(); out.write(output); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = "/consumer/offset/{group}/{topic}/realtime/ajax", method = RequestMethod.GET) public void offsetGraphAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Charset", "utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Encoding", "gzip"); String ip = request.getHeader("x-forwarded-for"); LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip)); try { byte[] output = GzipUtils.compressToByte(OffsetService.getOffsetsGraph(group, topic)); response.setContentLength(output == null ? "NULL".toCharArray().length : output.length); OutputStream out = response.getOutputStream(); out.write(output); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<KafkaMetaDomain> findLeader(String topic) { List<KafkaMetaDomain> list = new ArrayList<>(); SimpleConsumer consumer = null; for (KafkaBrokerDomain broker : getBrokers()) { try { consumer = new SimpleConsumer(broker.getHost(), broker.getPort(), 100000, 64 * 1024, "leaderLookup"); if (consumer != null) { break; } } catch (Exception ex) { LOG.error(ex.getMessage()); } } List<String> topics = Collections.singletonList(topic); TopicMetadataRequest req = new TopicMetadataRequest(topics); TopicMetadataResponse resp = consumer.send(req); List<TopicMetadata> metaData = resp.topicsMetadata(); for (TopicMetadata item : metaData) { for (PartitionMetadata part : item.partitionsMetadata()) { KafkaMetaDomain kMeta = new KafkaMetaDomain(); kMeta.setIsr(KafkaClusterUtils.geyReplicasIsr(topic, part.partitionId())); kMeta.setLeader(part.leader() == null ? -1 : part.leader().id()); kMeta.setPartitionId(part.partitionId()); List<Integer> repliList = new ArrayList<>(); for (Broker repli : part.replicas()) { repliList.add(repli.id()); } kMeta.setReplicas(repliList.toString()); list.add(kMeta); } } return list; } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code public static List<KafkaMetaDomain> findLeader(String topic) { List<KafkaMetaDomain> list = new ArrayList<>(); SimpleConsumer consumer = null; for (KafkaBrokerDomain broker : getBrokers()) { try { consumer = new SimpleConsumer(broker.getHost(), broker.getPort(), 100000, 64 * 1024, "leaderLookup"); if (consumer != null) { break; } } catch (Exception ex) { LOG.error(ex.getMessage()); } } if (consumer == null) { LOG.error("Connection [SimpleConsumer] has failed,please check brokers."); return list; } List<String> topics = Collections.singletonList(topic); TopicMetadataRequest req = new TopicMetadataRequest(topics); TopicMetadataResponse resp = consumer.send(req); if (resp == null) { LOG.error("Get [TopicMetadataResponse] has null."); return list; } List<TopicMetadata> metaData = resp.topicsMetadata(); for (TopicMetadata item : metaData) { for (PartitionMetadata part : item.partitionsMetadata()) { KafkaMetaDomain kMeta = new KafkaMetaDomain(); kMeta.setIsr(KafkaClusterUtils.geyReplicasIsr(topic, part.partitionId())); kMeta.setLeader(part.leader() == null ? -1 : part.leader().id()); kMeta.setPartitionId(part.partitionId()); List<Integer> repliList = new ArrayList<>(); for (Broker repli : part.replicas()) { repliList.add(repli.id()); } kMeta.setReplicas(repliList.toString()); list.add(kMeta); } } return list; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/alarm/topic/ajax", method = RequestMethod.GET) public void alarmTopicAjax(HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Charset", "utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Encoding", "gzip"); String ip = request.getHeader("x-forwarded-for"); LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip)); try { byte[] output = GzipUtils.compressToByte(AlarmService.getTopics(ip)); response.setContentLength(output.length); OutputStream out = response.getOutputStream(); out.write(output); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping(value = "/alarm/topic/ajax", method = RequestMethod.GET) public void alarmTopicAjax(HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Charset", "utf-8"); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Encoding", "gzip"); String ip = request.getHeader("x-forwarded-for"); LOG.info("IP:" + (ip == null ? request.getRemoteAddr() : ip)); try { byte[] output = GzipUtils.compressToByte(AlarmService.getTopics(ip)); response.setContentLength(output == null ? "NULL".toCharArray().length : output.length); OutputStream out = response.getOutputStream(); out.write(output); out.flush(); out.close(); } catch (Exception ex) { ex.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static boolean emptyDirectory(File directory) { boolean result = true; File[] entries = directory.listFiles(); for (int i = 0; i < entries.length; i++) { if (!entries[i].delete()) { result = false; } } return result; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public static boolean emptyDirectory(File directory) { boolean result = true; File[] entries = directory.listFiles(); for (File entry : entries) { if (!entry.delete()) { result = false; } } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<ColumnInfo> getMetaData(String tableName) throws SQLException { // 获取主键 ResultSet keyResultSet = connection.getMetaData().getPrimaryKeys(null, null, tableName); String primaryKey = null; if (keyResultSet.next()) { primaryKey = keyResultSet.getObject(4).toString(); } // 获取表注释 ResultSet tableResultSet = connection.getMetaData().getTables(null, connection.getSchema(), tableName.toUpperCase(), new String[]{"TABLE"}); String tableRemarks = null; if (tableResultSet.next()) { tableRemarks = tableResultSet.getString("REMARKS") == null ? "Unknown Table" : tableResultSet.getString("REMARKS"); } // 获取列信息 List<ColumnInfo> columnInfos = new ArrayList<>(); ResultSet columnResultSet = connection.getMetaData().getColumns(null, connection.getSchema(), tableName.toUpperCase(), "%"); while (columnResultSet.next()) { boolean isPrimaryKey; if (columnResultSet.getString("COLUMN_NAME").equals(primaryKey)) { isPrimaryKey = true; } else { isPrimaryKey = false; } ColumnInfo info = new ColumnInfo(columnResultSet.getString("COLUMN_NAME"), columnResultSet.getString("TYPE_NAME"), columnResultSet.getString("REMARKS"), tableRemarks, isPrimaryKey); columnInfos.add(info); } columnResultSet.close(); return columnInfos; } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code public List<ColumnInfo> getMetaData(String tableName) throws Exception { // 获取主键 ResultSet keyResultSet = connection.getMetaData().getPrimaryKeys(null, getSchema(connection), tableName.toUpperCase()); String primaryKey = null; if (keyResultSet.next()) { primaryKey = keyResultSet.getObject(4).toString(); } // 获取表注释 ResultSet tableResultSet = connection.getMetaData().getTables(null, getSchema(connection), tableName.toUpperCase(), new String[]{"TABLE"}); String tableRemarks = null; if (tableResultSet.next()) { tableRemarks = tableResultSet.getString("REMARKS") == null ? "Unknown Table" : tableResultSet.getString("REMARKS"); } // 获取列信息 List<ColumnInfo> columnInfos = new ArrayList<>(); ResultSet columnResultSet = connection.getMetaData().getColumns(null, getSchema(connection), tableName.toUpperCase(), "%"); while (columnResultSet.next()) { boolean isPrimaryKey; if (columnResultSet.getString("COLUMN_NAME").equals(primaryKey)) { isPrimaryKey = true; } else { isPrimaryKey = false; } ColumnInfo info = new ColumnInfo(columnResultSet.getString("COLUMN_NAME"), columnResultSet.getString("TYPE_NAME").toUpperCase(), columnResultSet.getString("REMARKS"), tableRemarks, isPrimaryKey); columnInfos.add(info); } columnResultSet.close(); if (columnInfos.size() == 0) { throw new Exception("Can not find column information from table:" + tableName); } if (connection.getMetaData().getURL().contains("sqlserver")) { // SQLServer需要单独处理REMARKS parseSqlServerColumnRemarks(tableName, columnInfos); } return columnInfos; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Set<RaftPeerId> getHigherPriorityPeers(RaftConfiguration conf) { Set<RaftPeerId> higherPriorityPeers = new HashSet<>(); int currPriority = conf.getPeer(server.getId()).getPriority(); Collection<RaftPeer> peers = conf.getPeers(); for (RaftPeer peer : peers) { if (peer.getPriority() > currPriority) { higherPriorityPeers.add(peer.getId()); } } return higherPriorityPeers; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private Set<RaftPeerId> getHigherPriorityPeers(RaftConfiguration conf) { Set<RaftPeerId> higherPriorityPeers = new HashSet<>(); int currPriority = conf.getPeer(server.getId()).getPriority(); final Collection<RaftPeer> peers = conf.getAllPeers(); for (RaftPeer peer : peers) { if (peer.getPriority() > currPriority) { higherPriorityPeers.add(peer.getId()); } } return higherPriorityPeers; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void runTestDataStream(){ final int bufferSize = 1024*1024; final int bufferNum = 10; final DataStreamOutput out = client.stream(); //send request final List<CompletableFuture<DataStreamReply>> futures = new ArrayList<>(); futures.add(sendRequest(out, 1024)); //send data final int halfBufferSize = bufferSize/2; int dataSize = 0; for(int i = 0; i < bufferNum; i++) { final int size = halfBufferSize + ThreadLocalRandom.current().nextInt(halfBufferSize); final ByteBuffer bf = initBuffer(dataSize, size); futures.add(out.streamAsync(bf)); dataSize += size; } //join all requests for(CompletableFuture<DataStreamReply> f : futures) { f.join(); } Assert.assertEquals(dataSize, byteWritten); shutDownSetup(); } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code public void runTestDataStream(){ final int bufferSize = 1024*1024; final int bufferNum = 10; final DataStreamOutput out = client.stream(); DataStreamClientImpl.DataStreamOutputImpl impl = (DataStreamClientImpl.DataStreamOutputImpl) out; final List<CompletableFuture<DataStreamReply>> futures = new ArrayList<>(); // add header futures.add(impl.getHeaderFuture()); //send data final int halfBufferSize = bufferSize/2; int dataSize = 0; for(int i = 0; i < bufferNum; i++) { final int size = halfBufferSize + ThreadLocalRandom.current().nextInt(halfBufferSize); final ByteBuffer bf = initBuffer(dataSize, size); futures.add(out.writeAsync(bf)); dataSize += size; } //join all requests for(CompletableFuture<DataStreamReply> f : futures) { f.join(); } Assert.assertEquals(writeRequest.getClientId(), impl.getHeader().getClientId()); Assert.assertEquals(writeRequest.getCallId(), impl.getHeader().getCallId()); Assert.assertEquals(writeRequest.getRaftGroupId(), impl.getHeader().getRaftGroupId()); Assert.assertEquals(writeRequest.getServerId(), impl.getHeader().getServerId()); Assert.assertEquals(dataSize, byteWritten); shutDownSetup(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { VerificationTool tool = new VerificationTool(); JCommander.newBuilder() .addObject(tool) .build() .parse(args); System.out.println(tool.metaQuorum); LogServiceClient client = new LogServiceClient(tool.metaQuorum); ExecutorService executor = Executors.newCachedThreadPool(); List<Future<?>> futures = new ArrayList<Future<?>>(tool.numLogs); for (int i = 0; i < tool.numLogs; i++) { BulkWriter writer = new BulkWriter(LOG_NAME_PREFIX + i, client, tool.numRecords); futures.add(executor.submit(writer)); } waitForCompletion(futures); futures = new ArrayList<Future<?>>(tool.numLogs); for (int i = 0; i < tool.numLogs; i++) { BulkReader reader = new BulkReader(LOG_NAME_PREFIX + i, client, tool.numRecords); futures.add(executor.submit(reader)); } waitForCompletion(futures); executor.shutdownNow(); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws IOException { VerificationTool tool = new VerificationTool(); JCommander jc = JCommander.newBuilder() .addObject(tool) .build(); jc.parse(args); if (tool.help) { jc.usage(); return; } System.out.println(tool.metaQuorum); LogServiceClient client = new LogServiceClient(tool.metaQuorum); ExecutorService executor = Executors.newCachedThreadPool(); List<Future<?>> futures = new ArrayList<Future<?>>(tool.numLogs); if (tool.write) { LOG.info("Executing parallel writes"); // Delete any logs that already exist first final Set<LogName> logsInSystem = new HashSet<>(); List<LogInfo> listOfLogs = client.listLogs(); for (LogInfo logInfo : listOfLogs) { logsInSystem.add(logInfo.getLogName()); } LOG.info("Observed logs already in system: {}", logsInSystem); for (int i = 0; i < tool.numLogs; i++) { LogName logName = getLogName(i); if (logsInSystem.contains(logName)) { LOG.info("Deleting {}", logName); client.deleteLog(logName); } BulkWriter writer = new BulkWriter(getLogName(i), client, tool.numRecords, tool.logFrequency); futures.add(executor.submit(writer)); } waitForCompletion(futures); } if (tool.read) { LOG.info("Executing parallel reads"); futures = new ArrayList<Future<?>>(tool.numLogs); for (int i = 0; i < tool.numLogs; i++) { BulkReader reader = new BulkReader(getLogName(i), client, tool.numRecords, tool.logFrequency); futures.add(executor.submit(reader)); } waitForCompletion(futures); } executor.shutdownNow(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void checkFollowerCommitLagsLeader(MiniRaftCluster cluster) { List<RaftServerImpl> followers = cluster.getFollowers(); RaftServerImpl leader = cluster.getLeader(); RatisMetricRegistry leaderMetricsRegistry = RatisMetrics.getMetricRegistryForRaftLeader( leader.getMemberId().toString()); Gauge leaderCommitGauge = RaftLeaderMetrics .getPeerCommitIndexGauge(leader, leader); for (RaftServerImpl follower : followers) { Gauge followerCommitGauge = RaftLeaderMetrics .getPeerCommitIndexGauge(leader, follower); Assert.assertTrue((Long)leaderCommitGauge.getValue() >= (Long)followerCommitGauge.getValue()); } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code private static void checkFollowerCommitLagsLeader(MiniRaftCluster cluster) { List<RaftServerImpl> followers = cluster.getFollowers(); RaftServerImpl leader = cluster.getLeader(); Gauge leaderCommitGauge = RaftServerMetrics .getPeerCommitIndexGauge(leader, leader); for (RaftServerImpl follower : followers) { Gauge followerCommitGauge = RaftServerMetrics .getPeerCommitIndexGauge(leader, follower); Assert.assertTrue((Long)leaderCommitGauge.getValue() >= (Long)followerCommitGauge.getValue()); Gauge followerMetric = RaftServerMetrics .getPeerCommitIndexGauge(follower, follower); System.out.println(followerCommitGauge.getValue()); System.out.println(followerMetric.getValue()); Assert.assertTrue((Long)followerCommitGauge.getValue() <= (Long)followerMetric.getValue()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Map<RaftPeer, NettyRpcService> initRpcServices( Collection<RaftServer> servers, RaftConfiguration conf) { final Map<RaftPeer, NettyRpcService> peerRpcs = new HashMap<>(); for (RaftServer s : servers) { final String address = getAddress(s.getId(), conf); final int port = RaftUtils.newInetSocketAddress(address).getPort(); final NettyRpcService rpc = new NettyRpcService(port, s); peerRpcs.put(new RaftPeer(s.getId(), rpc.getInetSocketAddress()), rpc); } return peerRpcs; } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code private static Map<RaftPeer, NettyRpcService> initRpcServices( Collection<RaftServer> servers, RaftConfiguration conf) { final Map<RaftPeer, NettyRpcService> peerRpcs = new HashMap<>(); for (RaftServer s : servers) { final NettyRpcService rpc = newNettyRpcService(s, conf); peerRpcs.put(new RaftPeer(s.getId(), rpc.getInetSocketAddress()), rpc); } return peerRpcs; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void saveMD5File(File dataFile, String digestString) throws IOException { File md5File = getDigestFileForFile(dataFile); String md5Line = digestString + " *" + dataFile.getName() + "\n"; AtomicFileOutputStream afos = new AtomicFileOutputStream(md5File); afos.write(md5Line.getBytes(StandardCharsets.UTF_8)); afos.close(); if (LOG.isDebugEnabled()) { LOG.debug("Saved MD5 " + digestString + " to " + md5File); } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code private static void saveMD5File(File dataFile, String digestString) throws IOException { File md5File = getDigestFileForFile(dataFile); String md5Line = digestString + " *" + dataFile.getName() + "\n"; try (AtomicFileOutputStream afos = new AtomicFileOutputStream(md5File)) { afos.write(md5Line.getBytes(StandardCharsets.UTF_8)); } if (LOG.isDebugEnabled()) { LOG.debug("Saved MD5 " + digestString + " to " + md5File); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @BeforeClass public static void beforeClass() { cluster = new LogServiceCluster(3); cluster.createWorkers(3); List<LogServer> workers = cluster.getWorkers(); assert(workers.size() == 3); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @BeforeClass public static void beforeClass() { cluster = new LogServiceCluster(3); cluster.createWorkers(3); workers = cluster.getWorkers(); assert(workers.size() == 3); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @BeforeClass public static void beforeClass() { cluster = new LogServiceCluster(3); cluster.createWorkers(3); workers = cluster.getWorkers(); assert(workers.size() == 3); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @BeforeClass public static void beforeClass() { cluster = new LogServiceCluster(3); cluster.createWorkers(3); workers = cluster.getWorkers(); assert(workers.size() == 3); RaftProperties properties = new RaftProperties(); RaftClientConfigKeys.Rpc.setRequestTimeout(properties, TimeDuration.valueOf(15, TimeUnit.SECONDS)); cluster.getMasters().parallelStream().forEach(master -> ((MetaStateMachine)master.getMetaStateMachine()).setProperties(properties)); client = new LogServiceClient(cluster.getMetaIdentity(), properties) { @Override public LogStream createLog(LogName logName) throws IOException { createCount.incrementAndGet(); return super.createLog(logName); } @Override public void deleteLog(LogName logName) throws IOException { deleteCount.incrementAndGet(); super.deleteLog(logName); } @Override public List<LogInfo> listLogs() throws IOException { listCount.incrementAndGet(); return super.listLogs(); } }; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void assertServer(MiniRaftCluster cluster, ClientId clientId, long callId, long oldLastApplied) throws Exception { final long leaderApplied = RaftServerTestUtil.getLastAppliedIndex(cluster.getLeader()); // make sure retry cache has the entry for (RaftServer.Division server : cluster.iterateDivisions()) { LOG.info("check server " + server.getId()); if (RaftServerTestUtil.getLastAppliedIndex(server) < leaderApplied) { Thread.sleep(1000); } Assert.assertEquals(2, RaftServerTestUtil.getRetryCacheSize(server)); Assert.assertNotNull(RaftServerTestUtil.getRetryEntry(server, clientId, callId)); // make sure there is only one log entry committed Assert.assertEquals(1, count(server.getRaftLog(), oldLastApplied + 1)); } } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public void assertServer(MiniRaftCluster cluster, ClientId clientId, long callId, long oldLastApplied) throws Exception { final long leaderApplied = cluster.getLeader().getInfo().getLastAppliedIndex(); // make sure retry cache has the entry for (RaftServer.Division server : cluster.iterateDivisions()) { LOG.info("check server " + server.getId()); if (server.getInfo().getLastAppliedIndex() < leaderApplied) { Thread.sleep(1000); } Assert.assertEquals(2, RaftServerTestUtil.getRetryCacheSize(server)); Assert.assertNotNull(RaftServerTestUtil.getRetryEntry(server, clientId, callId)); // make sure there is only one log entry committed Assert.assertEquals(1, count(server.getRaftLog(), oldLastApplied + 1)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void setupServer(){ servers = new ArrayList<>(peers.size()); singleDataStreamStateMachines = new ArrayList<>(peers.size()); // start stream servers on raft peers. for (int i = 0; i < peers.size(); i++) { SingleDataStreamStateMachine singleDataStreamStateMachine = new SingleDataStreamStateMachine(); singleDataStreamStateMachines.add(singleDataStreamStateMachine); DataStreamServerImpl streamServer; if (i == 0) { // only the first server routes requests to peers. List<RaftPeer> otherPeers = new ArrayList<>(peers); otherPeers.remove(peers.get(i)); streamServer = new DataStreamServerImpl( peers.get(i), properties, null, singleDataStreamStateMachine, otherPeers); } else { streamServer = new DataStreamServerImpl( peers.get(i), singleDataStreamStateMachine, properties, null); } servers.add(streamServer); streamServer.getServerRpc().startServer(); } // start peer clients on stream servers for (DataStreamServerImpl streamServer : servers) { ((NettyServerStreamRpc) streamServer.getServerRpc()).startClientToPeers(); } } #location 20 #vulnerability type NULL_DEREFERENCE
#fixed code private void setupServer(){ servers = new ArrayList<>(peers.size()); singleDataStreamStateMachines = new ArrayList<>(peers.size()); // start stream servers on raft peers. for (int i = 0; i < peers.size(); i++) { SingleDataStreamStateMachine singleDataStreamStateMachine = new SingleDataStreamStateMachine(); singleDataStreamStateMachines.add(singleDataStreamStateMachine); final DataStreamServerImpl streamServer = new DataStreamServerImpl( peers.get(i), singleDataStreamStateMachine, properties, null); final DataStreamServerRpc rpc = streamServer.getServerRpc(); if (i == 0) { // only the first server routes requests to peers. List<RaftPeer> otherPeers = new ArrayList<>(peers); otherPeers.remove(peers.get(i)); rpc.addPeers(otherPeers); } rpc.start(); servers.add(streamServer); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testZeroSizeInProgressFile() throws Exception { final RaftStorage storage = new RaftStorage(storageDir, StartupOption.REGULAR); final File file = storage.getStorageDir().getOpenLogFile(0); storage.close(); // create zero size in-progress file LOG.info("file: " + file); Assert.assertTrue(file.createNewFile()); final Path path = file.toPath(); Assert.assertTrue(Files.exists(path)); Assert.assertEquals(0, Files.size(path)); // getLogSegmentFiles should remove it. final List<RaftStorageDirectory.LogPathAndIndex> logs = storage.getStorageDir().getLogSegmentFiles(); Assert.assertEquals(0, logs.size()); Assert.assertFalse(Files.exists(path)); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testZeroSizeInProgressFile() throws Exception { final RaftStorage storage = RaftStorageTestUtils.newRaftStorage(storageDir); final File file = storage.getStorageDir().getOpenLogFile(0); storage.close(); // create zero size in-progress file LOG.info("file: " + file); Assert.assertTrue(file.createNewFile()); final Path path = file.toPath(); Assert.assertTrue(Files.exists(path)); Assert.assertEquals(0, Files.size(path)); // getLogSegmentFiles should remove it. final List<RaftStorageDirectory.LogPathAndIndex> logs = storage.getStorageDir().getLogSegmentFiles(); Assert.assertEquals(0, logs.size()); Assert.assertFalse(Files.exists(path)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDataStreamDisabled() throws Exception { try { setup(1); final DataStreamClientImpl client = newDataStreamClientImpl(); exception.expect(UnsupportedOperationException.class); exception.expectMessage(DisabledDataStreamClientFactory.class.getName() + "$1 does not support streamAsync"); // stream() will create a header request, thus it will hit UnsupportedOperationException due to // DisabledDataStreamFactory. client.stream(); } finally { shutdown(); } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testDataStreamDisabled() throws Exception { try { setup(1); final RaftClient client = newRaftClientForDataStream(); exception.expect(UnsupportedOperationException.class); exception.expectMessage(DisabledDataStreamClientFactory.class.getName() + "$1 does not support streamAsync"); // stream() will create a header request, thus it will hit UnsupportedOperationException due to // DisabledDataStreamFactory. client.getDataStreamApi().stream(); } finally { shutdown(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 1000) public void testMultipleTasks() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(1); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Assert.assertFalse(scheduler.hasScheduler()); final ErrorHandler errorHandler = new ErrorHandler(); final AtomicBoolean[] fired = new AtomicBoolean[3]; for(int i = 0; i < fired.length; i++) { final AtomicBoolean f = fired[i] = new AtomicBoolean(false); scheduler.onTimeout(TimeDuration.valueOf(100*i + 50, TimeUnit.MILLISECONDS), () -> { Assert.assertFalse(f.get()); f.set(true); }, errorHandler); Assert.assertTrue(scheduler.hasScheduler()); } Thread.sleep(100); Assert.assertTrue(fired[0].get()); Assert.assertFalse(fired[1].get()); Assert.assertFalse(fired[2].get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired[0].get()); Assert.assertTrue(fired[1].get()); Assert.assertFalse(fired[2].get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired[0].get()); Assert.assertTrue(fired[1].get()); Assert.assertTrue(fired[2].get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired[0].get()); Assert.assertTrue(fired[1].get()); Assert.assertTrue(fired[2].get()); Assert.assertFalse(scheduler.hasScheduler()); errorHandler.assertNoError(); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test(timeout = 1000) public void testMultipleTasks() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Assert.assertFalse(scheduler.hasScheduler()); final ErrorHandler errorHandler = new ErrorHandler(); final AtomicBoolean[] fired = new AtomicBoolean[3]; for(int i = 0; i < fired.length; i++) { final AtomicBoolean f = fired[i] = new AtomicBoolean(false); scheduler.onTimeout(TimeDuration.valueOf(100*i + 50, TimeUnit.MILLISECONDS), () -> { Assert.assertFalse(f.get()); f.set(true); }, errorHandler); Assert.assertTrue(scheduler.hasScheduler()); } Thread.sleep(100); Assert.assertTrue(fired[0].get()); Assert.assertFalse(fired[1].get()); Assert.assertFalse(fired[2].get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired[0].get()); Assert.assertTrue(fired[1].get()); Assert.assertFalse(fired[2].get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired[0].get()); Assert.assertTrue(fired[1].get()); Assert.assertTrue(fired[2].get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired[0].get()); Assert.assertTrue(fired[1].get()); Assert.assertTrue(fired[2].get()); Assert.assertFalse(scheduler.hasScheduler()); errorHandler.assertNoError(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Map<String, List<CompletableFuture<DataStreamReply>>> streamWrite( List<String> paths, FileStoreClient fileStoreClient) throws IOException { Map<String, List<CompletableFuture<DataStreamReply>>> fileMap = new HashMap<>(); for(String path : paths) { File file = new File(path); FileInputStream fis = new FileInputStream(file); final DataStreamOutput dataStreamOutput = fileStoreClient.getStreamOutput(path, (int) file.length()); if (dataStreamType.equals("DirectByteBuffer")) { fileMap.put(path, writeByDirectByteBuffer(dataStreamOutput, fis.getChannel())); } else if (dataStreamType.equals("MappedByteBuffer")) { fileMap.put(path, writeByMappedByteBuffer(dataStreamOutput, fis.getChannel())); } else if (dataStreamType.equals("NettyFileRegion")) { fileMap.put(path, writeByNettyFileRegion(dataStreamOutput, file)); } else { System.err.println("Error: dataStreamType should be one of DirectByteBuffer, MappedByteBuffer, transferTo"); } } return fileMap; } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code private Map<String, List<CompletableFuture<DataStreamReply>>> streamWrite( List<String> paths, FileStoreClient fileStoreClient) throws IOException { Map<String, List<CompletableFuture<DataStreamReply>>> fileMap = new HashMap<>(); for(String path : paths) { File file = new File(path); final long fileLength = file.length(); Preconditions.assertTrue(fileLength == getFileSizeInBytes(), "Unexpected file size: expected size is " + getFileSizeInBytes() + " but actual size is " + fileLength); FileInputStream fis = new FileInputStream(file); final DataStreamOutput dataStreamOutput = fileStoreClient.getStreamOutput(path, (int) file.length()); if (dataStreamType.equals("DirectByteBuffer")) { fileMap.put(path, writeByDirectByteBuffer(dataStreamOutput, fis.getChannel())); } else if (dataStreamType.equals("MappedByteBuffer")) { fileMap.put(path, writeByMappedByteBuffer(dataStreamOutput, fis.getChannel())); } else if (dataStreamType.equals("NettyFileRegion")) { fileMap.put(path, writeByNettyFileRegion(dataStreamOutput, file)); } else { System.err.println("Error: dataStreamType should be one of DirectByteBuffer, MappedByteBuffer, transferTo"); } } return fileMap; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void setup(int numServers){ peers = Arrays.stream(MiniRaftCluster.generateIds(numServers, 0)) .map(RaftPeerId::valueOf) .map(id -> new RaftPeer(id, NetUtils.createLocalServerAddress())) .collect(Collectors.toList()); servers = new ArrayList<>(peers.size()); stateMachines = new ConcurrentHashMap<>(); // start stream servers on raft peers. for (int i = 0; i < peers.size(); i++) { final RaftPeer peer = peers.get(i); final RaftServer server = newRaftServer(peer, properties); final DataStreamServerImpl streamServer = new DataStreamServerImpl(server, properties, null); final DataStreamServerRpc rpc = streamServer.getServerRpc(); if (i == 0) { // only the first server routes requests to peers. List<RaftPeer> otherPeers = new ArrayList<>(peers); otherPeers.remove(peers.get(i)); rpc.addRaftPeers(otherPeers); } rpc.start(); servers.add(streamServer); } } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code protected void setup(int numServers){ final List<RaftPeer> peers = Arrays.stream(MiniRaftCluster.generateIds(numServers, 0)) .map(RaftPeerId::valueOf) .map(id -> new RaftPeer(id, NetUtils.createLocalServerAddress())) .collect(Collectors.toList()); servers = new ArrayList<>(peers.size()); // start stream servers on raft peers. for (int i = 0; i < peers.size(); i++) { final RaftPeer peer = peers.get(i); final Server server = new Server(peer); if (i == 0) { // only the first server routes requests to peers. List<RaftPeer> otherPeers = new ArrayList<>(peers); otherPeers.remove(peers.get(i)); server.addRaftPeers(otherPeers); } server.start(); servers.add(server); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void assertServer(MiniRaftCluster cluster, ClientId clientId, long callId, long oldLastApplied) throws Exception { long leaderApplied = cluster.getLeader().getState().getLastAppliedIndex(); // make sure retry cache has the entry for (RaftServerImpl server : cluster.iterateServerImpls()) { LOG.info("check server " + server.getId()); if (server.getState().getLastAppliedIndex() < leaderApplied) { Thread.sleep(1000); } Assert.assertEquals(2, RaftServerTestUtil.getRetryCacheSize(server)); Assert.assertNotNull(RaftServerTestUtil.getRetryEntry(server, clientId, callId)); // make sure there is only one log entry committed Assert.assertEquals(1, count(server.getState().getLog(), oldLastApplied + 1)); } } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public void assertServer(MiniRaftCluster cluster, ClientId clientId, long callId, long oldLastApplied) throws Exception { final long leaderApplied = RaftServerTestUtil.getLastAppliedIndex(cluster.getLeader()); // make sure retry cache has the entry for (RaftServer.Division server : cluster.iterateDivisions()) { LOG.info("check server " + server.getId()); if (RaftServerTestUtil.getLastAppliedIndex(server) < leaderApplied) { Thread.sleep(1000); } Assert.assertEquals(2, RaftServerTestUtil.getRetryCacheSize(server)); Assert.assertNotNull(RaftServerTestUtil.getRetryEntry(server, clientId, callId)); // make sure there is only one log entry committed Assert.assertEquals(1, count(RaftServerTestUtil.getRaftLog(server), oldLastApplied + 1)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 1000) public void testRestartingScheduler() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(1); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Assert.assertFalse(scheduler.hasScheduler()); final ErrorHandler errorHandler = new ErrorHandler(); for(int i = 0; i < 2; i++) { final AtomicBoolean fired = new AtomicBoolean(false); scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> { Assert.assertFalse(fired.get()); fired.set(true); }, errorHandler); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertFalse(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired.get()); Assert.assertFalse(scheduler.hasScheduler()); } errorHandler.assertNoError(); } #location 31 #vulnerability type RESOURCE_LEAK
#fixed code @Test(timeout = 1000) public void testRestartingScheduler() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Assert.assertFalse(scheduler.hasScheduler()); final ErrorHandler errorHandler = new ErrorHandler(); for(int i = 0; i < 2; i++) { final AtomicBoolean fired = new AtomicBoolean(false); scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> { Assert.assertFalse(fired.get()); fired.set(true); }, errorHandler); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertFalse(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired.get()); Assert.assertFalse(scheduler.hasScheduler()); } errorHandler.assertNoError(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 1000) public void testSingleTask() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(1); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Assert.assertFalse(scheduler.hasScheduler()); final ErrorHandler errorHandler = new ErrorHandler(); final AtomicBoolean fired = new AtomicBoolean(false); scheduler.onTimeout(TimeDuration.valueOf(250, TimeUnit.MILLISECONDS), () -> { Assert.assertFalse(fired.get()); fired.set(true); }, errorHandler); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertFalse(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertFalse(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired.get()); Assert.assertFalse(scheduler.hasScheduler()); errorHandler.assertNoError(); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test(timeout = 1000) public void testSingleTask() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Assert.assertFalse(scheduler.hasScheduler()); final ErrorHandler errorHandler = new ErrorHandler(); final AtomicBoolean fired = new AtomicBoolean(false); scheduler.onTimeout(TimeDuration.valueOf(250, TimeUnit.MILLISECONDS), () -> { Assert.assertFalse(fired.get()); fired.set(true); }, errorHandler); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertFalse(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertFalse(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired.get()); Assert.assertFalse(scheduler.hasScheduler()); errorHandler.assertNoError(); scheduler.setGracePeriod(grace); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Map<String, List<CompletableFuture<DataStreamReply>>> streamWrite( List<String> paths, FileStoreClient fileStoreClient) throws IOException { Map<String, List<CompletableFuture<DataStreamReply>>> fileMap = new HashMap<>(); for(String path : paths) { File file = new File(path); FileInputStream fis = new FileInputStream(file); final DataStreamOutput dataStreamOutput = fileStoreClient.getStreamOutput(path, (int) file.length()); if (dataStreamType.equals("DirectByteBuffer")) { fileMap.put(path, writeByDirectByteBuffer(dataStreamOutput, fis.getChannel())); } else if (dataStreamType.equals("MappedByteBuffer")) { fileMap.put(path, writeByMappedByteBuffer(dataStreamOutput, fis.getChannel())); } else if (dataStreamType.equals("NettyFileRegion")) { fileMap.put(path, writeByNettyFileRegion(dataStreamOutput, file)); } else { System.err.println("Error: dataStreamType should be one of DirectByteBuffer, MappedByteBuffer, transferTo"); } } return fileMap; } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code private Map<String, List<CompletableFuture<DataStreamReply>>> streamWrite( List<String> paths, FileStoreClient fileStoreClient) throws IOException { Map<String, List<CompletableFuture<DataStreamReply>>> fileMap = new HashMap<>(); for(String path : paths) { File file = new File(path); final long fileLength = file.length(); Preconditions.assertTrue(fileLength == getFileSizeInBytes(), "Unexpected file size: expected size is " + getFileSizeInBytes() + " but actual size is " + fileLength); FileInputStream fis = new FileInputStream(file); final DataStreamOutput dataStreamOutput = fileStoreClient.getStreamOutput(path, (int) file.length()); if (dataStreamType.equals("DirectByteBuffer")) { fileMap.put(path, writeByDirectByteBuffer(dataStreamOutput, fis.getChannel())); } else if (dataStreamType.equals("MappedByteBuffer")) { fileMap.put(path, writeByMappedByteBuffer(dataStreamOutput, fis.getChannel())); } else if (dataStreamType.equals("NettyFileRegion")) { fileMap.put(path, writeByNettyFileRegion(dataStreamOutput, file)); } else { System.err.println("Error: dataStreamType should be one of DirectByteBuffer, MappedByteBuffer, transferTo"); } } return fileMap; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDataStreamDisabled() throws Exception { try { setup(1); final DataStreamClientImpl client = newDataStreamClientImpl(); exception.expect(UnsupportedOperationException.class); exception.expectMessage(DisabledDataStreamClientFactory.class.getName() + "$1 does not support streamAsync"); // stream() will create a header request, thus it will hit UnsupportedOperationException due to // DisabledDataStreamFactory. client.stream(); } finally { shutdown(); } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testDataStreamDisabled() throws Exception { try { setup(1); final RaftClient client = newRaftClientForDataStream(); exception.expect(UnsupportedOperationException.class); exception.expectMessage(DisabledDataStreamClientFactory.class.getName() + "$1 does not support streamAsync"); // stream() will create a header request, thus it will hit UnsupportedOperationException due to // DisabledDataStreamFactory. client.getDataStreamApi().stream(); } finally { shutdown(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 1000) public void testExtendingGracePeriod() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(1); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Assert.assertFalse(scheduler.hasScheduler()); final ErrorHandler errorHandler = new ErrorHandler(); { final AtomicBoolean fired = new AtomicBoolean(false); scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> { Assert.assertFalse(fired.get()); fired.set(true); }, errorHandler); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertFalse(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); } { // submit another task during grace period final AtomicBoolean fired2 = new AtomicBoolean(false); scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> { Assert.assertFalse(fired2.get()); fired2.set(true); }, errorHandler); Thread.sleep(100); Assert.assertFalse(fired2.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired2.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired2.get()); Assert.assertFalse(scheduler.hasScheduler()); } errorHandler.assertNoError(); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test(timeout = 1000) public void testExtendingGracePeriod() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Assert.assertFalse(scheduler.hasScheduler()); final ErrorHandler errorHandler = new ErrorHandler(); { final AtomicBoolean fired = new AtomicBoolean(false); scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> { Assert.assertFalse(fired.get()); fired.set(true); }, errorHandler); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertFalse(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired.get()); Assert.assertTrue(scheduler.hasScheduler()); } { // submit another task during grace period final AtomicBoolean fired2 = new AtomicBoolean(false); scheduler.onTimeout(TimeDuration.valueOf(150, TimeUnit.MILLISECONDS), () -> { Assert.assertFalse(fired2.get()); fired2.set(true); }, errorHandler); Thread.sleep(100); Assert.assertFalse(fired2.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired2.get()); Assert.assertTrue(scheduler.hasScheduler()); Thread.sleep(100); Assert.assertTrue(fired2.get()); Assert.assertFalse(scheduler.hasScheduler()); } errorHandler.assertNoError(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void operation(RaftClient client) throws IOException { int length = Integer.parseInt(size); int num = Integer.parseInt(numFiles); AtomicLong totalBytes = new AtomicLong(0); String entropy = RandomStringUtils.randomAlphanumeric(10); byte[] fileValue = string2Bytes(RandomStringUtils.randomAscii(length)); FileStoreClient fileStoreClient = new FileStoreClient(client); System.out.println("Starting load now "); long startTime = System.currentTimeMillis(); List<CompletableFuture<Long>> futures = new ArrayList<>(); for (int i = 0; i < num; i++) { String path = "file-" + entropy + "-" + i; ByteBuffer b = ByteBuffer.wrap(fileValue); futures.add(fileStoreClient.writeAsync(path, 0, true, b)); } for (CompletableFuture<Long> future : futures) { Long writtenLen = future.join(); totalBytes.addAndGet(writtenLen); if (writtenLen != length) { System.out.println("File length written is wrong: " + writtenLen + length); } } long endTime = System.currentTimeMillis(); System.out.println("Total files written: " + futures.size()); System.out.println("Each files size: " + length); System.out.println("Total data written: " + totalBytes + " bytes"); System.out.println("Total time taken: " + (endTime - startTime) + " millis"); client.close(); System.exit(0); } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code @Override protected void operation(RaftClient client) throws IOException { List<String> paths = generateFiles(); FileStoreClient fileStoreClient = new FileStoreClient(client); System.out.println("Starting Async write now "); long startTime = System.currentTimeMillis(); long totalWrittenBytes = waitWriteFinish(writeByHeapByteBuffer(paths, fileStoreClient)); long endTime = System.currentTimeMillis(); System.out.println("Total files written: " + getNumFiles()); System.out.println("Each files size: " + getFileSizeInBytes()); System.out.println("Total data written: " + totalWrittenBytes + " bytes"); System.out.println("Total time taken: " + (endTime - startTime) + " millis"); client.close(); System.exit(0); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String toString() { return peer.getId() + "(next=" + nextIndex + ", match=" + matchIndex + "," + " attendVote=" + attendVote + ", lastRpcSendTime=" + lastRpcSendTime.get().elapsedTimeMs() + ", lastRpcResponseTime=" + lastRpcResponseTime.get().elapsedTimeMs() + ")"; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String toString() { return name + "(c" + getCommitIndex() + ",m" + getMatchIndex() + ",n" + getNextIndex() + ", attendVote=" + attendVote + ", lastRpcSendTime=" + lastRpcSendTime.get().elapsedTimeMs() + ", lastRpcResponseTime=" + lastRpcResponseTime.get().elapsedTimeMs() + ")"; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Inventory deserializeInventory(JsonElement data, String title) { Preconditions.checkArgument(data.isJsonPrimitive()); try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data.getAsString()))) { try (BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream)) { Inventory inventory = Bukkit.getServer().createInventory(null, dataInput.readInt(), title); for (int i = 0; i < inventory.getSize(); i++) { inventory.setItem(i, (ItemStack) dataInput.readObject()); } return inventory; } } catch (ClassNotFoundException | IOException e) { throw new RuntimeException(e); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public static Inventory deserializeInventory(JsonElement data, String title) { Preconditions.checkArgument(data.isJsonPrimitive()); return InventorySerialization.decodeInventory(data.getAsString(), title); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void enable() { // provide an info command Commands.create() .handler(c -> { LoaderUtils.getHelperImplementationPlugins().stream() .sorted(Comparator.comparing(Plugin::getName)) .forEach(pl -> Players.msg(c.sender(), "&7[&6helper&7] &7Running &6" + pl.getName() + " v" + pl.getDescription().getVersion() + "&7.")); }) .register("helper"); // provide default service implementations provideService(HologramFactory.class, new BukkitHologramFactory()); provideService(BungeeCord.class, new BungeeCordImpl(this)); if (isPluginPresent("ProtocolLib")) { PacketScoreboardProvider scoreboardProvider = new PacketScoreboardProvider(this); provideService(ScoreboardProvider.class, scoreboardProvider); provideService(PacketScoreboardProvider.class, scoreboardProvider); SignPromptFactory signPromptFactory = new PacketSignPromptFactory(); provideService(SignPromptFactory.class, signPromptFactory); try { IndividualHologramFactory hologramFactory = new PacketIndividualHologramFactory(); provideService(IndividualHologramFactory.class, hologramFactory); } catch (Throwable t) { // ignore?? } } if (isPluginPresent("Citizens")) { CitizensNpcFactory npcManager = bind(new CitizensNpcFactory()); provideService(NpcFactory.class, npcManager); provideService(CitizensNpcFactory.class, npcManager); } if (isPluginPresent("ViaVersion")) { BossBarFactory bossBarFactory = new ViaBossBarFactory(); provideService(BossBarFactory.class, bossBarFactory, ServicePriority.High); } else if (classExists("org.bukkit.boss.BossBar")) { BossBarFactory bossBarFactory = new BukkitBossBarFactory(getServer()); provideService(BossBarFactory.class, bossBarFactory); } } #location 31 #vulnerability type RESOURCE_LEAK
#fixed code @Override protected void enable() { // provide an info command if (getConfig().getBoolean("info-command", true)) { Commands.create() .handler(c -> LoaderUtils.getHelperImplementationPlugins().stream() .sorted(Comparator.comparing(Plugin::getName)) .forEach(pl -> Players.msg(c.sender(), "&7[&6helper&7] &7Running &6" + pl.getName() + " v" + pl.getDescription().getVersion() + "&7."))) .register("helper"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ItemStack deserializeItemstack(JsonElement data) { Preconditions.checkArgument(data.isJsonPrimitive()); try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data.getAsString()))) { try (BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream)) { return (ItemStack) dataInput.readObject(); } } catch (ClassNotFoundException | IOException e) { throw new RuntimeException(e); } } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code public static ItemStack deserializeItemstack(JsonElement data) { Preconditions.checkArgument(data.isJsonPrimitive()); return InventorySerialization.decodeItemStack(data.getAsString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public final void onEnable() { // schedule cleanup of the registry Scheduler.runTaskRepeatingAsync(terminableRegistry::cleanup, 600L, 600L).bindWith(terminableRegistry); // call subclass enable(); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Override public final void onEnable() { // schedule cleanup of the registry Scheduler.builder() .async() .after(10, TimeUnit.SECONDS) .every(30, TimeUnit.SECONDS) .run(terminableRegistry::cleanup) .bindWith(terminableRegistry); // call subclass enable(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ItemStack[] deserializeItemstacks(JsonElement data) { Preconditions.checkArgument(data.isJsonPrimitive()); try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data.getAsString()))) { try (BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream)) { ItemStack[] items = new ItemStack[dataInput.readInt()]; for (int i = 0; i < items.length; i++) { items[i] = (ItemStack) dataInput.readObject(); } return items; } } catch (ClassNotFoundException | IOException e) { throw new RuntimeException(e); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public static ItemStack[] deserializeItemstacks(JsonElement data) { Preconditions.checkArgument(data.isJsonPrimitive()); return InventorySerialization.decodeItemStacks(data.getAsString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized boolean saveApi(ApiResult apiResult) { boolean successful = false; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); preparedStatement = connection.prepareStatement("INSERT INTO \"api\" (\"publickey\",\"privatekey\",\"lastused\",\"data\") VALUES (?,?,?,?)"); preparedStatement.setString(1, apiResult.getPublicKey()); preparedStatement.setString(2, apiResult.getPrivateKey()); preparedStatement.setString(3, apiResult.getLastUsed()); preparedStatement.setString(4, apiResult.getData()); preparedStatement.execute(); successful = true; } catch(SQLException ex) { Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(resultSet); Helpers.closeQuietly(preparedStatement); } return successful; } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code public synchronized boolean saveApi(ApiResult apiResult) { boolean successful = false; Connection connection; PreparedStatement preparedStatement = null; try { connection = this.dbConfig.getConnection(); preparedStatement = connection.prepareStatement("INSERT INTO \"api\" (\"publickey\",\"privatekey\",\"lastused\",\"data\") VALUES (?,?,?,?)"); preparedStatement.setString(1, apiResult.getPublicKey()); preparedStatement.setString(2, apiResult.getPrivateKey()); preparedStatement.setString(3, apiResult.getLastUsed()); preparedStatement.setString(4, apiResult.getData()); preparedStatement.execute(); successful = true; } catch(SQLException ex) { Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(preparedStatement); } return successful; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized boolean saveApi(ApiResult apiResult) { boolean successful = false; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = this.dbConfig.getConnection(); stmt = conn.prepareStatement("INSERT INTO \"api\" (\"publickey\",\"privatekey\",\"lastused\",\"data\") VALUES (?,?,?,?)"); stmt.setString(1, apiResult.getPublicKey()); stmt.setString(2, apiResult.getPrivateKey()); stmt.setString(3, apiResult.getLastUsed()); stmt.setString(4, apiResult.getData()); stmt.execute(); successful = true; this.cache.remove(apiResult.getPublicKey()); this.genericCache.remove(apiAllApiCacheKey); } catch(SQLException ex) { successful = false; LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(rs); Helpers.closeQuietly(stmt); Helpers.closeQuietly(conn); } return successful; } #location 29 #vulnerability type NULL_DEREFERENCE
#fixed code public synchronized boolean saveApi(ApiResult apiResult) { boolean successful = false; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); preparedStatement = connection.prepareStatement("INSERT INTO \"api\" (\"publickey\",\"privatekey\",\"lastused\",\"data\") VALUES (?,?,?,?)"); preparedStatement.setString(1, apiResult.getPublicKey()); preparedStatement.setString(2, apiResult.getPrivateKey()); preparedStatement.setString(3, apiResult.getLastUsed()); preparedStatement.setString(4, apiResult.getData()); preparedStatement.execute(); successful = true; } catch(SQLException ex) { Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(resultSet); Helpers.closeQuietly(preparedStatement); Helpers.closeQuietly(connection); } return successful; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void getGitChangeSets() throws IOException, GitAPIException { Repository localRepository = new FileRepository(new File("./repo/server/.git")); Git git = new Git(localRepository); Iterable<RevCommit> logs = git.log().call(); List<String> revisions = new ArrayList<>(); for(RevCommit rev: logs) { System.out.println(rev.getCommitTime() + " " + rev.getName()); revisions.add(rev.getName()); } revisions = Lists.reverse(revisions); // TODO currently this is ignoring the very first commit changes need to include those for (int i = 1; i < revisions.size(); i++) { System.out.println("///////////////////////////////////////////////"); this.getRevisionChanges(revisions.get(i - 1), revisions.get(i)); } } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public void getGitChangeSets() throws IOException, GitAPIException { Repository localRepository = new FileRepository(new File("./repo/server/.git")); Git git = new Git(localRepository); Iterable<RevCommit> logs = git.log().call(); List<String> revisions = new ArrayList<>(); for(RevCommit rev: logs) { System.out.println(rev.getCommitTime() + " " + rev.getName()); revisions.add(rev.getName()); } revisions = Lists.reverse(revisions); // TODO currently this is ignoring the very first commit changes need to include those for (int i = 1; i < revisions.size(); i++) { System.out.println("///////////////////////////////////////////////"); this.getRevisionChanges(localRepository, git, revisions.get(i - 1), revisions.get(i)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException { BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(filePath), guessCharset(new File(filePath)))); List<String> fileLines = new ArrayList<>(); String line = ""; int lineCount = 0; while ((line = reader.readLine()) != null) { lineCount++; fileLines.add(line); if (lineCount == maxFileLineDepth) { return fileLines; } } return fileLines; } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException { List<String> fileLines = new ArrayList<>(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), guessCharset(new File(filePath)))); try { String line; int lineCount = 0; while ((line = reader.readLine()) != null) { lineCount++; fileLines.add(line); if (lineCount == maxFileLineDepth) { return fileLines; } } } finally { reader.close(); } return fileLines; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void execute(JobExecutionContext context) throws JobExecutionException { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while(CodeIndexer.shouldPauseAdding()) { Singleton.getLogger().info("Pausing parser."); return; } // Pull the next repo to index from the queue UniqueRepoQueue repoQueue = this.getNextQueuedRepo(); RepoResult repoResult = repoQueue.poll(); AbstractMap<String, Integer> runningIndexRepoJobs = Singleton.getRunningIndexRepoJobs(); if (repoResult != null && !runningIndexRepoJobs.containsKey(repoResult.getName())) { Singleton.getLogger().info("Indexing " + repoResult.getName()); try { runningIndexRepoJobs.put(repoResult.getName(), (int) (System.currentTimeMillis() / 1000)); JobDataMap data = context.getJobDetail().getJobDataMap(); String repoName = repoResult.getName(); String repoRemoteLocation = repoResult.getUrl(); String repoUserName = repoResult.getUsername(); String repoPassword = repoResult.getPassword(); String repoBranch = repoResult.getBranch(); String repoLocations = data.get("REPOLOCATIONS").toString(); this.LOWMEMORY = Boolean.parseBoolean(data.get("LOWMEMORY").toString()); // Check if sucessfully cloned, and if not delete and restart boolean cloneSucess = checkCloneUpdateSucess(repoLocations + repoName); if (cloneSucess == false) { // Delete the folder and delete from the index try { FileUtils.deleteDirectory(new File(repoLocations + "/" + repoName + "/")); CodeIndexer.deleteByReponame(repoName); } catch (IOException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + "\n with message: " + ex.getMessage()); } } deleteCloneUpdateSuccess(repoLocations + "/" + repoName); String repoGitLocation = repoLocations + "/" + repoName + "/.git/"; File f = new File(repoGitLocation); boolean existingRepo = f.exists(); boolean useCredentials = repoUserName != null && !repoUserName.isEmpty(); RepositoryChanged repositoryChanged = null; if (existingRepo) { repositoryChanged = this.updateExistingRepository(repoName, repoRemoteLocation, repoUserName, repoPassword, repoLocations, repoBranch, useCredentials); } else { repositoryChanged = this.getNewRepository(repoName, repoRemoteLocation, repoUserName, repoPassword, repoLocations, repoBranch, useCredentials); } // Write file indicating we have sucessfully cloned createCloneUpdateSuccess(repoLocations + "/" + repoName); // If the last index was not sucessful, then trigger full index boolean indexsuccess = checkIndexSucess(repoGitLocation); if (repositoryChanged.isChanged() || indexsuccess == false) { Singleton.getLogger().info("Update found indexing " + repoRemoteLocation); this.updateIndex(repoName, repoLocations, repoRemoteLocation, existingRepo, repositoryChanged); } } finally { // Clean up the job runningIndexRepoJobs.remove(repoResult.getName()); } } } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code public void execute(JobExecutionContext context) throws JobExecutionException { if (isEnabled() == false) { return; } Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while(CodeIndexer.shouldPauseAdding()) { Singleton.getLogger().info("Pausing parser."); return; } // Pull the next repo to index from the queue UniqueRepoQueue repoQueue = this.getNextQueuedRepo(); RepoResult repoResult = repoQueue.poll(); AbstractMap<String, Integer> runningIndexRepoJobs = Singleton.getRunningIndexRepoJobs(); if (repoResult != null && !runningIndexRepoJobs.containsKey(repoResult.getName())) { Singleton.getLogger().info("Indexing " + repoResult.getName()); try { runningIndexRepoJobs.put(repoResult.getName(), (int) (System.currentTimeMillis() / 1000)); JobDataMap data = context.getJobDetail().getJobDataMap(); String repoName = repoResult.getName(); String repoRemoteLocation = repoResult.getUrl(); String repoUserName = repoResult.getUsername(); String repoPassword = repoResult.getPassword(); String repoBranch = repoResult.getBranch(); String repoLocations = data.get("REPOLOCATIONS").toString(); this.LOWMEMORY = Boolean.parseBoolean(data.get("LOWMEMORY").toString()); // Check if sucessfully cloned, and if not delete and restart boolean cloneSucess = checkCloneUpdateSucess(repoLocations + repoName); if (cloneSucess == false) { // Delete the folder and delete from the index try { FileUtils.deleteDirectory(new File(repoLocations + "/" + repoName + "/")); CodeIndexer.deleteByReponame(repoName); } catch (IOException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + "\n with message: " + ex.getMessage()); } } deleteCloneUpdateSuccess(repoLocations + "/" + repoName); String repoGitLocation = repoLocations + "/" + repoName + "/.git/"; File f = new File(repoGitLocation); boolean existingRepo = f.exists(); boolean useCredentials = repoUserName != null && !repoUserName.isEmpty(); RepositoryChanged repositoryChanged = null; if (existingRepo) { repositoryChanged = this.updateExistingRepository(repoName, repoRemoteLocation, repoUserName, repoPassword, repoLocations, repoBranch, useCredentials); } else { repositoryChanged = this.getNewRepository(repoName, repoRemoteLocation, repoUserName, repoPassword, repoLocations, repoBranch, useCredentials); } // Write file indicating we have sucessfully cloned createCloneUpdateSuccess(repoLocations + "/" + repoName); // If the last index was not sucessful, then trigger full index boolean indexsuccess = checkIndexSucess(repoGitLocation); if (repositoryChanged.isChanged() || indexsuccess == false) { Singleton.getLogger().info("Update found indexing " + repoRemoteLocation); this.updateIndex(repoName, repoLocations, repoRemoteLocation, existingRepo, repositoryChanged); } } finally { // Clean up the job runningIndexRepoJobs.remove(repoResult.getName()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized void deleteRepoByName(String repositoryName) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = this.dbConfig.getConnection(); stmt = conn.prepareStatement("delete from repo where name=?;"); stmt.setString(1, repositoryName); stmt.execute(); this.cache.remove(repositoryName); this.genericCache.remove(this.repoCountCacheKey); this.genericCache.remove(this.repoAllRepoCacheKey); } catch(SQLException ex) { LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(rs); Helpers.closeQuietly(stmt); Helpers.closeQuietly(conn); } } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code public synchronized void deleteRepoByName(String repositoryName) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); preparedStatement = connection.prepareStatement("delete from repo where name=?;"); preparedStatement.setString(1, repositoryName); preparedStatement.execute(); } catch(SQLException ex) { LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(resultSet); Helpers.closeQuietly(preparedStatement); Helpers.closeQuietly(connection); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SlocCount countStats(String contents, String languageName) { if (contents == null || contents.isEmpty()) { return new SlocCount(); } FileClassifierResult fileClassifierResult = this.database.get(languageName); State currentState = State.S_BLANK; int endPoint = contents.length() - 1; String endString = null; int linesCount = 0; int blankCount = 0; int codeCount = 0; int commentCount = 0; int complexity = 0; for (int index=0; index < contents.length(); index++) { switch (currentState) { case S_BLANK: case S_MULTICOMMENT_BLANK: if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.line_comment, contents)) { currentState = State.S_COMMENT; break; } endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents); if (endString != null) { currentState = State.S_MULTICOMMENT; break; } endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.quotes, contents); if (endString != null) { currentState = State.S_STRING; break; } if (!this.isWhitespace(contents.charAt(index))) { currentState = State.S_CODE; if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.complexitychecks, contents)) { complexity++; } } break; case S_CODE: endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents); if (endString != null) { currentState = State.S_MULTICOMMENT_CODE; break; } endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.quotes, contents); if (endString != null) { currentState = State.S_STRING; break; } else if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.complexitychecks, contents)) { complexity++; } break; case S_STRING: if (contents.charAt(index-1) != '\\' && this.checkForMatchSingle(contents.charAt(index), index, endPoint, endString, contents)) { currentState = State.S_CODE; } break; case S_MULTICOMMENT: case S_MULTICOMMENT_CODE: if (this.checkForMatchMultiClose(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents)) { if (currentState == State.S_MULTICOMMENT_CODE) { currentState = State.S_CODE; } else { // TODO check if out of bounds if (index + 1 <= endPoint && this.isWhitespace(contents.charAt(index+1))) { currentState = State.S_MULTICOMMENT_BLANK; } else { currentState = State.S_MULTICOMMENT_CODE; } } } break; } // This means the end of processing the line so calculate the stats according to what state // we are currently in if (contents.charAt(index) == '\n' || index == endPoint) { linesCount++; switch (currentState) { case S_BLANK: blankCount++; break; case S_COMMENT: case S_MULTICOMMENT: case S_MULTICOMMENT_BLANK: commentCount++; break; case S_CODE: case S_STRING: case S_COMMENT_CODE: case S_MULTICOMMENT_CODE: codeCount++; break; } // If we are in a multiline comment that started after some code then we need // to move to a multiline comment if a multiline comment then stay there // otherwise we reset back into a blank state if (currentState != State.S_MULTICOMMENT && currentState != State.S_MULTICOMMENT_CODE) { currentState = State.S_BLANK; } else { currentState = State.S_MULTICOMMENT; } } } return new SlocCount(linesCount, blankCount, codeCount, commentCount, complexity); } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code public SlocCount countStats(String contents, String languageName) { if (contents == null || contents.isEmpty()) { return new SlocCount(); } FileClassifierResult fileClassifierResult = this.database.get(languageName); State currentState = State.S_BLANK; int endPoint = contents.length() - 1; String endString = null; ArrayList<String> endComments = new ArrayList<>(); int linesCount = 0; int blankCount = 0; int codeCount = 0; int commentCount = 0; int complexity = 0; for (int index=0; index < contents.length(); index++) { if (!isWhitespace(contents.charAt(index))) { switch (currentState) { case S_CODE: if (fileClassifierResult.nestedmultiline || endComments.size() == 0) { endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents); if (endString != null) { endComments.add(endString); currentState = State.S_MULTICOMMENT_CODE; break; } } if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.line_comment, contents)) { currentState = State.S_COMMENT_CODE; break; } endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.quotes, contents); if (endString != null) { currentState = State.S_STRING; break; } else if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.complexitychecks, contents)) { complexity++; } break; case S_MULTICOMMENT_BLANK: if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.line_comment, contents)) { currentState = State.S_COMMENT; break; } endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents); if (endString != null) { currentState = State.S_MULTICOMMENT; break; } endString = this.checkForMatchMultiOpen(contents.charAt(index), index, endPoint, fileClassifierResult.quotes, contents); if (endString != null) { currentState = State.S_STRING; break; } if (!this.isWhitespace(contents.charAt(index))) { currentState = State.S_CODE; if (this.checkForMatch(contents.charAt(index), index, endPoint, fileClassifierResult.complexitychecks, contents)) { complexity++; } } break; case S_STRING: if (contents.charAt(index - 1) != '\\' && this.checkForMatchSingle(contents.charAt(index), index, endPoint, endString, contents)) { currentState = State.S_CODE; } break; case S_MULTICOMMENT: case S_MULTICOMMENT_CODE: if (this.checkForMatchMultiClose(contents.charAt(index), index, endPoint, fileClassifierResult.multi_line, contents)) { if (currentState == State.S_MULTICOMMENT_CODE) { currentState = State.S_CODE; } else { // TODO check if out of bounds if (index + 1 <= endPoint && this.isWhitespace(contents.charAt(index + 1))) { currentState = State.S_MULTICOMMENT_BLANK; } else { currentState = State.S_MULTICOMMENT_CODE; } } } break; } } // This means the end of processing the line so calculate the stats according to what state // we are currently in if (contents.charAt(index) == '\n' || index == endPoint) { linesCount++; switch (currentState) { case S_BLANK: blankCount++; break; case S_COMMENT: case S_MULTICOMMENT: case S_MULTICOMMENT_BLANK: commentCount++; break; case S_CODE: case S_STRING: case S_COMMENT_CODE: case S_MULTICOMMENT_CODE: codeCount++; break; } // If we are in a multiline comment that started after some code then we need // to move to a multiline comment if a multiline comment then stay there // otherwise we reset back into a blank state if (currentState != State.S_MULTICOMMENT && currentState != State.S_MULTICOMMENT_CODE) { currentState = State.S_BLANK; } else { currentState = State.S_MULTICOMMENT; } } } return new SlocCount(linesCount, blankCount, codeCount, commentCount, complexity); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String languageGuesser(String fileName) { fileName = fileName.toLowerCase(); String extension = this.getExtension(fileName); for (String key: database.keySet()) { FileClassifierResult fileClassifierResult = database.get(key); for (String ext: fileClassifierResult.extensions) { if (extension.equals(ext)) { return key; } } } return Values.UNKNOWN_LANGUAGE; } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public String languageGuesser(String fileName) { fileName = fileName.toLowerCase(); String extension; Optional<String> lang = this.checkIfExtentionExists(fileName); if (!lang.isPresent()) { extension = this.getExtension(fileName); lang = this.checkIfExtentionExists(extension); } if (!lang.isPresent()) { extension = this.getExtension(fileName); lang = this.checkIfExtentionExists(extension); } return lang.orElse(Values.UNKNOWN_LANGUAGE); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<String> readFileLines(String filePath, int maxFileLineDepth) throws FileNotFoundException { List<String> lines = new ArrayList<>(); Scanner input = new Scanner(new File(filePath)); int counter = 0; while(input.hasNextLine() && counter < maxFileLineDepth) { lines.add(input.nextLine()); counter++; } return lines; } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public static List<String> readFileLines(String filePath, int maxFileLineDepth) throws FileNotFoundException { List<String> lines = new ArrayList<>(); Scanner input = new Scanner(new File(filePath)); try { int counter = 0; while (input.hasNextLine() && counter < maxFileLineDepth) { lines.add(input.nextLine()); counter++; } } finally { input.close(); } return lines; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public synchronized boolean saveRepo(RepoResult repoResult) { RepoResult existing = this.getRepoByName(repoResult.getName()); this.cache.remove(repoResult.getName()); boolean isNew = false; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; if (existing != null) { // Update with new details try { conn = this.dbConfig.getConnection(); stmt = conn.prepareStatement("UPDATE \"repo\" SET \"name\" = ?, \"scm\" = ?, \"url\" = ?, \"username\" = ?, \"password\" = ?, \"source\" = ?, \"branch\" = ? WHERE \"name\" = ?"); stmt.setString(1, repoResult.getName()); stmt.setString(2, repoResult.getScm()); stmt.setString(3, repoResult.getUrl()); stmt.setString(4, repoResult.getUsername()); stmt.setString(5, repoResult.getPassword()); stmt.setString(6, repoResult.getSource()); stmt.setString(7, repoResult.getBranch()); // Target the row stmt.setString(8, repoResult.getName()); stmt.execute(); } catch(SQLException ex) { LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(rs); Helpers.closeQuietly(stmt); Helpers.closeQuietly(conn); } } else { isNew = true; try { conn = this.dbConfig.getConnection(); stmt = conn.prepareStatement("INSERT INTO repo(\"name\",\"scm\",\"url\", \"username\", \"password\",\"source\",\"branch\") VALUES (?,?,?,?,?,?,?)"); stmt.setString(1, repoResult.getName()); stmt.setString(2, repoResult.getScm()); stmt.setString(3, repoResult.getUrl()); stmt.setString(4, repoResult.getUsername()); stmt.setString(5, repoResult.getPassword()); stmt.setString(6, repoResult.getSource()); stmt.setString(7, repoResult.getBranch()); stmt.execute(); } catch(SQLException ex) { LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(rs); Helpers.closeQuietly(stmt); Helpers.closeQuietly(conn); } } this.genericCache.remove(this.repoCountCacheKey); this.genericCache.remove(this.repoAllRepoCacheKey); return isNew; } #location 35 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public synchronized boolean saveRepo(RepoResult repoResult) { RepoResult existing = this.getRepoByName(repoResult.getName()); this.cache.remove(repoResult.getName()); boolean isNew = false; Connection connection = null; PreparedStatement preparedStatement = null; // Update with new details try { connection = this.dbConfig.getConnection(); if (existing != null) { preparedStatement = connection.prepareStatement("UPDATE \"repo\" SET \"name\" = ?, \"scm\" = ?, \"url\" = ?, \"username\" = ?, \"password\" = ?, \"source\" = ?, \"branch\" = ? WHERE \"name\" = ?"); preparedStatement.setString(8, repoResult.getName()); } else { isNew = true; preparedStatement = connection.prepareStatement("INSERT INTO repo(\"name\",\"scm\",\"url\", \"username\", \"password\",\"source\",\"branch\") VALUES (?,?,?,?,?,?,?)"); } preparedStatement.setString(1, repoResult.getName()); preparedStatement.setString(2, repoResult.getScm()); preparedStatement.setString(3, repoResult.getUrl()); preparedStatement.setString(4, repoResult.getUsername()); preparedStatement.setString(5, repoResult.getPassword()); preparedStatement.setString(6, repoResult.getSource()); preparedStatement.setString(7, repoResult.getBranch()); preparedStatement.execute(); } catch(SQLException ex) { LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(preparedStatement); Helpers.closeQuietly(connection); } this.genericCache.remove(this.repoCountCacheKey); this.genericCache.remove(this.repoAllRepoCacheKey); return isNew; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RepositoryChanged updateSvnRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, boolean useCredentials) { boolean changed = false; List<String> changedFiles = new ArrayList<>(); List<String> deletedFiles = new ArrayList<>(); Singleton.getLogger().info("SVN: attempting to pull latest from " + repoRemoteLocation + " for " + repoName); ProcessBuilder processBuilder; if (useCredentials) { processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "update"); } else { processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "update", "--username", repoUserName, "--password", repoPassword); } processBuilder.directory(new File(repoLocations + repoName)); Process process = null; try { String previousRevision = this.getCurrentRevision(repoLocations, repoName); Singleton.getLogger().info("SVN: update previous revision " + previousRevision); process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { Singleton.getLogger().info("svn update: " + line); } String currentRevision = this.getCurrentRevision(repoLocations, repoName); Singleton.getLogger().info("SVN: update current revision " + currentRevision); if (!previousRevision.equals(currentRevision)) { return this.getDiffBetweenRevisions(repoLocations, repoName, previousRevision); } } catch (IOException | InvalidPathException ex) { changed = false; Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " updateSvnRepository for " + repoName + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(process); } return new RepositoryChanged(changed, changedFiles, deletedFiles); } #location 40 #vulnerability type RESOURCE_LEAK
#fixed code public RepositoryChanged updateSvnRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, boolean useCredentials) { boolean changed = false; List<String> changedFiles = new ArrayList<>(); List<String> deletedFiles = new ArrayList<>(); Singleton.getLogger().info("SVN: attempting to pull latest from " + repoRemoteLocation + " for " + repoName); ProcessBuilder processBuilder; if (useCredentials) { processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "update"); } else { processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "update", "--username", repoUserName, "--password", repoPassword); } processBuilder.directory(new File(repoLocations + repoName)); Process process = null; BufferedReader bufferedReader = null; try { String previousRevision = this.getCurrentRevision(repoLocations, repoName); Singleton.getLogger().info("SVN: update previous revision " + previousRevision); process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); bufferedReader = new BufferedReader(isr); String line; while ((line = bufferedReader.readLine()) != null) { Singleton.getLogger().info("svn update: " + line); } String currentRevision = this.getCurrentRevision(repoLocations, repoName); Singleton.getLogger().info("SVN: update current revision " + currentRevision); if (!previousRevision.equals(currentRevision)) { return this.getDiffBetweenRevisions(repoLocations, repoName, previousRevision); } } catch (IOException | InvalidPathException ex) { changed = false; Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " updateSvnRepository for " + repoName + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(process); Helpers.closeQuietly(bufferedReader); } return new RepositoryChanged(changed, changedFiles, deletedFiles); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized void createTableIfMissing() { Connection connection; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); preparedStatement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS \"repo\" (\"name\" VARCHAR PRIMARY KEY NOT NULL ,\"scm\" VARCHAR,\"url\" VARCHAR,\"username\" VARCHAR,\"password\" VARCHAR, \"source\", \"branch\" VARCHAR, data text);"); preparedStatement.execute(); } catch (SQLException ex) { this.logger.severe(String.format("5ec972ce::error in class %s exception %s", ex.getClass(), ex.getMessage())); } finally { this.helpers.closeQuietly(resultSet); this.helpers.closeQuietly(preparedStatement); } } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code public synchronized void createTableIfMissing() { Connection connection; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); preparedStatement = connection.prepareStatement("SELECT name FROM sqlite_master WHERE type='table' AND name='repo';"); resultSet = preparedStatement.executeQuery(); String value = Values.EMPTYSTRING; while (resultSet.next()) { value = resultSet.getString("name"); } if (Singleton.getHelpers().isNullEmptyOrWhitespace(value)) { preparedStatement = connection.prepareStatement("CREATE TABLE IF NOT EXISTS \"repo\" (\"name\" VARCHAR PRIMARY KEY NOT NULL ,\"scm\" VARCHAR,\"url\" VARCHAR,\"username\" VARCHAR,\"password\" VARCHAR, \"source\", \"branch\" VARCHAR, data text);"); preparedStatement.execute(); } } catch (SQLException ex) { this.logger.severe(String.format("5ec972ce::error in class %s exception %s searchcode was to create the api key table, so api calls will fail", ex.getClass(), ex.getMessage())); } finally { this.helpers.closeQuietly(resultSet); this.helpers.closeQuietly(preparedStatement); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized void deleteApiByPublicKey(String publicKey) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = this.dbConfig.getConnection(); stmt = conn.prepareStatement("delete from api where publickey=?;"); stmt.setString(1, publicKey); stmt.execute(); this.cache.remove(publicKey); this.genericCache.remove(apiAllApiCacheKey); } catch(SQLException ex) { LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(rs); Helpers.closeQuietly(stmt); Helpers.closeQuietly(conn); } } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code public synchronized void deleteApiByPublicKey(String publicKey) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); preparedStatement = connection.prepareStatement("delete from api where publickey=?;"); preparedStatement.setString(1, publicKey); preparedStatement.execute(); } catch(SQLException ex) { Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(resultSet); Helpers.closeQuietly(preparedStatement); Helpers.closeQuietly(connection); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testSaveRetrieve() { String randomApiString = this.getRandomString(); this.api.saveApi(new ApiResult(0, randomApiString, "privateKey", "", "")); ApiResult apiResult = this.api.getApiByPublicKey(randomApiString); assertThat(apiResult.getPublicKey()).isEqualTo(randomApiString); assertThat(apiResult.getPrivateKey()).isEqualTo("privateKey"); this.api.deleteApiByPublicKey(randomApiString); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public void testSaveRetrieve() { String randomApiString = this.getRandomString(); this.api.saveApi(new ApiResult(0, randomApiString, "privateKey", "", "")); Optional<ApiResult> apiByPublicKey = this.api.getApiByPublicKey(randomApiString); assertThat(apiByPublicKey.get().getPublicKey()).isEqualTo(randomApiString); assertThat(apiByPublicKey.get().getPrivateKey()).isEqualTo("privateKey"); this.api.deleteApiByPublicKey(randomApiString); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized void deleteApiByPublicKey(String publicKey) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); preparedStatement = connection.prepareStatement("delete from api where publickey=?;"); preparedStatement.setString(1, publicKey); preparedStatement.execute(); } catch(SQLException ex) { Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(resultSet); Helpers.closeQuietly(preparedStatement); } } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code public synchronized void deleteApiByPublicKey(String publicKey) { Connection connection; PreparedStatement preparedStatement = null; try { connection = this.dbConfig.getConnection(); preparedStatement = connection.prepareStatement("delete from api where publickey=?;"); preparedStatement.setString(1, publicKey); preparedStatement.execute(); } catch(SQLException ex) { Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(preparedStatement); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<CodeOwner> getBlameInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) { List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize); // -w is to ignore whitespace bug ProcessBuilder processBuilder = new ProcessBuilder(this.GITBINARYPATH, "blame", "-c", "-w", fileName); // The / part is required due to centos bug for version 1.1.1 processBuilder.directory(new File(repoLocations + "/" + repoName)); Process process = null; try { process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; DateFormat df = new SimpleDateFormat("yyyy-mm-dd kk:mm:ss"); HashMap<String, CodeOwner> owners = new HashMap<>(); boolean foundSomething = false; while ((line = br.readLine()) != null) { Singleton.getLogger().info("Blame line " + repoName + fileName + ": " + line); String[] split = line.split("\t"); if (split.length > 2 && split[1].length() != 0) { foundSomething = true; String author = split[1].substring(1); int commitTime = (int) (System.currentTimeMillis() / 1000); try { commitTime = (int) (df.parse(split[2]).getTime() / 1000); } catch(ParseException ex) { Singleton.getLogger().info("time parse expection for " + repoName + fileName); } if (owners.containsKey(author)) { CodeOwner codeOwner = owners.get(author); codeOwner.incrementLines(); int timestamp = codeOwner.getMostRecentUnixCommitTimestamp(); if (commitTime > timestamp) { codeOwner.setMostRecentUnixCommitTimestamp(commitTime); } owners.put(author, codeOwner); } else { owners.put(author, new CodeOwner(author, 1, commitTime)); } } } if (foundSomething == false) { // External call for CentOS issue String[] split = fileName.split("/"); if ( split.length != 1) { codeOwners = getBlameInfoExternal(codeLinesSize, repoName, repoLocations, String.join("/", Arrays.asList(split).subList(1, split.length))); } } else { codeOwners = new ArrayList<>(owners.values()); } } catch (IOException | StringIndexOutOfBoundsException ex) { Singleton.getLogger().info("getBlameInfoExternal repoloc: " + repoLocations + "/" + repoName); Singleton.getLogger().info("getBlameInfoExternal fileName: " + fileName); Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getBlameInfoExternal for " + repoName + " " + fileName + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(process); } return codeOwners; } #location 67 #vulnerability type RESOURCE_LEAK
#fixed code public List<CodeOwner> getBlameInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) { List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize); // -w is to ignore whitespace bug ProcessBuilder processBuilder = new ProcessBuilder(this.GITBINARYPATH, "blame", "-c", "-w", fileName); // The / part is required due to centos bug for version 1.1.1 processBuilder.directory(new File(repoLocations + "/" + repoName)); Process process = null; BufferedReader bufferedReader = null; try { process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); bufferedReader = new BufferedReader(isr); String line; DateFormat df = new SimpleDateFormat("yyyy-mm-dd kk:mm:ss"); HashMap<String, CodeOwner> owners = new HashMap<>(); boolean foundSomething = false; while ((line = bufferedReader.readLine()) != null) { Singleton.getLogger().info("Blame line " + repoName + fileName + ": " + line); String[] split = line.split("\t"); if (split.length > 2 && split[1].length() != 0) { foundSomething = true; String author = split[1].substring(1); int commitTime = (int) (System.currentTimeMillis() / 1000); try { commitTime = (int) (df.parse(split[2]).getTime() / 1000); } catch(ParseException ex) { Singleton.getLogger().info("time parse expection for " + repoName + fileName); } if (owners.containsKey(author)) { CodeOwner codeOwner = owners.get(author); codeOwner.incrementLines(); int timestamp = codeOwner.getMostRecentUnixCommitTimestamp(); if (commitTime > timestamp) { codeOwner.setMostRecentUnixCommitTimestamp(commitTime); } owners.put(author, codeOwner); } else { owners.put(author, new CodeOwner(author, 1, commitTime)); } } } if (foundSomething == false) { // External call for CentOS issue String[] split = fileName.split("/"); if ( split.length != 1) { codeOwners = getBlameInfoExternal(codeLinesSize, repoName, repoLocations, String.join("/", Arrays.asList(split).subList(1, split.length))); } } else { codeOwners = new ArrayList<>(owners.values()); } } catch (IOException | StringIndexOutOfBoundsException ex) { Singleton.getLogger().info("getBlameInfoExternal repoloc: " + repoLocations + "/" + repoName); Singleton.getLogger().info("getBlameInfoExternal fileName: " + fileName); Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getBlameInfoExternal for " + repoName + " " + fileName + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(process); Helpers.closeQuietly(bufferedReader); } return codeOwners; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static java.util.Properties getProperties() { if (properties == null) { properties = new java.util.Properties(); try { properties.load(new FileInputStream("searchcode.properties")); } catch (IOException e) { // TODO Use second 'stdout' logger here, because ctor LoggerWrapper call this method Singleton.getLogger().severe("Unable to load 'searchcode.properties' file. Will resort to defaults for all values."); } } return properties; } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public static java.util.Properties getProperties() { if (properties == null) { properties = new java.util.Properties(); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream("searchcode.properties"); properties.load(fileInputStream); } catch (IOException e) { // TODO Use second 'stdout' logger here, because ctor LoggerWrapper call this method Singleton.getLogger().severe("Unable to load 'searchcode.properties' file. Will resort to defaults for all values."); } finally { IOUtils.closeQuietly(fileInputStream); } } return properties; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testRepoSaveDelete() { this.repo.saveRepo(new RepoResult(-1, "myname", "git", "myurl", "username", "password", "mysource", "mybranch", "{}")); RepoResult result = this.repo.getRepoByName("myname"); assertThat(result.getName()).isEqualTo("myname"); assertThat(result.getScm()).isEqualTo("git"); assertThat(result.getUrl()).isEqualTo("myurl"); assertThat(result.getUsername()).isEqualTo("username"); assertThat(result.getPassword()).isEqualTo("password"); assertThat(result.getSource()).isEqualTo("mysource"); assertThat(result.getBranch()).isEqualTo("mybranch"); assertThat(result.getData().averageIndexTimeSeconds).isEqualTo(0); this.repo.deleteRepoByName("myname"); result = this.repo.getRepoByName("myname"); assertThat(result).isNull(); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void testRepoSaveDelete() { this.repo.saveRepo(new RepoResult(-1, "myname", "git", "myurl", "username", "password", "mysource", "mybranch", "{}")); Optional<RepoResult> repoResult = this.repo.getRepoByName("myname"); RepoResult result = repoResult.get(); assertThat(result.getName()).isEqualTo("myname"); assertThat(result.getScm()).isEqualTo("git"); assertThat(result.getUrl()).isEqualTo("myurl"); assertThat(result.getUsername()).isEqualTo("username"); assertThat(result.getPassword()).isEqualTo("password"); assertThat(result.getSource()).isEqualTo("mysource"); assertThat(result.getBranch()).isEqualTo("mybranch"); assertThat(result.getData().averageIndexTimeSeconds).isEqualTo(0); this.repo.deleteRepoByName("myname"); Optional<RepoResult> repoResult2 = this.repo.getRepoByName("myname"); assertThat(repoResult2.isPresent()).isFalse(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RepositoryChanged checkoutSvnRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, boolean useCredentials) { boolean successful = false; Singleton.getLogger().info("Attempting to checkout " + repoRemoteLocation); ProcessBuilder processBuilder; // http://serverfault.com/questions/158349/how-to-stop-subversion-from-prompting-about-server-certificate-verification-fai // http://stackoverflow.com/questions/34687/subversion-ignoring-password-and-username-options#38386 if (useCredentials) { processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "checkout", "--no-auth-cache", "--non-interactive", repoRemoteLocation, repoName); } else { processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "checkout", "--no-auth-cache", "--non-interactive", "--username", repoUserName, "--password", repoPassword, repoRemoteLocation, repoName); } processBuilder.directory(new File(repoLocations)); Process process = null; try { File f = new File(repoLocations); if (!f.exists()) { f.mkdir(); } process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { Singleton.getLogger().info(line); } successful = true; } catch (IOException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " checkoutSvnRepository for " + repoName + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(process); } RepositoryChanged repositoryChanged = new RepositoryChanged(successful); repositoryChanged.setClone(true); return repositoryChanged; } #location 39 #vulnerability type RESOURCE_LEAK
#fixed code public RepositoryChanged checkoutSvnRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, boolean useCredentials) { boolean successful = false; Singleton.getLogger().info("Attempting to checkout " + repoRemoteLocation); ProcessBuilder processBuilder; // http://serverfault.com/questions/158349/how-to-stop-subversion-from-prompting-about-server-certificate-verification-fai // http://stackoverflow.com/questions/34687/subversion-ignoring-password-and-username-options#38386 if (useCredentials) { processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "checkout", "--no-auth-cache", "--non-interactive", repoRemoteLocation, repoName); } else { processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "checkout", "--no-auth-cache", "--non-interactive", "--username", repoUserName, "--password", repoPassword, repoRemoteLocation, repoName); } processBuilder.directory(new File(repoLocations)); Process process = null; BufferedReader bufferedReader = null; try { File file = new File(repoLocations); if (!file.exists()) { boolean success = file.mkdir(); if (!success) { throw new IOException("Was unable to create directory " + repoLocations); } } process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); bufferedReader = new BufferedReader(isr); String line; while ((line = bufferedReader.readLine()) != null) { Singleton.getLogger().info(line); } successful = true; } catch (IOException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " checkoutSvnRepository for " + repoName + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(process); Helpers.closeQuietly(bufferedReader); } RepositoryChanged repositoryChanged = new RepositoryChanged(successful); repositoryChanged.setClone(true); return repositoryChanged; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testIsBinaryWhiteListedExtension() { SearchcodeLib sl = new SearchcodeLib(); ArrayList<String> codeLines = new ArrayList<>(); codeLines.add("你你你你你你你你你你你你你你你你你你你你你你你你你你你"); FileClassifier fileClassifier = new FileClassifier(); for(Classifier classifier: fileClassifier.getClassifier()) { for(String extension: classifier.extensions) { BinaryFinding isBinary = sl.isBinary(codeLines, "myfile." + extension); assertThat(isBinary.isBinary()).isFalse(); } } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public void testIsBinaryWhiteListedExtension() { SearchcodeLib sl = new SearchcodeLib(); ArrayList<String> codeLines = new ArrayList<>(); codeLines.add("你你你你你你你你你你你你你你你你你你你你你你你你你你你"); FileClassifier fileClassifier = new FileClassifier(); for(FileClassifierResult fileClassifierResult: fileClassifier.getDatabase()) { for(String extension: fileClassifierResult.extensions) { BinaryFinding isBinary = sl.isBinary(codeLines, "myfile." + extension); assertThat(isBinary.isBinary()).isFalse(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void indexDocument(Queue<CodeIndexDocument> documentQueue) throws IOException { // Need to connect to each sphinx config eventually SphinxSearchConfig sphinxSearchConfig = new SphinxSearchConfig(); Connection connection = null; PreparedStatement stmt = null; try { connection = sphinxSearchConfig.getConnection(); } catch (SQLException ex) { return; } finally { this.helpers.closeQuietly(connection); } try { // for (SearchcodeCodeResult codeResult: codeResultList) { // try { // stmt = connection.prepareStatement("REPLACE INTO codesearchrt1 VALUES(?,?,?,?,?,?,?,?,?)"); // // stmt.setInt(1, codeResult.getId()); // stmt.setString(2, CodeIndexer.runCodeIndexPipeline(Singleton.getSearchCodeLib(), codeResult.getContent())); // stmt.setString(3, codeResult.getFilename()); // stmt.setInt(4, codeResult.getRepoid()); // stmt.setInt(5, codeResult.getFiletypeid()); // stmt.setInt(6, codeResult.getLangugeid()); // stmt.setInt(7, codeResult.getSourceid()); // stmt.setInt(8, 0); //CCR // stmt.setInt(9, codeResult.getLinescount()); // stmt.execute(); // } catch (SQLException ex) { // Singleton.getLogger().warning(ex.toString()); // } // } } finally { this.helpers.closeQuietly(stmt); this.helpers.closeQuietly(connection); } } #location 38 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void indexDocument(Queue<CodeIndexDocument> documentQueue) throws IOException { // Need to connect to each sphinx config eventually SphinxSearchConfig sphinxSearchConfig = new SphinxSearchConfig(); Connection connection = null; PreparedStatement stmt = null; try { connection = sphinxSearchConfig.getConnection(); } catch (SQLException ignored) { } CodeIndexDocument codeIndexDocument = documentQueue.poll(); List<CodeIndexDocument> codeIndexDocumentList = new ArrayList<>(); while (codeIndexDocument != null) { codeIndexDocumentList.add(codeIndexDocument); codeIndexDocument = documentQueue.poll(); } try { for (CodeIndexDocument codeResult: codeIndexDocumentList) { try { stmt = connection.prepareStatement("REPLACE INTO codesearchrt1 VALUES(?,?,?,?,?,?,?,?,?)"); // stmt.setInt(1, codeResult.getId()); // stmt.setString(2, CodeIndexer.runCodeIndexPipeline(Singleton.getSearchCodeLib(), codeResult.getContent())); stmt.setString(3, codeResult.getFileName()); // stmt.setInt(4, codeResult.getRepoid()); // stmt.setInt(5, codeResult.getFiletypeid()); // stmt.setInt(6, codeResult.getLangugeid()); // stmt.setInt(7, codeResult.getSourceid()); // stmt.setInt(8, 0); //CCR // stmt.setInt(9, codeResult.getLinescount()); stmt.execute(); } catch (SQLException ex) { Singleton.getLogger().warning(ex.toString()); } } } finally { this.helpers.closeQuietly(stmt); this.helpers.closeQuietly(connection); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private CodeOwner getInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) { CodeOwner owner = new CodeOwner("Unknown", codeLinesSize, (int)(System.currentTimeMillis() / 1000)); ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml", fileName); processBuilder.directory(new File(repoLocations + repoName)); Process process = null; try { process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; StringBuilder bf = new StringBuilder(); while ((line = br.readLine()) != null) { bf.append(Helpers.removeUTF8BOM(line)); } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new ByteArrayInputStream(bf.toString().getBytes())); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("entry"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; Node node = eElement.getElementsByTagName("commit").item(0); Element e = (Element) node; owner.setName(e.getElementsByTagName("author").item(0).getTextContent()); } } } catch (IOException | ParserConfigurationException | SAXException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getInfoExternal for " + repoName + " " + fileName + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(process); } return owner; } #location 43 #vulnerability type RESOURCE_LEAK
#fixed code private CodeOwner getInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) { CodeOwner owner = new CodeOwner("Unknown", codeLinesSize, (int)(System.currentTimeMillis() / 1000)); ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml", fileName); processBuilder.directory(new File(repoLocations + repoName)); Process process = null; BufferedReader bufferedReader = null; try { process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); bufferedReader = new BufferedReader(isr); String line; StringBuilder bf = new StringBuilder(); while ((line = bufferedReader.readLine()) != null) { bf.append(Helpers.removeUTF8BOM(line)); } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new ByteArrayInputStream(bf.toString().getBytes())); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("entry"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; Node node = eElement.getElementsByTagName("commit").item(0); Element e = (Element) node; owner.setName(e.getElementsByTagName("author").item(0).getTextContent()); } } } catch (IOException | ParserConfigurationException | SAXException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getInfoExternal for " + repoName + " " + fileName + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(process); Helpers.closeQuietly(bufferedReader); } return owner; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public synchronized boolean saveRepo(RepoResult repoResult) { RepoResult existing = this.getRepoByName(repoResult.getName()); this.cache.remove(repoResult.getName()); boolean isNew = false; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; if (existing != null) { // Update with new details try { conn = this.dbConfig.getConnection(); stmt = conn.prepareStatement("UPDATE \"repo\" SET \"name\" = ?, \"scm\" = ?, \"url\" = ?, \"username\" = ?, \"password\" = ?, \"source\" = ?, \"branch\" = ? WHERE \"name\" = ?"); stmt.setString(1, repoResult.getName()); stmt.setString(2, repoResult.getScm()); stmt.setString(3, repoResult.getUrl()); stmt.setString(4, repoResult.getUsername()); stmt.setString(5, repoResult.getPassword()); stmt.setString(6, repoResult.getSource()); stmt.setString(7, repoResult.getBranch()); // Target the row stmt.setString(8, repoResult.getName()); stmt.execute(); } catch(SQLException ex) { LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(rs); Helpers.closeQuietly(stmt); Helpers.closeQuietly(conn); } } else { isNew = true; try { conn = this.dbConfig.getConnection(); stmt = conn.prepareStatement("INSERT INTO repo(\"name\",\"scm\",\"url\", \"username\", \"password\",\"source\",\"branch\") VALUES (?,?,?,?,?,?,?)"); stmt.setString(1, repoResult.getName()); stmt.setString(2, repoResult.getScm()); stmt.setString(3, repoResult.getUrl()); stmt.setString(4, repoResult.getUsername()); stmt.setString(5, repoResult.getPassword()); stmt.setString(6, repoResult.getSource()); stmt.setString(7, repoResult.getBranch()); stmt.execute(); } catch(SQLException ex) { LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(rs); Helpers.closeQuietly(stmt); Helpers.closeQuietly(conn); } } this.genericCache.remove(this.repoCountCacheKey); this.genericCache.remove(this.repoAllRepoCacheKey); return isNew; } #location 35 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public synchronized boolean saveRepo(RepoResult repoResult) { RepoResult existing = this.getRepoByName(repoResult.getName()); this.cache.remove(repoResult.getName()); boolean isNew = false; Connection connection = null; PreparedStatement preparedStatement = null; // Update with new details try { connection = this.dbConfig.getConnection(); if (existing != null) { preparedStatement = connection.prepareStatement("UPDATE \"repo\" SET \"name\" = ?, \"scm\" = ?, \"url\" = ?, \"username\" = ?, \"password\" = ?, \"source\" = ?, \"branch\" = ? WHERE \"name\" = ?"); preparedStatement.setString(8, repoResult.getName()); } else { isNew = true; preparedStatement = connection.prepareStatement("INSERT INTO repo(\"name\",\"scm\",\"url\", \"username\", \"password\",\"source\",\"branch\") VALUES (?,?,?,?,?,?,?)"); } preparedStatement.setString(1, repoResult.getName()); preparedStatement.setString(2, repoResult.getScm()); preparedStatement.setString(3, repoResult.getUrl()); preparedStatement.setString(4, repoResult.getUsername()); preparedStatement.setString(5, repoResult.getPassword()); preparedStatement.setString(6, repoResult.getSource()); preparedStatement.setString(7, repoResult.getBranch()); preparedStatement.execute(); } catch(SQLException ex) { LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(preparedStatement); Helpers.closeQuietly(connection); } this.genericCache.remove(this.repoCountCacheKey); this.genericCache.remove(this.repoAllRepoCacheKey); return isNew; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SourceCodeDTO saveCode(CodeIndexDocument codeIndexDocument) { Optional<SourceCodeDTO> existing = this.getByCodeIndexDocument(codeIndexDocument); Connection conn = null; PreparedStatement stmt = null; try { conn = this.dbConfig.getConnection(); String query = "INSERT INTO `sourcecode` (`id`, `repoid`, `languageid`, `sourceid`, `ownerid`, `licenseid`, `location`, `filename`, `content`, `hash`, `simhash`, `linescount`, `data`) VALUES " + "(NULL, ?, (SELECT id FROM languagetype WHERE type = ?), ?, ?, ?, ?, ?, COMPRESS(?), ?, ?, ?, ?)"; if (existing.isPresent()) { return existing.get(); } stmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); stmt.setInt(1, 31337); stmt.setString(2, codeIndexDocument.getLanguageName()); stmt.setInt(3, 31337); stmt.setInt(4, 31337); stmt.setInt(5, 31337); stmt.setString(6, this.getLocation(codeIndexDocument)); stmt.setString(7, codeIndexDocument.getFileName()); stmt.setString(8, codeIndexDocument.getContents()); stmt.setString(9, codeIndexDocument.getHash()); stmt.setString(10, "simhash"); stmt.setInt(11, codeIndexDocument.getCodeLines()); stmt.setString(12, "{}"); stmt.execute(); ResultSet tableKeys = stmt.getGeneratedKeys(); tableKeys.next(); int autoGeneratedID = tableKeys.getInt(1); return this.getById(autoGeneratedID).get(); } catch (SQLException ex) { Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { this.helpers.closeQuietly(stmt); // this.helpers.closeQuietly(conn); } return null; } #location 41 #vulnerability type NULL_DEREFERENCE
#fixed code public SourceCodeDTO saveCode(CodeIndexDocument codeIndexDocument) { Optional<SourceCodeDTO> existing = this.getByCodeIndexDocument(codeIndexDocument); Connection conn = null; PreparedStatement stmt = null; try { conn = this.dbConfig.getConnection(); // If the language does not exist then create it Optional<LanguageTypeDTO> languageType = this.languageType.createLanguageType(codeIndexDocument.getLanguageName()); String query = "INSERT INTO `sourcecode` (`id`, `repoid`, `languageid`, `sourceid`, `ownerid`, `licenseid`, `location`, `filename`, `content`, `hash`, `simhash`, `linescount`, `data`) VALUES " + "(NULL, ?, ?, ?, ?, ?, ?, ?, COMPRESS(?), ?, ?, ?, ?)"; // Why is this here and not above?? if (existing.isPresent()) { return existing.get(); } stmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); stmt.setInt(1, 31337); stmt.setInt(2, languageType.get().getId()); stmt.setInt(3, 31337); stmt.setInt(4, 31337); stmt.setInt(5, 31337); stmt.setString(6, this.getLocation(codeIndexDocument)); stmt.setString(7, codeIndexDocument.getFileName()); stmt.setString(8, codeIndexDocument.getContents()); stmt.setString(9, codeIndexDocument.getHash()); stmt.setString(10, "simhash"); stmt.setInt(11, codeIndexDocument.getCodeLines()); stmt.setString(12, "{}"); stmt.execute(); ResultSet tableKeys = stmt.getGeneratedKeys(); tableKeys.next(); int autoGeneratedID = tableKeys.getInt(1); return this.getById(autoGeneratedID).get(); } catch (SQLException ex) { Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { this.helpers.closeQuietly(stmt); // this.helpers.closeQuietly(conn); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testMultipleRetrieveCache() { String randomApiString = this.getRandomString(); this.api.saveApi(new ApiResult(0, randomApiString, "privateKey", "", "")); for(int i=0; i < 500; i++) { ApiResult apiResult = this.api.getApiByPublicKey(randomApiString); assertThat(apiResult.getPublicKey()).isEqualTo(randomApiString); assertThat(apiResult.getPrivateKey()).isEqualTo("privateKey"); } this.api.deleteApiByPublicKey(randomApiString); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public void testMultipleRetrieveCache() { String randomApiString = this.getRandomString(); this.api.saveApi(new ApiResult(0, randomApiString, "privateKey", "", "")); for(int i=0; i < 500; i++) { Optional<ApiResult> apiByPublicKey = this.api.getApiByPublicKey(randomApiString); assertThat(apiByPublicKey.get().getPublicKey()).isEqualTo(randomApiString); assertThat(apiByPublicKey.get().getPrivateKey()).isEqualTo("privateKey"); } this.api.deleteApiByPublicKey(randomApiString); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException { BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(filePath), guessCharset(new File(filePath)))); List<String> fileLines = new ArrayList<>(); String line = ""; int lineCount = 0; while ((line = reader.readLine()) != null) { lineCount++; fileLines.add(line); if (lineCount == maxFileLineDepth) { return fileLines; } } return fileLines; } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException { List<String> fileLines = new ArrayList<>(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), guessCharset(new File(filePath)))); try { String line; int lineCount = 0; while ((line = reader.readLine()) != null) { lineCount++; fileLines.add(line); if (lineCount == maxFileLineDepth) { return fileLines; } } } finally { reader.close(); } return fileLines; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getCurrentRevision(String repoLocations, String repoName) { String currentRevision = ""; ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml"); processBuilder.directory(new File(repoLocations + repoName)); Process process = null; try { process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(Helpers.removeUTF8BOM(line)); } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Singleton.getLogger().info("getCurrentRevision: " + repoName + " " + sb.toString()); Document doc = dBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes())); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("entry"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; currentRevision = eElement.getAttribute("revision"); } } } catch (IOException | ParserConfigurationException | SAXException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getCurrentRevision for " + repoName + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(process); } return currentRevision; } #location 39 #vulnerability type RESOURCE_LEAK
#fixed code public String getCurrentRevision(String repoLocations, String repoName) { String currentRevision = ""; ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml"); processBuilder.directory(new File(repoLocations + repoName)); Process process = null; BufferedReader bufferedReader = null; try { process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); bufferedReader = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { sb.append(Helpers.removeUTF8BOM(line)); } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Singleton.getLogger().info("getCurrentRevision: " + repoName + " " + sb.toString()); Document doc = dBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes())); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("entry"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; currentRevision = eElement.getAttribute("revision"); } } } catch (IOException | ParserConfigurationException | SAXException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getCurrentRevision for " + repoName + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(process); Helpers.closeQuietly(bufferedReader); } return currentRevision; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testExecuteNothingInQueue() throws JobExecutionException { IndexGitRepoJob indexGitRepoJob = new IndexGitRepoJob(); IndexGitRepoJob spy = spy(indexGitRepoJob); when(spy.getNextQueuedRepo()).thenReturn(new UniqueRepoQueue()); spy.execute(null); assertThat(spy.haveRepoResult).isFalse(); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public void testExecuteNothingInQueue() throws JobExecutionException { IndexGitRepoJob indexGitRepoJob = new IndexGitRepoJob(); IndexGitRepoJob spy = spy(indexGitRepoJob); when(spy.getNextQueuedRepo()).thenReturn(new UniqueRepoQueue()); JobExecutionContext mockContext = Mockito.mock(JobExecutionContext.class); JobDetail mockDetail = Mockito.mock(JobDetail.class); JobDataMap mockJobDataMap = Mockito.mock(JobDataMap.class); CodeIndexer mockCodeIndexer = Mockito.mock(CodeIndexer.class); when(mockJobDataMap.get("REPOLOCATIONS")).thenReturn(""); when(mockJobDataMap.get("LOWMEMORY")).thenReturn("true"); when(mockDetail.getJobDataMap()).thenReturn(mockJobDataMap); when(mockContext.getJobDetail()).thenReturn(mockDetail); when(mockCodeIndexer.shouldPauseAdding()).thenReturn(false); spy.codeIndexer = mockCodeIndexer; spy.execute(mockContext); assertThat(spy.haveRepoResult).isFalse(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized boolean saveData(String key, String value) { String existing = this.getDataByName(key); boolean isNew = false; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; if (existing != null) { try { conn = this.dbConfig.getConnection(); stmt = conn.prepareStatement("UPDATE \"data\" SET \"key\" = ?, \"value\" = ? WHERE \"key\" = ?"); stmt.setString(1, key); stmt.setString(2, value); stmt.setString(3, key); stmt.execute(); } catch(SQLException ex) { LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(rs); Helpers.closeQuietly(stmt); Helpers.closeQuietly(conn); } } else { isNew = true; try { conn = this.dbConfig.getConnection(); stmt = conn.prepareStatement("INSERT INTO data(\"key\",\"value\") VALUES (?,?)"); stmt.setString(1, key); stmt.setString(2, value); stmt.execute(); } catch(SQLException ex) { LOGGER.severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(rs); Helpers.closeQuietly(stmt); Helpers.closeQuietly(conn); } } // Update cache with new value if (value != null) { this.cache.put(key, value); } else { this.cache.remove(key); } return isNew; } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code public synchronized boolean saveData(String key, String value) { String existing = this.getDataByName(key); boolean isNew = false; Connection connection = null; PreparedStatement preparedStatement = null; try { connection = this.dbConfig.getConnection(); if (existing != null) { preparedStatement = connection.prepareStatement("UPDATE \"data\" SET \"key\" = ?, \"value\" = ? WHERE \"key\" = ?"); preparedStatement.setString(1, key); preparedStatement.setString(2, value); preparedStatement.setString(3, key); } else { isNew = true; preparedStatement = connection.prepareStatement("INSERT INTO data(\"key\",\"value\") VALUES (?,?)"); preparedStatement.setString(1, key); preparedStatement.setString(2, value); } preparedStatement.execute(); } catch(SQLException ex) { Singleton.getLogger().severe(" caught a " + ex.getClass() + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(preparedStatement); Helpers.closeQuietly(connection); } // Update cache with new value if (value != null) { this.cache.put(key, value); } else { this.cache.remove(key); } return isNew; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized void deleteRepoByName(String repositoryName) { Connection connection; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); preparedStatement = connection.prepareStatement("delete from repo where name=?;"); preparedStatement.setString(1, repositoryName); preparedStatement.execute(); } catch (SQLException ex) { this.logger.severe(String.format("8f05a49c::error in class %s exception %s searchcode was unable to delete repository by name %s, this is unlikely to break anything but there should be other errors in the logs", ex.getClass(), ex.getMessage(), repositoryName)); } finally { this.helpers.closeQuietly(resultSet); this.helpers.closeQuietly(preparedStatement); } } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code public synchronized void deleteRepoByName(String repositoryName) { ConnStmtRs connStmtRs = new ConnStmtRs(); try { connStmtRs.conn = this.dbConfig.getConnection(); connStmtRs.stmt = connStmtRs.conn.prepareStatement("delete from repo where name=?;"); connStmtRs.stmt.setString(1, repositoryName); connStmtRs.stmt.execute(); } catch (SQLException ex) { this.logger.severe(String.format("8f05a49c::error in class %s exception %s searchcode was unable to delete repository by name %s, this is unlikely to break anything but there should be other errors in the logs", ex.getClass(), ex.getMessage(), repositoryName)); } finally { this.helpers.closeQuietly(connStmtRs, this.dbConfig.closeConnection()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RepositoryChanged getDiffBetweenRevisions(String repoLocations, String repoName, String startRevision) { // svn diff -r 4000:HEAD --summarize --xml List<String> changedFiles = new ArrayList<>(); List<String> deletedFiles = new ArrayList<>(); ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "diff", "-r", startRevision + ":HEAD", "--summarize", "--xml"); processBuilder.directory(new File(repoLocations + repoName)); Process process = null; try { process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; StringBuffer sb = new StringBuffer(); while ((line = br.readLine()) != null) { Singleton.getLogger().info("svn diff: " + line); sb.append(Helpers.removeUTF8BOM(line)); } Singleton.getLogger().info("Before XML parsing: " + sb.toString()); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes())); doc.getDocumentElement().normalize(); Element node = (Element)doc.getElementsByTagName("diff").item(0); node = (Element)node.getElementsByTagName("paths").item(0); NodeList nList = node.getElementsByTagName("path"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String type = eElement.getAttribute("item"); String path = eElement.getTextContent(); if ("modified".equals(type) || "added".equals(type)) { changedFiles.add(path); } else { deletedFiles.add(path); } } } } catch(IOException | ParserConfigurationException | SAXException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getDiffBetweenRevisions for " + repoName + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(process); } return new RepositoryChanged(true, changedFiles, deletedFiles); } #location 57 #vulnerability type RESOURCE_LEAK
#fixed code public RepositoryChanged getDiffBetweenRevisions(String repoLocations, String repoName, String startRevision) { // svn diff -r 4000:HEAD --summarize --xml List<String> changedFiles = new ArrayList<>(); List<String> deletedFiles = new ArrayList<>(); ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "diff", "-r", startRevision + ":HEAD", "--summarize", "--xml"); processBuilder.directory(new File(repoLocations + repoName)); Process process = null; BufferedReader bufferedReader = null; try { process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); bufferedReader = new BufferedReader(isr); String line; StringBuffer sb = new StringBuffer(); while ((line = bufferedReader.readLine()) != null) { Singleton.getLogger().info("svn diff: " + line); sb.append(Helpers.removeUTF8BOM(line)); } Singleton.getLogger().info("Before XML parsing: " + sb.toString()); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes())); doc.getDocumentElement().normalize(); Element node = (Element)doc.getElementsByTagName("diff").item(0); node = (Element)node.getElementsByTagName("paths").item(0); NodeList nList = node.getElementsByTagName("path"); for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; String type = eElement.getAttribute("item"); String path = eElement.getTextContent(); if ("modified".equals(type) || "added".equals(type)) { changedFiles.add(path); } else { deletedFiles.add(path); } } } } catch(IOException | ParserConfigurationException | SAXException ex) { Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass() + " getDiffBetweenRevisions for " + repoName + "\n with message: " + ex.getMessage()); } finally { Helpers.closeQuietly(process); Helpers.closeQuietly(bufferedReader); } return new RepositoryChanged(true, changedFiles, deletedFiles); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private String runCommand(String directory, String... command) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(new File(directory)); Process process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } return sb.toString(); } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code private String runCommand(String directory, String... command) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(new File(directory)); Process process = processBuilder.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is, Values.CHARSET_UTF8); BufferedReader br = new BufferedReader(isr); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } return sb.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void getGitChangeSets() throws IOException, GitAPIException { Repository localRepository = new FileRepository(new File("./repo/.timelord/test/.git")); Git git = new Git(localRepository); Iterable<RevCommit> logs = git.log().call(); for(RevCommit rev: logs) { System.out.println(rev.getName()); git.checkout().setName(rev.getName()).call(); } } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code public void getGitChangeSets() throws IOException, GitAPIException { Repository localRepository = new FileRepository(new File("./repo/server/.git")); Git git = new Git(localRepository); Iterable<RevCommit> logs = git.log().call(); List<String> revisions = new ArrayList<>(); for(RevCommit rev: logs) { System.out.println(rev.getCommitTime() + " " + rev.getName()); revisions.add(rev.getName()); } revisions = Lists.reverse(revisions); for (int i = 1; i < revisions.size(); i++) { System.out.println("///////////////////////////////////////////////"); this.getRevisionChanges(revisions.get(i - 1), revisions.get(i)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void reindexByRepo(RepoResult repo) { // Stop adding to job processing queue this.repoAdderPause = true; this.repoJobExit = true; // Clear job processing queue queue // CLear index queue this.codeIndexDocumentQueue.clear(); // Delete repo from index // Delete repo from db } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void reindexByRepo(RepoResult repo) { // Stop adding to job processing queue //this.repoAdderPause = true; //this.repoJobExit = true; // Clear job processing queue queue // CLear index queue //this.codeIndexDocumentQueue.clear(); // Delete repo from index // Delete repo from db }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SourceCodeDTO saveCode(CodeIndexDocument codeIndexDocument) { Optional<SourceCodeDTO> existing = this.getByCodeIndexDocument(codeIndexDocument); Connection conn = null; PreparedStatement stmt = null; try { conn = this.dbConfig.getConnection(); // If the language does not exist then create it Optional<LanguageTypeDTO> languageType = this.languageType.createLanguageType(codeIndexDocument.getLanguageName()); String query = "INSERT INTO `sourcecode` (`id`, `repoid`, `languageid`, `sourceid`, `ownerid`, `licenseid`, `location`, `filename`, `content`, `hash`, `simhash`, `linescount`, `data`) VALUES " + "(NULL, ?, ?, ?, ?, ?, ?, ?, COMPRESS(?), ?, ?, ?, ?)"; // Why is this here and not above?? if (existing.isPresent()) { return existing.get(); } stmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); stmt.setInt(1, 31337); stmt.setInt(2, languageType.get().getId()); stmt.setInt(3, 31337); stmt.setInt(4, 31337); stmt.setInt(5, 31337); stmt.setString(6, this.getLocation(codeIndexDocument)); stmt.setString(7, codeIndexDocument.getFileName()); stmt.setString(8, codeIndexDocument.getContents()); stmt.setString(9, codeIndexDocument.getHash()); stmt.setString(10, "simhash"); stmt.setInt(11, codeIndexDocument.getLines()); stmt.setString(12, "{}"); stmt.execute(); ResultSet tableKeys = stmt.getGeneratedKeys(); tableKeys.next(); int autoGeneratedID = tableKeys.getInt(1); return this.getById(autoGeneratedID).get(); } catch (SQLException ex) { this.logger.severe(String.format("4a1aa86d::error in class %s exception %s searchcode save code with name %s", ex.getClass(), ex.getMessage(), codeIndexDocument.getFileName())); } finally { this.helpers.closeQuietly(stmt); // this.helpers.closeQuietly(conn); } return null; } #location 44 #vulnerability type NULL_DEREFERENCE
#fixed code public SourceCodeDTO saveCode(CodeIndexDocument codeIndexDocument) { Optional<SourceCodeDTO> existing = this.getByCodeIndexDocument(codeIndexDocument); ConnStmtRs connStmtRs = new ConnStmtRs(); try { connStmtRs.conn = this.dbConfig.getConnection(); // If the language does not exist then create it Optional<LanguageTypeDTO> languageType = this.languageType.createLanguageType(codeIndexDocument.getLanguageName()); String query = "INSERT INTO `sourcecode` (`id`, `repoid`, `languageid`, `sourceid`, `ownerid`, `licenseid`, `location`, `filename`, `content`, `hash`, `simhash`, `linescount`, `data`) VALUES " + "(NULL, ?, ?, ?, ?, ?, ?, ?, COMPRESS(?), ?, ?, ?, ?)"; // Why is this here and not above?? if (existing.isPresent()) { return existing.get(); } connStmtRs.stmt = connStmtRs.conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS); connStmtRs.stmt.setInt(1, 31337); connStmtRs.stmt.setInt(2, languageType.get().getId()); connStmtRs.stmt.setInt(3, 31337); connStmtRs.stmt.setInt(4, 31337); connStmtRs.stmt.setInt(5, 31337); connStmtRs.stmt.setString(6, this.getLocation(codeIndexDocument)); connStmtRs.stmt.setString(7, codeIndexDocument.getFileName()); connStmtRs.stmt.setString(8, codeIndexDocument.getContents()); connStmtRs.stmt.setString(9, codeIndexDocument.getHash()); connStmtRs.stmt.setString(10, "simhash"); connStmtRs.stmt.setInt(11, codeIndexDocument.getLines()); connStmtRs.stmt.setString(12, "{}"); connStmtRs.stmt.execute(); ResultSet tableKeys = connStmtRs.stmt.getGeneratedKeys(); tableKeys.next(); int autoGeneratedID = tableKeys.getInt(1); return this.getById(autoGeneratedID).get(); } catch (SQLException ex) { this.logger.severe(String.format("4a1aa86d::error in class %s exception %s searchcode save code with name %s", ex.getClass(), ex.getMessage(), codeIndexDocument.getFileName())); } finally { this.helpers.closeQuietly(connStmtRs, this.dbConfig.closeConnection()); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Home createHome(BridgeSettingsDescriptor bridgeSettings) { lifxMap = null; aGsonHandler = null; validLifx = bridgeSettings.isValidLifx(); log.info("LifxDevice Home created." + (validLifx ? "" : " No LifxDevices configured.")); if(validLifx) { try { log.info("Open Lifx client...."); InetAddress configuredAddress = InetAddress.getByName(bridgeSettings.getUpnpConfigAddress()); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(configuredAddress); InetAddress bcastInetAddr = null; if (networkInterface != null) { for (InterfaceAddress ifaceAddr : networkInterface.getInterfaceAddresses()) { InetAddress addr = ifaceAddr.getAddress(); if (addr instanceof Inet4Address) { bcastInetAddr = ifaceAddr.getBroadcast(); break; } } } lifxMap = new HashMap<String, LifxDevice>(); log.info("Opening LFX Client with broadcast address: " + bcastInetAddr.getHostAddress()); client = new LFXClient(bcastInetAddr.getHostAddress()); client.getLights().addLightCollectionListener(new MyLightListener(lifxMap)); client.getGroups().addGroupCollectionListener(new MyGroupListener(lifxMap)); client.open(false); } catch (IOException e) { log.warn("Could not open LIFX, with IO Exception", e); client = null; return this; } catch (InterruptedException e) { log.warn("Could not open LIFX, with Interruprted Exception", e); client = null; return this; } aGsonHandler = new GsonBuilder() .create(); } return this; } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Home createHome(BridgeSettingsDescriptor bridgeSettings) { lifxMap = null; aGsonHandler = null; validLifx = bridgeSettings.isValidLifx(); log.info("LifxDevice Home created." + (validLifx ? "" : " No LifxDevices configured.")); if(validLifx) { try { log.info("Open Lifx client...."); InetAddress configuredAddress = InetAddress.getByName(bridgeSettings.getUpnpConfigAddress()); NetworkInterface networkInterface = NetworkInterface.getByInetAddress(configuredAddress); InetAddress bcastInetAddr = null; if (networkInterface != null) { for (InterfaceAddress ifaceAddr : networkInterface.getInterfaceAddresses()) { InetAddress addr = ifaceAddr.getAddress(); if (addr instanceof Inet4Address) { bcastInetAddr = ifaceAddr.getBroadcast(); break; } } } if(bcastInetAddr != null) { lifxMap = new HashMap<String, LifxDevice>(); log.info("Opening LFX Client with broadcast address: " + bcastInetAddr.getHostAddress()); client = new LFXClient(bcastInetAddr.getHostAddress()); client.getLights().addLightCollectionListener(new MyLightListener(lifxMap)); client.getGroups().addGroupCollectionListener(new MyGroupListener(lifxMap)); client.open(false); aGsonHandler = new GsonBuilder() .create(); } else { log.warn("Could not open LIFX, no bcast addr available, check your upnp config address."); client = null; validLifx = false; return this; } } catch (IOException e) { log.warn("Could not open LIFX, with IO Exception", e); client = null; validLifx = false; return this; } catch (InterruptedException e) { log.warn("Could not open LIFX, with Interruprted Exception", e); client = null; validLifx = false; return this; } } return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void configWriter(String content, Path filePath) { if(Files.exists(filePath) && !Files.isWritable(filePath)){ log.error("Error file is not writable: " + filePath); return; } if(Files.notExists(filePath.getParent())) { try { Files.createDirectories(filePath.getParent()); } catch (IOException e) { log.error("Error creating the directory: " + filePath + " message: " + e.getMessage(), e); } } try { Path target = null; if(Files.exists(filePath)) { target = FileSystems.getDefault().getPath(filePath.getParent().toString(), "habridge.config.old"); Files.move(filePath, target); } Files.write(filePath, content.getBytes(), StandardOpenOption.CREATE); // set attributes to be for user only // using PosixFilePermission to set file permissions Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); // add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); try { if(System.getProperty("os.name").toLowerCase().indexOf("win") <= 0) Files.setPosixFilePermissions(filePath, perms); } catch(UnsupportedOperationException e) { log.info("Cannot set permissions for config file on this system as it is not supported. Continuing"); } if(target != null) Files.delete(target); } catch (IOException e) { log.error("Error writing the file: " + filePath + " message: " + e.getMessage(), e); } } #location 31 #vulnerability type NULL_DEREFERENCE
#fixed code private void configWriter(String content, Path filePath) { if(Files.exists(filePath) && !Files.isWritable(filePath)){ log.error("Error file is not writable: " + filePath); return; } if(Files.notExists(filePath.getParent())) { try { Files.createDirectories(filePath.getParent()); } catch (IOException e) { log.error("Error creating the directory: " + filePath + " message: " + e.getMessage(), e); } } try { Path target = null; if(Files.exists(filePath)) { target = FileSystems.getDefault().getPath(filePath.getParent().toString(), "habridge.config.old"); Files.move(filePath, target); } Files.write(filePath, content.getBytes(), StandardOpenOption.CREATE); // set attributes to be for user only // using PosixFilePermission to set file permissions Set<PosixFilePermission> perms = new HashSet<PosixFilePermission>(); // add owners permission perms.add(PosixFilePermission.OWNER_READ); perms.add(PosixFilePermission.OWNER_WRITE); try { String osName = System.getProperty("os.name"); if(osName.toLowerCase().indexOf("win") < 0) Files.setPosixFilePermissions(filePath, perms); } catch(UnsupportedOperationException e) { log.info("Cannot set permissions for config file on this system as it is not supported. Continuing"); } if(target != null) Files.delete(target); } catch (IOException e) { log.error("Error writing the file: " + filePath + " message: " + e.getMessage(), e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void denormalizeSdata(Sdata theSdata) { Map<String,Room> roomMap = new HashMap<String,Room>(); for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i); Map<String,Categorie> categoryMap = new HashMap<String,Categorie>(); for (Categorie i : theSdata.getCategoriess()) categoryMap.put(i.getId(),i); Categorie controllerCat = new Categorie(); controllerCat.setName("Controller"); controllerCat.setId("0"); categoryMap.put(controllerCat.getId(),controllerCat); ListIterator<Device> theIterator = theSdata.getDevices().listIterator(); Device theDevice = null; while (theIterator.hasNext()) { theDevice = theIterator.next(); if(theDevice.getRoom() != null) theDevice.setRoom(roomMap.get(theDevice.getRoom()).getName()); else theDevice.setRoom("<unknown>"); if(theDevice.getCategory() != null) theDevice.setCategory(categoryMap.get(theDevice.getCategory()).getName()); else theDevice.setCategory("<unknown>"); } ListIterator<Scene> theSecneIter = theSdata.getScenes().listIterator(); Scene theScene = null; while (theSecneIter.hasNext()) { theScene = theSecneIter.next(); theScene.setRoom(roomMap.get(theScene.getRoom()).getName()); } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code private void denormalizeSdata(Sdata theSdata) { Map<String,Room> roomMap = new HashMap<String,Room>(); for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i); Map<String,Categorie> categoryMap = new HashMap<String,Categorie>(); for (Categorie i : theSdata.getCategoriess()) categoryMap.put(i.getId(),i); Categorie controllerCat = new Categorie(); controllerCat.setName("Controller"); controllerCat.setId("0"); categoryMap.put(controllerCat.getId(),controllerCat); ListIterator<Device> theIterator = theSdata.getDevices().listIterator(); Device theDevice = null; while (theIterator.hasNext()) { theDevice = theIterator.next(); if(theDevice.getRoom() != null && roomMap.get(theDevice.getRoom()) != null) theDevice.setRoom(roomMap.get(theDevice.getRoom()).getName()); else theDevice.setRoom("no room"); if(theDevice.getCategory() != null && categoryMap.get(theDevice.getCategory()) != null) theDevice.setCategory(categoryMap.get(theDevice.getCategory()).getName()); else theDevice.setCategory("<unknown>"); } ListIterator<Scene> theSecneIter = theSdata.getScenes().listIterator(); Scene theScene = null; while (theSecneIter.hasNext()) { theScene = theSecneIter.next(); theScene.setRoom(roomMap.get(theScene.getRoom()).getName()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri,Integer targetBriInc, DeviceDescriptor device, String body) { log.debug("executing HUE api request to TCP: " + anItem.getItem().getAsString()); String theUrl = anItem.getItem().getAsString(); if(theUrl != null && !theUrl.isEmpty () && theUrl.startsWith("tcp://")) { String intermediate = theUrl.substring(theUrl.indexOf("://") + 3); String hostPortion = intermediate.substring(0, intermediate.indexOf('/')); String theUrlBody = intermediate.substring(intermediate.indexOf('/') + 1); String hostAddr = null; String port = null; InetAddress IPAddress = null; if (hostPortion.contains(":")) { hostAddr = hostPortion.substring(0, intermediate.indexOf(':')); port = hostPortion.substring(intermediate.indexOf(':') + 1); } else hostAddr = hostPortion; try { IPAddress = InetAddress.getByName(hostAddr); } catch (UnknownHostException e) { // noop } theUrlBody = TimeDecode.replaceTimeValue(theUrlBody); if (theUrlBody.startsWith("0x")) { theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, intensity, targetBri, targetBriInc, true); sendData = DatatypeConverter.parseHexBinary(theUrlBody.substring(2)); } else { theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, intensity, targetBri, targetBriInc, false); sendData = theUrlBody.getBytes(); } try { Socket dataSendSocket = new Socket(IPAddress, Integer.parseInt(port)); DataOutputStream outToClient = new DataOutputStream(dataSendSocket.getOutputStream()); outToClient.write(sendData); outToClient.flush(); dataSendSocket.close(); } catch (Exception e) { // noop } } else log.warn("Tcp Call to be presented as tcp://<ip_address>:<port>/payload, format of request unknown: " + theUrl); return null; } #location 39 #vulnerability type RESOURCE_LEAK
#fixed code @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri,Integer targetBriInc, DeviceDescriptor device, String body) { Socket dataSendSocket = null; log.debug("executing HUE api request to TCP: " + anItem.getItem().getAsString()); String theUrl = anItem.getItem().getAsString(); if(theUrl != null && !theUrl.isEmpty () && theUrl.startsWith("tcp://")) { String intermediate = theUrl.substring(theUrl.indexOf("://") + 3); String hostPortion = intermediate.substring(0, intermediate.indexOf('/')); String theUrlBody = intermediate.substring(intermediate.indexOf('/') + 1); String hostAddr = null; String port = null; InetAddress IPAddress = null; dataSendSocket = theSockets.get(hostPortion); if(dataSendSocket == null) { if (hostPortion.contains(":")) { hostAddr = hostPortion.substring(0, intermediate.indexOf(':')); port = hostPortion.substring(intermediate.indexOf(':') + 1); } else hostAddr = hostPortion; try { IPAddress = InetAddress.getByName(hostAddr); } catch (UnknownHostException e) { // noop } try { dataSendSocket = new Socket(IPAddress, Integer.parseInt(port)); theSockets.put(hostPortion, dataSendSocket); } catch (Exception e) { // noop } } theUrlBody = TimeDecode.replaceTimeValue(theUrlBody); if (theUrlBody.startsWith("0x")) { theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, intensity, targetBri, targetBriInc, true); sendData = DatatypeConverter.parseHexBinary(theUrlBody.substring(2)); } else { theUrlBody = BrightnessDecode.calculateReplaceIntensityValue(theUrlBody, intensity, targetBri, targetBriInc, false); sendData = theUrlBody.getBytes(); } try { DataOutputStream outToClient = new DataOutputStream(dataSendSocket.getOutputStream()); outToClient.write(sendData); outToClient.flush(); } catch (Exception e) { // noop } } else log.warn("Tcp Call to be presented as tcp://<ip_address>:<port>/payload, format of request unknown: " + theUrl); return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Home createHome(BridgeSettings bridgeSettings) { fhemMap = null; validFhem = bridgeSettings.getBridgeSettingsDescriptor().isValidOpenhab(); log.info("FHEM Home created." + (validFhem ? "" : " No FHEMs configured.")); if(validFhem) { fhemMap = new HashMap<String,FHEMInstance>(); httpClient = HTTPHome.getHandler(); Iterator<NamedIP> theList = bridgeSettings.getBridgeSettingsDescriptor().getOpenhabaddress().getDevices().iterator(); while(theList.hasNext() && validFhem) { NamedIP aFhem = theList.next(); try { fhemMap.put(aFhem.getName(), new FHEMInstance(aFhem)); } catch (Exception e) { log.error("Cannot get FHEM (" + aFhem.getName() + ") setup, Exiting with message: " + e.getMessage(), e); validFhem = false; } } } return this; } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Home createHome(BridgeSettings bridgeSettings) { fhemMap = null; validFhem = bridgeSettings.getBridgeSettingsDescriptor().isValidFhem(); log.info("FHEM Home created." + (validFhem ? "" : " No FHEMs configured.")); if(validFhem) { fhemMap = new HashMap<String,FHEMInstance>(); httpClient = HTTPHome.getHandler(); Iterator<NamedIP> theList = bridgeSettings.getBridgeSettingsDescriptor().getFhemaddress().getDevices().iterator(); while(theList.hasNext() && validFhem) { NamedIP aFhem = theList.next(); try { fhemMap.put(aFhem.getName(), new FHEMInstance(aFhem)); } catch (Exception e) { log.error("Cannot get FHEM (" + aFhem.getName() + ") setup, Exiting with message: " + e.getMessage(), e); validFhem = false; } } } return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public HueError[] validateWhitelistUser(String aUser, String userDescription, boolean strict) { String validUser = null; boolean found = false; if (aUser != null && !aUser.equalsIgnoreCase("undefined") && !aUser.equalsIgnoreCase("null") && !aUser.equalsIgnoreCase("")) { if (securityDescriptor.getWhitelist() != null) { Set<String> theUserIds = securityDescriptor.getWhitelist().keySet(); Iterator<String> userIterator = theUserIds.iterator(); while (userIterator.hasNext()) { validUser = userIterator.next(); if (validUser.equals(aUser)) found = true; } } } if(!found && !strict) { newWhitelistUser(aUser, userDescription); found = true; } if (!found) { return HueErrorResponse.createResponse("1", "/api/" + aUser, "unauthorized user", null, null, null).getTheErrors(); } Object anUser = securityDescriptor.getWhitelist().remove(DEPRACATED_INTERNAL_USER); if(anUser != null) setSettingsChanged(true); return null; } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code public HueError[] validateWhitelistUser(String aUser, String userDescription, boolean strict) { String validUser = null; boolean found = false; if (aUser != null && !aUser.equalsIgnoreCase("undefined") && !aUser.equalsIgnoreCase("null") && !aUser.equalsIgnoreCase("")) { if (securityDescriptor.getWhitelist() != null) { Set<String> theUserIds = securityDescriptor.getWhitelist().keySet(); Iterator<String> userIterator = theUserIds.iterator(); while (userIterator.hasNext()) { validUser = userIterator.next(); if (validUser.equals(aUser)) { found = true; log.debug("validateWhitelistUser: found a user <" + aUser + ">"); } } } } if(!found && !strict) { log.debug("validateWhitelistUser: a user was not found and it is not strict rules <" + aUser + "> being created"); newWhitelistUser(aUser, userDescription); found = true; } if (!found) { log.debug("validateWhitelistUser: a user was not found and it is strict rules <" + aUser + ">"); return HueErrorResponse.createResponse("1", "/api/" + aUser == null ? "" : aUser, "unauthorized user", null, null, null).getTheErrors(); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri, Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) { log.debug("Exec Request called with url: " + anItem.getItem().getAsString() + " and exec Garden: " + (theSettings.getBridgeSecurity().getExecGarden() == null ? "not given" : theSettings.getBridgeSecurity().getExecGarden())); String responseString = null; String intermediate; if (anItem.getItem().getAsString().contains("exec://")) intermediate = anItem.getItem().getAsString().substring(anItem.getItem().getAsString().indexOf("://") + 3); else intermediate = anItem.getItem().getAsString(); intermediate = BrightnessDecode.calculateReplaceIntensityValue(intermediate, intensity, targetBri, targetBriInc, false); if (colorData != null) { intermediate = ColorDecode.replaceColorData(intermediate, colorData, BrightnessDecode.calculateIntensity(intensity, targetBri, targetBriInc), false); } intermediate = DeviceDataDecode.replaceDeviceData(intermediate, device); intermediate = TimeDecode.replaceTimeValue(intermediate); String execGarden = theSettings.getBridgeSecurity().getExecGarden(); if(execGarden != null && !execGarden.trim().isEmpty()) { if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) intermediate = execGarden + "\\" + intermediate; else intermediate = execGarden + "/" + intermediate; } String anError = doExecRequest(intermediate, lightId); if (anError != null) { responseString = anError; } return responseString; } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri, Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) { log.debug("Exec Request called with url: " + anItem.getItem().getAsString() + " and exec Garden: " + (theSettings.getBridgeSecurity().getExecGarden() == null ? "not given" : theSettings.getBridgeSecurity().getExecGarden())); String responseString = null; String intermediate; if (anItem.getItem().getAsString().contains("exec://")) intermediate = anItem.getItem().getAsString().substring(anItem.getItem().getAsString().indexOf("://") + 3); else intermediate = anItem.getItem().getAsString(); intermediate = BrightnessDecode.calculateReplaceIntensityValue(intermediate, intensity, targetBri, targetBriInc, false); if (colorData != null) { intermediate = ColorDecode.replaceColorData(intermediate, colorData, BrightnessDecode.calculateIntensity(intensity, targetBri, targetBriInc), false); } intermediate = DeviceDataDecode.replaceDeviceData(intermediate, device); intermediate = TimeDecode.replaceTimeValue(intermediate); String execGarden = theSettings.getBridgeSecurity().getExecGarden(); if(execGarden != null && !execGarden.trim().isEmpty()) { intermediate = new File(execGarden.trim(), intermediate).getAbsolutePath(); } String anError = doExecRequest(intermediate, lightId); if (anError != null) { responseString = anError; } return responseString; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int itensity, Integer targetBri, Integer targetBriInc, DeviceDescriptor device, String body) { log.debug("Exec Request called with url: " + anItem.getItem().getAsString()); String responseString = null; String intermediate; if (anItem.getItem().getAsString().contains("exec://")) intermediate = anItem.getItem().getAsString().substring(anItem.getItem().getAsString().indexOf("://") + 3); else intermediate = anItem.getItem().getAsString(); intermediate = BrightnessDecode.calculateReplaceIntensityValue(intermediate, itensity, targetBri, targetBriInc, false); intermediate = DeviceDataDecode.replaceDeviceData(intermediate, device); intermediate = TimeDecode.replaceTimeValue(intermediate); if(execGarden != null) { if(System.getProperty("os.name").toLowerCase().indexOf("win") > 0) intermediate = execGarden + "\\" + intermediate; else intermediate = execGarden + "/" + intermediate; } String anError = doExecRequest(intermediate, lightId); if (anError != null) { responseString = anError; } return responseString; } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int itensity, Integer targetBri, Integer targetBriInc, DeviceDescriptor device, String body) { log.debug("Exec Request called with url: " + anItem.getItem().getAsString() + " and exec Garden: " + (theSettings.getBridgeSecurity().getExecGarden() == null ? "not given" : theSettings.getBridgeSecurity().getExecGarden())); String responseString = null; String intermediate; if (anItem.getItem().getAsString().contains("exec://")) intermediate = anItem.getItem().getAsString().substring(anItem.getItem().getAsString().indexOf("://") + 3); else intermediate = anItem.getItem().getAsString(); intermediate = BrightnessDecode.calculateReplaceIntensityValue(intermediate, itensity, targetBri, targetBriInc, false); intermediate = DeviceDataDecode.replaceDeviceData(intermediate, device); intermediate = TimeDecode.replaceTimeValue(intermediate); String execGarden = theSettings.getBridgeSecurity().getExecGarden(); execGarden = execGarden.trim(); if(execGarden != null && !execGarden.isEmpty()) { if(System.getProperty("os.name").toLowerCase().indexOf("win") >= 0) intermediate = execGarden + "\\" + intermediate; else intermediate = execGarden + "/" + intermediate; } String anError = doExecRequest(intermediate, lightId); if (anError != null) { responseString = anError; } return responseString; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { Logger log = LoggerFactory.getLogger(HABridge.class); DeviceResource theResources; HomeManager homeManager; HueMulator theHueMulator; UDPDatagramSender udpSender; UpnpSettingsResource theSettingResponder; UpnpListener theUpnpListener; SystemControl theSystem; BridgeSettings bridgeSettings; Version theVersion; theVersion = new Version(); log.info("HA Bridge (v" + theVersion.getVersion() + ") starting...."); bridgeSettings = new BridgeSettings(); // sparkjava config directive to set html static file location for Jetty staticFileLocation("/public"); while(!bridgeSettings.getBridgeControl().isStop()) { bridgeSettings.buildSettings(); log.info("HA Bridge initializing...."); // sparkjava config directive to set ip address for the web server to listen on ipAddress(bridgeSettings.getBridgeSettingsDescriptor().getWebaddress()); // sparkjava config directive to set port for the web server to listen on port(bridgeSettings.getBridgeSettingsDescriptor().getServerPort()); if(!bridgeSettings.getBridgeControl().isReinit()) init(); bridgeSettings.getBridgeControl().setReinit(false); // setup system control api first theSystem = new SystemControl(bridgeSettings, theVersion); theSystem.setupServer(); // setup the UDP Datagram socket to be used by the HueMulator and the upnpListener udpSender = UDPDatagramSender.createUDPDatagramSender(bridgeSettings.getBridgeSettingsDescriptor().getUpnpResponsePort()); if(udpSender == null) { bridgeSettings.getBridgeControl().setStop(true); } else { //Setup the device connection homes through the manager homeManager = new HomeManager(); homeManager.buildHomes(bridgeSettings, udpSender); // setup the class to handle the resource setup rest api theResources = new DeviceResource(bridgeSettings, homeManager); // setup the class to handle the upnp response rest api theSettingResponder = new UpnpSettingsResource(bridgeSettings.getBridgeSettingsDescriptor()); theSettingResponder.setupServer(); // setup the class to handle the hue emulator rest api theHueMulator = new HueMulator(bridgeSettings, theResources.getDeviceRepository(), homeManager); theHueMulator.setupServer(); // wait for the sparkjava initialization of the rest api classes to be complete awaitInitialization(); // start the upnp ssdp discovery listener theUpnpListener = new UpnpListener(bridgeSettings.getBridgeSettingsDescriptor(), bridgeSettings.getBridgeControl(), udpSender); if(theUpnpListener.startListening()) log.info("HA Bridge (v" + theVersion.getVersion() + ") reinitialization requessted...."); else bridgeSettings.getBridgeControl().setStop(true); if(bridgeSettings.getBridgeSettingsDescriptor().isSettingsChanged()) bridgeSettings.save(bridgeSettings.getBridgeSettingsDescriptor()); homeManager.closeHomes(); udpSender.closeResponseSocket(); udpSender = null; } stop(); if(!bridgeSettings.getBridgeControl().isStop()) { try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } bridgeSettings.getBridgeSecurity().removeTestUsers(); if(bridgeSettings.getBridgeSecurity().isSettingsChanged()) bridgeSettings.updateConfigFile(); log.info("HA Bridge (v" + theVersion.getVersion() + ") exiting...."); System.exit(0); } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) { Logger log = LoggerFactory.getLogger(HABridge.class); DeviceResource theResources; HomeManager homeManager; HueMulator theHueMulator; UDPDatagramSender udpSender; UpnpSettingsResource theSettingResponder; UpnpListener theUpnpListener; SystemControl theSystem; BridgeSettings bridgeSettings; Version theVersion; theVersion = new Version(); log.info("HA Bridge (v" + theVersion.getVersion() + ") starting...."); bridgeSettings = new BridgeSettings(); // sparkjava config directive to set html static file location for Jetty staticFileLocation("/public"); while(!bridgeSettings.getBridgeControl().isStop()) { bridgeSettings.buildSettings(); bridgeSettings.getBridgeSecurity().removeTestUsers(); log.info("HA Bridge initializing...."); // sparkjava config directive to set ip address for the web server to listen on ipAddress(bridgeSettings.getBridgeSettingsDescriptor().getWebaddress()); // sparkjava config directive to set port for the web server to listen on port(bridgeSettings.getBridgeSettingsDescriptor().getServerPort()); if(!bridgeSettings.getBridgeControl().isReinit()) init(); bridgeSettings.getBridgeControl().setReinit(false); // setup system control api first theSystem = new SystemControl(bridgeSettings, theVersion); theSystem.setupServer(); // setup the UDP Datagram socket to be used by the HueMulator and the upnpListener udpSender = UDPDatagramSender.createUDPDatagramSender(bridgeSettings.getBridgeSettingsDescriptor().getUpnpResponsePort()); if(udpSender == null) { bridgeSettings.getBridgeControl().setStop(true); } else { //Setup the device connection homes through the manager homeManager = new HomeManager(); homeManager.buildHomes(bridgeSettings, udpSender); // setup the class to handle the resource setup rest api theResources = new DeviceResource(bridgeSettings, homeManager); // setup the class to handle the upnp response rest api theSettingResponder = new UpnpSettingsResource(bridgeSettings.getBridgeSettingsDescriptor()); theSettingResponder.setupServer(); // setup the class to handle the hue emulator rest api theHueMulator = new HueMulator(bridgeSettings, theResources.getDeviceRepository(), homeManager); theHueMulator.setupServer(); // wait for the sparkjava initialization of the rest api classes to be complete awaitInitialization(); // start the upnp ssdp discovery listener theUpnpListener = new UpnpListener(bridgeSettings.getBridgeSettingsDescriptor(), bridgeSettings.getBridgeControl(), udpSender); if(theUpnpListener.startListening()) log.info("HA Bridge (v" + theVersion.getVersion() + ") reinitialization requessted...."); else bridgeSettings.getBridgeControl().setStop(true); if(bridgeSettings.getBridgeSettingsDescriptor().isSettingsChanged()) bridgeSettings.save(bridgeSettings.getBridgeSettingsDescriptor()); homeManager.closeHomes(); udpSender.closeResponseSocket(); udpSender = null; } stop(); if(!bridgeSettings.getBridgeControl().isStop()) { try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } bridgeSettings.getBridgeSecurity().removeTestUsers(); if(bridgeSettings.getBridgeSecurity().isSettingsChanged()) bridgeSettings.updateConfigFile(); log.info("HA Bridge (v" + theVersion.getVersion() + ") exiting...."); System.exit(0); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void denormalizeSdata(Sdata theSdata) { Map<String,Room> roomMap = new HashMap<String,Room>(); for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i); Map<String,Categorie> categoryMap = new HashMap<String,Categorie>(); for (Categorie i : theSdata.getCategoriess()) categoryMap.put(i.getId(),i); Categorie controllerCat = new Categorie(); controllerCat.setName("Controller"); controllerCat.setId("0"); categoryMap.put(controllerCat.getId(),controllerCat); ListIterator<Device> theIterator = theSdata.getDevices().listIterator(); Device theDevice = null; while (theIterator.hasNext()) { theDevice = theIterator.next(); if(theDevice.getRoom() != null) theDevice.setRoom(roomMap.get(theDevice.getRoom()).getName()); else theDevice.setRoom("<unknown>"); if(theDevice.getCategory() != null) theDevice.setCategory(categoryMap.get(theDevice.getCategory()).getName()); else theDevice.setCategory("<unknown>"); } ListIterator<Scene> theSecneIter = theSdata.getScenes().listIterator(); Scene theScene = null; while (theSecneIter.hasNext()) { theScene = theSecneIter.next(); theScene.setRoom(roomMap.get(theScene.getRoom()).getName()); } } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code private void denormalizeSdata(Sdata theSdata) { Map<String,Room> roomMap = new HashMap<String,Room>(); for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i); Map<String,Categorie> categoryMap = new HashMap<String,Categorie>(); for (Categorie i : theSdata.getCategoriess()) categoryMap.put(i.getId(),i); Categorie controllerCat = new Categorie(); controllerCat.setName("Controller"); controllerCat.setId("0"); categoryMap.put(controllerCat.getId(),controllerCat); ListIterator<Device> theIterator = theSdata.getDevices().listIterator(); Device theDevice = null; while (theIterator.hasNext()) { theDevice = theIterator.next(); if(theDevice.getRoom() != null && roomMap.get(theDevice.getRoom()) != null) theDevice.setRoom(roomMap.get(theDevice.getRoom()).getName()); else theDevice.setRoom("no room"); if(theDevice.getCategory() != null && categoryMap.get(theDevice.getCategory()) != null) theDevice.setCategory(categoryMap.get(theDevice.getCategory()).getName()); else theDevice.setCategory("<unknown>"); } ListIterator<Scene> theSecneIter = theSdata.getScenes().listIterator(); Scene theScene = null; while (theSecneIter.hasNext()) { theScene = theSecneIter.next(); theScene.setRoom(roomMap.get(theScene.getRoom()).getName()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void saveResource(String resourcePath, boolean replace) { if (resourcePath == null || resourcePath.equals("")) { throw new IllegalArgumentException("ResourcePath cannot be null or empty"); } resourcePath = resourcePath.replace('\\', '/'); InputStream in = getResource(resourcePath); if (in == null) { throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + getFile()); } File outFile = new File(getDataFolder(), resourcePath); int lastIndex = resourcePath.lastIndexOf('/'); File outDir = new File(getDataFolder(), resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0)); if (!outDir.exists()) { outDir.mkdirs(); } try { if (!outFile.exists() || replace) { OutputStream out = new FileOutputStream(outFile); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); in.close(); } else { Logger.getLogger(JavaPlugin.class.getName()).log(Level.WARNING, "Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists."); } } catch (IOException ex) { Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, ex); } } #location 33 #vulnerability type RESOURCE_LEAK
#fixed code public void saveResource(String resourcePath, boolean replace) { if (resourcePath == null || resourcePath.equals("")) { throw new IllegalArgumentException("ResourcePath cannot be null or empty"); } resourcePath = resourcePath.replace('\\', '/'); InputStream in = getResource(resourcePath); if (in == null) { throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + getFile()); } File outFile = new File(getDataFolder(), resourcePath); int lastIndex = resourcePath.lastIndexOf('/'); File outDir = new File(getDataFolder(), resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0)); if (!outDir.exists()) { outDir.mkdirs(); } try { if (!outFile.exists() || replace) { OutputStream out = new FileOutputStream(outFile); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } out.close(); in.close(); } else { getLogger().log(Level.WARNING, "Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists."); } } catch (IOException ex) { getLogger().log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException { Validate.notNull(file, "File cannot be null"); load(new FileInputStream(file)); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException { Validate.notNull(file, "File cannot be null"); final FileInputStream stream = new FileInputStream(file); load(new InputStreamReader(stream, UTF8_OVERRIDE && !UTF_BIG ? Charsets.UTF_8 : Charset.defaultCharset())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException { JavaPlugin result = null; PluginDescriptionFile description = null; if (!file.exists()) { throw new InvalidPluginException(new FileNotFoundException(String.format("%s does not exist", file.getPath()))); } try { JarFile jar = new JarFile(file); JarEntry entry = jar.getJarEntry("plugin.yml"); if (entry == null) { throw new InvalidPluginException(new FileNotFoundException("Jar does not contain plugin.yml")); } InputStream stream = jar.getInputStream(entry); description = new PluginDescriptionFile(stream); stream.close(); jar.close(); } catch (IOException ex) { throw new InvalidPluginException(ex); } catch (YAMLException ex) { throw new InvalidPluginException(ex); } File dataFolder = new File(file.getParentFile(), description.getName()); File oldDataFolder = getDataFolder(file); // Found old data folder if (dataFolder.equals(oldDataFolder)) { // They are equal -- nothing needs to be done! } else if (dataFolder.isDirectory() && oldDataFolder.isDirectory()) { server.getLogger().log( Level.INFO, String.format( "While loading %s (%s) found old-data folder: %s next to the new one: %s", description.getName(), file, oldDataFolder, dataFolder )); } else if (oldDataFolder.isDirectory() && !dataFolder.exists()) { if (!oldDataFolder.renameTo(dataFolder)) { throw new InvalidPluginException(new Exception("Unable to rename old data folder: '" + oldDataFolder + "' to: '" + dataFolder + "'")); } server.getLogger().log( Level.INFO, String.format( "While loading %s (%s) renamed data folder: '%s' to '%s'", description.getName(), file, oldDataFolder, dataFolder )); } if (dataFolder.exists() && !dataFolder.isDirectory()) { throw new InvalidPluginException(new Exception(String.format( "Projected datafolder: '%s' for %s (%s) exists and is not a directory", dataFolder, description.getName(), file ))); } ArrayList<String> depend; try { depend = (ArrayList)description.getDepend(); if(depend == null) { depend = new ArrayList<String>(); } } catch (ClassCastException ex) { throw new InvalidPluginException(ex); } for(String pluginName : depend) { if(loaders == null) { throw new UnknownDependencyException(pluginName); } PluginClassLoader current = loaders.get(pluginName); if(current == null) { throw new UnknownDependencyException(pluginName); } } PluginClassLoader loader = null; try { URL[] urls = new URL[1]; urls[0] = file.toURI().toURL(); loader = new PluginClassLoader(this, urls, getClass().getClassLoader()); Class<?> jarClass = Class.forName(description.getMain(), true, loader); Class<? extends JavaPlugin> plugin = jarClass.asSubclass(JavaPlugin.class); Constructor<? extends JavaPlugin> constructor = plugin.getConstructor(); result = constructor.newInstance(); result.initialize(this, server, description, dataFolder, file, loader); } catch (Throwable ex) { throw new InvalidPluginException(ex); } loaders.put(description.getName(), (PluginClassLoader)loader); return (Plugin)result; } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException { return loadPlugin(file, false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) return true; if (args.length < 1 || args.length > 4) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } Player player; if (args.length == 1 || args.length == 3) { if (sender instanceof Player) { player = (Player) sender; } else { sender.sendMessage("Please provide a player!"); return true; } } else { player = Bukkit.getPlayerExact(args[0]); } if (player == null) { sender.sendMessage("Player not found: " + args[0]); } if (args.length < 3) { Player target = Bukkit.getPlayerExact(args[args.length - 1]); if (target == null) { sender.sendMessage("Can't find user " + args[args.length - 1] + ". No tp."); } player.teleport(target, TeleportCause.COMMAND); sender.sendMessage("Teleported " + player.getName() + " to " + target.getName()); } else if (player.getWorld() != null) { int x = getInteger(sender, args[args.length - 3], -30000000, 30000000); int y = getInteger(sender, args[args.length - 2], 0, 256); int z = getInteger(sender, args[args.length - 1], -30000000, 30000000); Location location = new Location(player.getWorld(), x, y, z); player.teleport(location); sender.sendMessage("Teleported " + player.getName() + " to " + x + "," + y + "," + z); } return true; } #location 32 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) return true; if (args.length < 1 || args.length > 4) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } Player player; if (args.length == 1 || args.length == 3) { if (sender instanceof Player) { player = (Player) sender; } else { sender.sendMessage("Please provide a player!"); return true; } } else { player = Bukkit.getPlayerExact(args[0]); } if (player == null) { sender.sendMessage("Player not found: " + args[0]); return true; } if (args.length < 3) { Player target = Bukkit.getPlayerExact(args[args.length - 1]); if (target == null) { sender.sendMessage("Can't find user " + args[args.length - 1] + ". No tp."); return true; } player.teleport(target, TeleportCause.COMMAND); Command.broadcastCommandMessage(sender, "Teleported " + player.getName() + " to " + target.getName()); } else if (player.getWorld() != null) { int x = getInteger(sender, args[args.length - 3], -30000000, 30000000); int y = getInteger(sender, args[args.length - 2], 0, 256); int z = getInteger(sender, args[args.length - 1], -30000000, 30000000); Location location = new Location(player.getWorld(), x, y, z); player.teleport(location); Command.broadcastCommandMessage(sender, "Teleported " + player.getName() + " to " + + x + "," + y + "," + z); } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void recalculatePermissions() { dirtyPermissions = true; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void recalculatePermissions() { clearPermissions(); Set<Permission> defaults = Bukkit.getServer().getPluginManager().getDefaultPermissions(isOp()); Bukkit.getServer().getPluginManager().subscribeToDefaultPerms(isOp(), parent); for (Permission perm : defaults) { String name = perm.getName().toLowerCase(); permissions.put(name, new PermissionAttachmentInfo(parent, name, null, true)); Bukkit.getServer().getPluginManager().subscribeToPermission(name, parent); calculateChildPermissions(perm.getChildren(), false, null); } for (PermissionAttachment attachment : attachments) { calculateChildPermissions(attachment.getPermissions(), false, attachment); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<byte[]> getLoadBlocks(boolean includeDebug, boolean separateComponents, int blockSize) { List<byte[]> blocks = null; if (!separateComponents) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); try { bo.write(createHeader(includeDebug)); bo.write(getRawCode(includeDebug)); } catch (IOException ioe) { } blocks = splitArray(bo.toByteArray(), blockSize); } else { for (String name : componentNames) { if (!includeDebug && (name.equals("Debug") || name.equals("Descriptor"))) continue; byte[] currentComponent = capComponents.get(name); if (currentComponent == null) { continue; } if (name.equals("Header")) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); try { bo.write(createHeader(includeDebug)); bo.write(currentComponent); } catch (IOException ioe) { } currentComponent = bo.toByteArray(); } blocks.addAll(splitArray(currentComponent, blockSize)); } } return blocks; } #location 34 #vulnerability type NULL_DEREFERENCE
#fixed code public List<byte[]> getLoadBlocks(boolean includeDebug, boolean separateComponents, int blockSize) { List<byte[]> blocks = null; if (!separateComponents) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); try { bo.write(createHeader(includeDebug)); bo.write(getRawCode(includeDebug)); } catch (IOException ioe) { } blocks = splitArray(bo.toByteArray(), blockSize); } else { for (String name : componentNames) { if (!includeDebug && (name.equals("Debug") || name.equals("Descriptor"))) continue; byte[] currentComponent = capComponents.get(name); if (currentComponent == null) { continue; } if (name.equals("Header")) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); try { bo.write(createHeader(includeDebug)); bo.write(currentComponent); } catch (IOException ioe) { } currentComponent = bo.toByteArray(); } blocks = splitArray(currentComponent, blockSize); } } return blocks; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConsumerNormalOps() throws InterruptedException, ExecutionException { // Tests create instance, read, and delete final List<ConsumerRecord> referenceRecords = Arrays.asList( new ConsumerRecord("k1".getBytes(), "v1".getBytes(), 0, 0), new ConsumerRecord("k2".getBytes(), "v2".getBytes(), 1, 0), new ConsumerRecord("k3".getBytes(), "v3".getBytes(), 2, 0) ); Map<Integer,List<ConsumerRecord>> referenceSchedule = new HashMap<>(); referenceSchedule.put(50, referenceRecords); Map<String,List<Map<Integer,List<ConsumerRecord>>>> schedules = new HashMap<>(); schedules.put(topicName, Arrays.asList(referenceSchedule)); expectCreate(schedules); EasyMock.expect(mdObserver.topicExists(topicName)).andReturn(true); EasyMock.replay(mdObserver, consumerFactory); String cid = consumerManager.createConsumer(groupName); consumerManager.readTopic(groupName, cid, topicName, new ConsumerManager.ReadCallback() { @Override public void onCompletion(List<ConsumerRecord> records, Exception e) { assertNull(e); assertEquals(referenceRecords, records); } }).get(); // With # of messages < max per request, this should finish at the per-request timeout assertEquals(config.consumerRequestTimeoutMs, config.time.milliseconds()); consumerManager.commitOffsets(groupName, cid, new ConsumerManager.CommitCallback() { @Override public void onCompletion(List<TopicPartitionOffset> offsets, Exception e) { assertNull(e); // Mock consumer doesn't handle offsets, so we just check we get some output for the right partitions assertNotNull(offsets); assertEquals(3, offsets.size()); } }).get(); consumerManager.deleteConsumer(groupName, cid); EasyMock.verify(mdObserver, consumerFactory); } #location 27 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testConsumerNormalOps() throws InterruptedException, ExecutionException { // Tests create instance, read, and delete final List<ConsumerRecord> referenceRecords = Arrays.asList( new ConsumerRecord("k1".getBytes(), "v1".getBytes(), 0, 0), new ConsumerRecord("k2".getBytes(), "v2".getBytes(), 1, 0), new ConsumerRecord("k3".getBytes(), "v3".getBytes(), 2, 0) ); Map<Integer,List<ConsumerRecord>> referenceSchedule = new HashMap<>(); referenceSchedule.put(50, referenceRecords); Map<String,List<Map<Integer,List<ConsumerRecord>>>> schedules = new HashMap<>(); schedules.put(topicName, Arrays.asList(referenceSchedule)); expectCreate(schedules); EasyMock.expect(mdObserver.topicExists(topicName)).andReturn(true); EasyMock.replay(mdObserver, consumerFactory); String cid = consumerManager.createConsumer(groupName, new ConsumerInstanceConfig()); consumerManager.readTopic(groupName, cid, topicName, new ConsumerManager.ReadCallback() { @Override public void onCompletion(List<ConsumerRecord> records, Exception e) { assertNull(e); assertEquals(referenceRecords, records); } }).get(); // With # of messages < max per request, this should finish at the per-request timeout assertEquals(config.consumerRequestTimeoutMs, config.time.milliseconds()); consumerManager.commitOffsets(groupName, cid, new ConsumerManager.CommitCallback() { @Override public void onCompletion(List<TopicPartitionOffset> offsets, Exception e) { assertNull(e); // Mock consumer doesn't handle offsets, so we just check we get some output for the right partitions assertNotNull(offsets); assertEquals(3, offsets.size()); } }).get(); consumerManager.deleteConsumer(groupName, cid); EasyMock.verify(mdObserver, consumerFactory); }
Below is the vulnerable code, please generate the patch based on the following information.