input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code public final void build() { LOGGER.info("Starting tree reconstruction"); Project inbox = new Project(); inbox.setName("Inbox"); inbox.setId("__%%Inbox"); // to give deterministic JSON/XML output Context noContext = new Context(); noContext.setName("No Context"); noContext.setId("__%%NoContext"); // to give deterministic JSON/XML output // Build Folder Hierarchy for (Folder folder : folders.values()) { String parentId = folder.getParentFolderId(); if (parentId != null) { Folder parent = folders.get(parentId); parent.add(folder); } } // Build Task Hierarchy for (Task task : tasks.values()) { String parentId = task.getParentTaskId(); if (parentId != null) { Task parent = tasks.get(parentId); parent.add(task); } if (task.isInInbox() && task.getParentTaskId() == null) { inbox.add(task); } if (task.getContextId() == null) { noContext.add(task); } } // Build Context Hierarchy for (Context context : contexts.values()) { String parentId = context.getParentContextId(); if (parentId != null) { Context parent = contexts.get(parentId); parent.add(context); } } // Add tasks to contexts for (Task task : tasks.values()) { String contextId = task.getContextId(); if (contextId != null) { Context context = contexts.get(contextId); context.getTasks().add(task); task.setContext(context); } } // Create Projects from their root tasks // Must do this after task hierarchy is woven // since a copy of the root tasks subtasks is taken for (ProjectInfo projInfo : projInfos.values()) { Task rootTask = tasks.get(projInfo.getRootTaskId()); Project project = new Project(projInfo, rootTask); // Set containing Folder for project String folderId = projInfo.getFolderId(); if (folderId != null) { Folder folder = folders.get(folderId); folder.add(project); } projects.put(project.getId(), project); // Discard the root task. But note that it'll still be // a child in any contexts tasks.remove(rootTask.getId()); } if (!inbox.getTasks().isEmpty()) { projects.put(inbox.getId(), inbox); } if (!noContext.getTasks().isEmpty()) { contexts.put(noContext.getId(), noContext); } LOGGER.info("Finished tree reconstruction"); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code public final void build() { LOGGER.info("Starting tree reconstruction"); Project inbox = beanFactory.getBean("project", Project.class); inbox.setName("Inbox"); inbox.setId("__%%Inbox"); // to give deterministic JSON/XML output Context noContext = beanFactory.getBean("context", Context.class); noContext.setName("No Context"); noContext.setId("__%%NoContext"); // to give deterministic JSON/XML output ConfigParams configParams = beanFactory.getBean("configparams", ConfigParams.class); // Build Folder Hierarchy for (Folder folder : folders.values()) { String parentId = folder.getParentFolderId(); if (parentId != null) { Folder parent = folders.get(parentId); parent.add(folder); } } // Build Task Hierarchy for (Task task : tasks.values()) { String parentId = task.getParentTaskId(); if (parentId != null) { Task parent = tasks.get(parentId); parent.add(task); } if (task.isInInbox() && task.getParentTaskId() == null) { inbox.add(task); } if (task.getContextId() == null) { noContext.add(task); } } // Build Context Hierarchy for (Context context : contexts.values()) { String parentId = context.getParentContextId(); if (parentId != null) { Context parent = contexts.get(parentId); parent.add(context); } } // Add tasks to contexts for (Task task : tasks.values()) { String contextId = task.getContextId(); if (contextId != null) { Context context = contexts.get(contextId); context.getTasks().add(task); task.setContext(context); } } // Create Projects from their root tasks // Must do this after task hierarchy is woven // since a copy of the root tasks subtasks is taken for (ProjectInfo projInfo : projInfos.values()) { Task rootTask = tasks.get(projInfo.getRootTaskId()); Project project = new Project(projInfo, rootTask); project.setConfigParams(configParams); // Set containing Folder for project String folderId = projInfo.getFolderId(); if (folderId != null) { Folder folder = folders.get(folderId); folder.add(project); } projects.put(project.getId(), project); // Discard the root task. But note that it'll still be // a child in any contexts tasks.remove(rootTask.getId()); } if (!inbox.getTasks().isEmpty()) { projects.put(inbox.getId(), inbox); } if (!noContext.getTasks().isEmpty()) { contexts.put(noContext.getId(), noContext); } LOGGER.info("Finished tree reconstruction"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean within(Date date, String lower, String upper) throws ParseException { Date lowerDate = date(lower); Date upperDate = date(upper); return date != null && date.getTime() >= lowerDate.getTime() && date.getTime() <= upperDate.getTime(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean within(Date date, String lower, String upper) throws ParseException { LOGGER.debug("within({},{},{})", date, lower, upper); Date lowerDate = date(lower); Date upperDate = date(upper); boolean result = date != null && date.getTime() >= lowerDate.getTime() && date.getTime() <= upperDate.getTime(); LOGGER.debug("within({},{},{})={}", date, lower, upper, result); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { ApplicationContext appContext = ApplicationContextFactory.create(); Main main = appContext.getBean("main", Main.class); if (!main.procesPreLoadOptions(args)) { LOGGER.debug("Exiting"); return; } main.loadData(); main.processPostLoadOptions(args); main.run(); LOGGER.debug("Exiting"); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] args) throws Exception { ApplicationContext appContext = ApplicationContextFactory.getContext(); Main main = appContext.getBean("main", Main.class); if (!main.procesPreLoadOptions(args)) { LOGGER.debug("Exiting"); return; } main.loadData(); main.processPostLoadOptions(args); main.run(); LOGGER.debug("Exiting"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; } #location 37 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别 int pc = folder.getFolderConstraint(); if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) { try { int ifc = Integer.parseInt(folderConstraint); if (ifc > 0 && account == null) { return UPLOADERROR; } if (ifc < pc) { return UPLOADERROR; } } catch (Exception e) { return UPLOADERROR; } } else { folderConstraint = pc + ""; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); // 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void writeToLog(String type, String content) { String t = ServerTimeUtil.accurateToLogName(); File f = new File(logs, t + ".klog"); FileWriter fw = null; if (f.exists()) { try { fw = new FileWriter(f, true); fw.write("\r\n\r\nTIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (Exception e1) { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } else { try { fw = new FileWriter(f, false); fw.write("TIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (IOException e1) { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code private void writeToLog(String type, String content) { writerThread.execute(()->{ String t = ServerTimeUtil.accurateToLogName(); File f = new File(logs, t + ".klog"); FileWriter fw = null; if (f.exists()) { try { fw = new FileWriter(f, true); fw.write("\r\n\r\nTIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (Exception e1) { if (Printer.instance != null) { Printer.instance.print("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } else { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } else { try { fw = new FileWriter(f, false); fw.write("TIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (IOException e1) { if (Printer.instance != null) { Printer.instance.print("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } else { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void downloadCheckedFilesZip(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String zipname = request.getParameter("zipId"); if (zipname != null && !zipname.equals("ERROR")) { final String tfPath = ConfigureReader.instance().getTemporaryfilePath(); final File zip = new File(tfPath, zipname); if (zip.exists()) { response.setContentType("application/force-download"); response.setHeader("Content-Length", "" + zip.length()); response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder .encode("kiftd_" + ServerTimeUtil.accurateToDay() + "_\u6253\u5305\u4e0b\u8f7d.zip", "UTF-8")); final FileInputStream fis = new FileInputStream(zip); final BufferedInputStream bis = new BufferedInputStream(fis); final OutputStream out = (OutputStream) response.getOutputStream(); final byte[] buffer = new byte[ConfigureReader.instance().getBuffSize()]; int count = 0; while ((count = bis.read(buffer)) != -1) { out.write(buffer, 0, count); } bis.close(); fis.close(); zip.delete(); } } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code public void downloadCheckedFilesZip(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final String zipname = request.getParameter("zipId"); if (zipname != null && !zipname.equals("ERROR")) { final String tfPath = ConfigureReader.instance().getTemporaryfilePath(); final File zip = new File(tfPath, zipname); String fname = URLEncoder .encode("kiftd_" + ServerTimeUtil.accurateToDay() + "_\u6253\u5305\u4e0b\u8f7d.zip", "UTF-8"); if (zip.exists()) { downloadRangeFile(request, response, zip, fname); zip.delete(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void getFolderView(String folderId) throws Exception { try { currentView = FileSystemManager.getInstance().getFolderView(folderId); filesTable.updateValues(currentView.getFolders(), currentView.getFiles()); window.setTitle("kiftd-" + currentView.getCurrent().getFolderName()); } catch (Exception e) { throw e; } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private void getFolderView(String folderId) throws Exception { try { currentView = FileSystemManager.getInstance().getFolderView(folderId); if(currentView!=null && currentView.getCurrent()!=null) { filesTable.updateValues(currentView.getFolders(), currentView.getFiles()); window.setTitle("kiftd-" + currentView.getCurrent().getFolderName()); }else { //浏览一个不存在的文件夹时自动返回根目录 getFolderView("root"); } } catch (Exception e) { throw e; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void doDownloadFile(final HttpServletRequest request, final HttpServletResponse response) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) { final String fileId = request.getParameter("fileId"); if (fileId != null) { final Node f = this.fm.queryById(fileId); if (f != null) { final String fileBlocks = ConfigureReader.instance().getFileBlockPath(); final File fo = this.fbu.getFileFromBlocks(fileBlocks, f.getFilePath()); try { final FileInputStream fis = new FileInputStream(fo); response.setContentType("application/force-download"); response.setHeader("Content-Length", "" + fo.length()); response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(f.getFileName(), "UTF-8")); final int buffersize = ConfigureReader.instance().getBuffSize(); final byte[] buffer = new byte[buffersize]; final BufferedInputStream bis = new BufferedInputStream(fis); final OutputStream os = (OutputStream) response.getOutputStream(); int index = 0; while ((index = bis.read(buffer)) != -1) { os.write(buffer, 0, index); } bis.close(); fis.close(); this.lu.writeDownloadFileEvent(request, f); } catch (Exception ex) { } } } } } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code public void doDownloadFile(final HttpServletRequest request, final HttpServletResponse response) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) { final String fileId = request.getParameter("fileId"); if (fileId != null) { final Node f = this.fm.queryById(fileId); if (f != null) { final String fileBlocks = ConfigureReader.instance().getFileBlockPath(); final File fo = this.fbu.getFileFromBlocks(fileBlocks, f.getFilePath()); downloadRangeFile(request, response, fo, f.getFileName());// 使用断点续传执行下载 this.lu.writeDownloadFileEvent(request, f); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void writeToLog(String type, String content) { String t = ServerTimeUtil.accurateToLogName(); File f = new File(logs, t + ".klog"); FileWriter fw = null; if (f.exists()) { try { fw = new FileWriter(f, true); fw.write("\r\n\r\nTIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (Exception e1) { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } else { try { fw = new FileWriter(f, false); fw.write("TIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (IOException e1) { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code private void writeToLog(String type, String content) { writerThread.execute(()->{ String t = ServerTimeUtil.accurateToLogName(); File f = new File(logs, t + ".klog"); FileWriter fw = null; if (f.exists()) { try { fw = new FileWriter(f, true); fw.write("\r\n\r\nTIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (Exception e1) { if (Printer.instance != null) { Printer.instance.print("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } else { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } else { try { fw = new FileWriter(f, false); fw.write("TIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n" + content); fw.close(); } catch (IOException e1) { if (Printer.instance != null) { Printer.instance.print("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } else { System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage()); } } } }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String fname = request.getParameter("fname"); final String originalFileName = (fname != null ? fname : file.getOriginalFilename()).replaceAll("\"", "_"); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES, fu.getAllFoldersId(folderId)) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> nodes = this.fm.queryByParentFolderId(folderId); if (nodes.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 如果要覆盖的文件不存在与其他节点共享文件块的情况,则找到该文件块并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 // 如果要覆盖的文件是某个文件块的众多副本之一,那么“覆盖”就是新存入一个文件块,然后再更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 case "cover": // 特殊操作权限检查,“覆盖”操作同时还要求用户必须具备删除权限,否则不能执行 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER, fu.getAllFoldersId(folderId))) { return UPLOADERROR; } for (Node f : nodes) { // 找到要覆盖的节点 if (f.getFileName().equals(originalFileName)) { try { // 首先先将该节点中必须覆盖的信息更新 f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } // 该节点对应的文件块是否独享? Map<String, String> map = new HashMap<>(); map.put("path", f.getFilePath()); map.put("fileId", f.getFileId()); List<Node> nodesHasSomeBlock = fm.queryByPathExcludeById(map); if (nodesHasSomeBlock == null || nodesHasSomeBlock.isEmpty()) { // 如果该节点的文件块仅由该节点引用,那么直接重写此文件块 if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { File block = fbu.getFileFromBlocks(f); file.transferTo(block); this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } } } else { // 如果此文件块还被其他节点引用,那么为此节点新建一个文件块 File block = fbu.saveToFileBlocks(file); // 并将该节点的文件块索引更新为新的文件块 f.setFilePath(block.getName()); if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } else { block.delete(); } } } return UPLOADERROR; } catch (Exception e) { return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, nodes); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 判断该文件夹内的文件数量是否超限 if (fm.countByParentFolderId(folderId) >= FileNodeUtil.MAXIMUM_NUM_OF_SINGLE_FOLDER) { return FILES_TOTAL_OUT_OF_LIMIT; } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final File block = this.fbu.saveToFileBlocks(file); if (block == null) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); Node newNode = fbu.insertNewNode(fileName, account, block.getName(), fsize, folderId); if (newNode != null) { // 存入成功,则写入日志并返回成功提示 this.lu.writeUploadFileEvent(request, newNode, account); return UPLOADSUCCESS; } else { // 存入失败则删除残余文件块,并返回失败提示 block.delete(); return UPLOADERROR; } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String fname = request.getParameter("fname"); final String originalFileName = (fname != null ? fname : file.getOriginalFilename()); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES, fu.getAllFoldersId(folderId)) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> nodes = this.fm.queryByParentFolderId(folderId); if (nodes.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 如果要覆盖的文件不存在与其他节点共享文件块的情况,则找到该文件块并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 // 如果要覆盖的文件是某个文件块的众多副本之一,那么“覆盖”就是新存入一个文件块,然后再更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 case "cover": // 特殊操作权限检查,“覆盖”操作同时还要求用户必须具备删除权限,否则不能执行 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER, fu.getAllFoldersId(folderId))) { return UPLOADERROR; } for (Node f : nodes) { // 找到要覆盖的节点 if (f.getFileName().equals(originalFileName)) { try { // 首先先将该节点中必须覆盖的信息更新 f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } // 该节点对应的文件块是否独享? Map<String, String> map = new HashMap<>(); map.put("path", f.getFilePath()); map.put("fileId", f.getFileId()); List<Node> nodesHasSomeBlock = fm.queryByPathExcludeById(map); if (nodesHasSomeBlock == null || nodesHasSomeBlock.isEmpty()) { // 如果该节点的文件块仅由该节点引用,那么直接重写此文件块 if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { File block = fbu.getFileFromBlocks(f); file.transferTo(block); this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } } } else { // 如果此文件块还被其他节点引用,那么为此节点新建一个文件块 File block = fbu.saveToFileBlocks(file); // 并将该节点的文件块索引更新为新的文件块 f.setFilePath(block.getName()); if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } else { block.delete(); } } } return UPLOADERROR; } catch (Exception e) { return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, nodes); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 判断该文件夹内的文件数量是否超限 if (fm.countByParentFolderId(folderId) >= FileNodeUtil.MAXIMUM_NUM_OF_SINGLE_FOLDER) { return FILES_TOTAL_OUT_OF_LIMIT; } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final File block = this.fbu.saveToFileBlocks(file); if (block == null) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); Node newNode = fbu.insertNewNode(fileName, account, block.getName(), fsize, folderId); if (newNode != null) { // 存入成功,则写入日志并返回成功提示 this.lu.writeUploadFileEvent(request, newNode, account); return UPLOADSUCCESS; } else { // 存入失败则删除残余文件块,并返回失败提示 block.delete(); return UPLOADERROR; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES, fu.getAllFoldersId(folderId)) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> nodes = this.fm.queryByParentFolderId(folderId); if (nodes.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 如果要覆盖的文件不存在与其他节点共享文件块的情况,则找到该文件块并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 // 如果要覆盖的文件是某个文件块的众多副本之一,那么“覆盖”就是新存入一个文件块,然后再更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 case "cover": // 特殊操作权限检查,“覆盖”操作同时还要求用户必须具备删除权限,否则不能执行 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER, fu.getAllFoldersId(folderId))) { return UPLOADERROR; } for (Node f : nodes) { // 找到要覆盖的节点 if (f.getFileName().equals(originalFileName)) { try { // 首先先将该节点中必须覆盖的信息更新 f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } // 该节点对应的文件块是否独享? Map<String, String> map = new HashMap<>(); map.put("path", f.getFilePath()); map.put("fileId", f.getFileId()); List<Node> nodesHasSomeBlock = fm.queryByPathExcludeById(map); if (nodesHasSomeBlock == null || nodesHasSomeBlock.isEmpty()) { // 如果该节点的文件块仅由该节点引用,那么直接重写此文件块 if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { File block = fbu.getFileFromBlocks(f); file.transferTo(block); this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } } } else { // 如果此文件块还被其他节点引用,那么为此节点新建一个文件块 File block = fbu.saveToFileBlocks(file); // 并将该节点的文件块索引更新为新的文件块 f.setFilePath(block.getName()); if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } else { block.delete(); } } } return UPLOADERROR; } catch (Exception e) { return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, nodes); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 判断该文件夹内的文件数量是否超限 if (fm.countByParentFolderId(folderId) >= FileNodeUtil.MAXIMUM_NUM_OF_SINGLE_FOLDER) { return FILES_TOTAL_OUT_OF_LIMIT; } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final File block = this.fbu.saveToFileBlocks(file); if (block == null) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); Node newNode = fbu.insertNewNode(fileName, account, block.getName(), fsize, folderId); if (newNode != null) { // 存入成功,则写入日志并返回成功提示 this.lu.writeUploadFileEvent(request, newNode, account); return UPLOADSUCCESS; } else { // 存入失败则删除残余文件块,并返回失败提示 block.delete(); return UPLOADERROR; } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String fname = request.getParameter("fname"); final String originalFileName = fname != null ? fname : file.getOriginalFilename(); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES, fu.getAllFoldersId(folderId)) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> nodes = this.fm.queryByParentFolderId(folderId); if (nodes.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 如果要覆盖的文件不存在与其他节点共享文件块的情况,则找到该文件块并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 // 如果要覆盖的文件是某个文件块的众多副本之一,那么“覆盖”就是新存入一个文件块,然后再更新原节点信息(除了文件名、父目录和ID之外的全部信息)。 case "cover": // 特殊操作权限检查,“覆盖”操作同时还要求用户必须具备删除权限,否则不能执行 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER, fu.getAllFoldersId(folderId))) { return UPLOADERROR; } for (Node f : nodes) { // 找到要覆盖的节点 if (f.getFileName().equals(originalFileName)) { try { // 首先先将该节点中必须覆盖的信息更新 f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } // 该节点对应的文件块是否独享? Map<String, String> map = new HashMap<>(); map.put("path", f.getFilePath()); map.put("fileId", f.getFileId()); List<Node> nodesHasSomeBlock = fm.queryByPathExcludeById(map); if (nodesHasSomeBlock == null || nodesHasSomeBlock.isEmpty()) { // 如果该节点的文件块仅由该节点引用,那么直接重写此文件块 if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { File block = fbu.getFileFromBlocks(f); file.transferTo(block); this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } } } else { // 如果此文件块还被其他节点引用,那么为此节点新建一个文件块 File block = fbu.saveToFileBlocks(file); // 并将该节点的文件块索引更新为新的文件块 f.setFilePath(block.getName()); if (fm.update(f) > 0) { if (fbu.isValidNode(f)) { this.lu.writeUploadFileEvent(request, f, account); return UPLOADSUCCESS; } else { block.delete(); } } } return UPLOADERROR; } catch (Exception e) { return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, nodes); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 判断该文件夹内的文件数量是否超限 if (fm.countByParentFolderId(folderId) >= FileNodeUtil.MAXIMUM_NUM_OF_SINGLE_FOLDER) { return FILES_TOTAL_OUT_OF_LIMIT; } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final File block = this.fbu.saveToFileBlocks(file); if (block == null) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); Node newNode = fbu.insertNewNode(fileName, account, block.getName(), fsize, folderId); if (newNode != null) { // 存入成功,则写入日志并返回成功提示 this.lu.writeUploadFileEvent(request, newNode, account); return UPLOADSUCCESS; } else { // 存入失败则删除残余文件块,并返回失败提示 block.delete(); return UPLOADERROR; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void writeRangeFileStream(HttpServletRequest request, HttpServletResponse response, File fo, String fname, String contentType) { long skipLength = 0;// 下载时跳过的字节数 long downLength = 0;// 需要继续下载的字节数 boolean hasEnd = false;// 是否具备结束字节声明 try { response.setHeader("Accept-Ranges", "bytes");// 支持断点续传声明 // 获取已下载字节数和需下载字节数 String rangeLabel = request.getHeader("Range");// 获取下载长度声明 if (null != rangeLabel) { // 当进行断点续传时,返回响应码206 response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 解析下载跳过长度和继续长度 rangeLabel = request.getHeader("Range").replaceAll("bytes=", ""); if (rangeLabel.indexOf('-') == rangeLabel.length() - 1) { hasEnd = false; rangeLabel = rangeLabel.substring(0, rangeLabel.indexOf('-')); skipLength = Long.parseLong(rangeLabel.trim()); } else { hasEnd = true; String startBytes = rangeLabel.substring(0, rangeLabel.indexOf('-')); String endBytes = rangeLabel.substring(rangeLabel.indexOf('-') + 1, rangeLabel.length()); skipLength = Long.parseLong(startBytes.trim()); downLength = Long.parseLong(endBytes); } } // 设置响应中文件块声明 long fileLength = fo.length();// 文件长度 if (0 != skipLength) { String contentRange = ""; if (hasEnd) { contentRange = new StringBuffer(rangeLabel).append("/").append(new Long(fileLength).toString()) .toString(); } else { contentRange = new StringBuffer("bytes").append(new Long(skipLength).toString()).append("-") .append(new Long(fileLength - 1).toString()).append("/") .append(new Long(fileLength).toString()).toString(); } response.setHeader("Content-Range", contentRange); } // 开始执行下载 response.setContentType(contentType); response.setHeader("Content-Length", "" + fileLength); response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fname, "UTF-8")); final int buffersize = ConfigureReader.instance().getBuffSize(); final byte[] buffer = new byte[buffersize]; final RandomAccessFile raf = new RandomAccessFile(fo, "r"); final OutputStream os = (OutputStream) response.getOutputStream(); raf.seek(skipLength);// 跳过已经下载的字节数 if (hasEnd) { while (raf.getFilePointer() < downLength) { os.write(raf.read()); } } else { int index = 0; while ((index = raf.read(buffer)) != -1) { os.write(buffer, 0, index); } } raf.close(); os.close(); } catch (Exception ex) { ex.printStackTrace(); } } #location 62 #vulnerability type RESOURCE_LEAK
#fixed code protected void writeRangeFileStream(HttpServletRequest request, HttpServletResponse response, File fo, String fname, String contentType) { long fileLength = fo.length(); // 记录文件大小 long pastLength = 0; // 记录已下载文件大小 int rangeSwitch = 0; // 0:从头开始的全文下载;1:从某字节开始的下载(bytes=27000-);2:从某字节开始到某字节结束的下载(bytes=27000-39000) long toLength = 0; // 记录客户端需要下载的字节段的最后一个字节偏移量(比如bytes=27000-39000,则这个值是为39000) long contentLength = 0; // 客户端请求的字节总量 String rangeBytes = ""; // 记录客户端传来的形如“bytes=27000-”或者“bytes=27000-39000”的内容 OutputStream os = null; // 写出数据 OutputStream out = null; // 缓冲 byte b[] = new byte[ConfigureReader.instance().getBuffSize()]; // 暂存容器 if (request.getHeader("Range") != null) { // 客户端请求的下载的文件块的开始字节 response.setStatus(javax.servlet.http.HttpServletResponse.SC_PARTIAL_CONTENT); rangeBytes = request.getHeader("Range").replaceAll("bytes=", ""); if (rangeBytes.indexOf('-') == rangeBytes.length() - 1) {// bytes=969998336- rangeSwitch = 1; rangeBytes = rangeBytes.substring(0, rangeBytes.indexOf('-')); pastLength = Long.parseLong(rangeBytes.trim()); contentLength = fileLength - pastLength; // 客户端请求的是 969998336 之后的字节 } else { // bytes=1275856879-1275877358 rangeSwitch = 2; String temp0 = rangeBytes.substring(0, rangeBytes.indexOf('-')); String temp2 = rangeBytes.substring(rangeBytes.indexOf('-') + 1, rangeBytes.length()); pastLength = Long.parseLong(temp0.trim()); // bytes=1275856879-1275877358,从第 1275856879 个字节开始下载 toLength = Long.parseLong(temp2); // bytes=1275856879-1275877358,到第 1275877358 个字节结束 contentLength = toLength - pastLength; // 客户端请求的是 1275856879-1275877358 之间的字节 } } else { // 从开始进行下载 contentLength = fileLength; // 客户端要求全文下载 } /** * 如果设设置了Content -Length,则客户端会自动进行多线程下载。如果不希望支持多线程,则不要设置这个参数。 响应的格式是: Content - * Length: [文件的总大小] - [客户端请求的下载的文件块的开始字节] * ServletActionContext.getResponse().setHeader("Content- Length", new * Long(file.length() - p).toString()); */ response.setHeader("Accept-Ranges", "bytes");// 如果是第一次下,还没有断点续传,状态是默认的 200,无需显式设置;响应的格式是:HTTP/1.1 200 OK if (pastLength != 0) { // 不是从最开始下载, // 响应的格式是: // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小] switch (rangeSwitch) { case 1: { // 针对 bytes=27000- 的请求 String contentRange = new StringBuffer("bytes ").append(new Long(pastLength).toString()).append("-") .append(new Long(fileLength - 1).toString()).append("/").append(new Long(fileLength).toString()) .toString(); response.setHeader("Content-Range", contentRange); break; } case 2: { // 针对 bytes=27000-39000 的请求 String contentRange = new StringBuffer("bytes ").append(rangeBytes).append("/").append(new Long(fileLength).toString()).toString(); response.setHeader("Content-Range", contentRange); break; } default: { break; } } } else { // 是从开始下载 } response.addHeader("Content-Disposition", "attachment; filename=\"" + fname + "\""); response.setContentType(contentType); // set the MIME type. response.addHeader("Content-Length", String.valueOf(contentLength)); try (RandomAccessFile raf = new RandomAccessFile(fo, "r")) { os = response.getOutputStream(); out = new BufferedOutputStream(os); System.out.println("--Range Download--"); System.out.println("Content-Type:"+response.getContentType()); System.out.println("Content-Length:"+response.getHeader("Content-Length")); System.out.println("Content-Range:"+response.getHeader("Content-Range")); System.out.println("--Range Download--"); switch (rangeSwitch) { case 0: { // 普通下载,或者从头开始的下载 // 同1 } case 1: { // 针对 bytes=27000- 的请求 raf.seek(pastLength); // 形如 bytes=969998336- 的客户端请求,跳过 969998336 个字节 int n = 0; while ((n = raf.read(b)) != -1) { out.write(b, 0, n); } break; } case 2: { // 针对 bytes=27000-39000 的请求 raf.seek(pastLength); // 形如 bytes=1275856879-1275877358 的客户端请求,找到第 1275856879 个字节 int n = 0; long readLength = 0; // 记录已读字节数 while (readLength <= contentLength) {// 大部分字节在这里读取 n = raf.read(b); readLength += n; out.write(b, 0, n); } break; } default: { break; } } out.flush(); } catch (IOException ex) { } finally { } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void getCondensedPicture(final HttpServletRequest request, final HttpServletResponse response) { // TODO 自动生成的方法存根 if (ConfigureReader.instance().authorized((String) request.getSession().getAttribute("ACCOUNT"), AccountAuth.DOWNLOAD_FILES)) { String fileId = request.getParameter("fileId"); if (fileId != null) { Node node = fm.queryById(fileId); if (node != null) { File pBlock = fbu.getFileFromBlocks(node); if (pBlock.exists()) { try { int pSize = Integer.parseInt(node.getFileSize()); if (pSize < 3) { Thumbnails.of(pBlock).size(1024, 1024).outputFormat("JPG") .toOutputStream(response.getOutputStream()); } else if (pSize < 5) { Thumbnails.of(pBlock).size(1440, 1440).outputFormat("JPG") .toOutputStream(response.getOutputStream()); } else { Thumbnails.of(pBlock).size(1680, 1680).outputFormat("JPG") .toOutputStream(response.getOutputStream()); } } catch (IOException e) { // TODO 自动生成的 catch 块 // 压缩失败时,尝试以源文件进行预览 try { Files.copy(pBlock.toPath(), response.getOutputStream()); } catch (IOException e1) { // TODO 自动生成的 catch 块 } } } } } } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void getCondensedPicture(final HttpServletRequest request, final HttpServletResponse response) { // TODO 自动生成的方法存根 if (ConfigureReader.instance().authorized((String) request.getSession().getAttribute("ACCOUNT"), AccountAuth.DOWNLOAD_FILES)) { String fileId = request.getParameter("fileId"); if (fileId != null) { Node node = fm.queryById(fileId); if (node != null) { File pBlock = fbu.getFileFromBlocks(node); if (pBlock != null && pBlock.exists()) { try { int pSize = Integer.parseInt(node.getFileSize()); if (pSize < 3) { Thumbnails.of(pBlock).size(1024, 1024).outputFormat("JPG") .toOutputStream(response.getOutputStream()); } else if (pSize < 5) { Thumbnails.of(pBlock).size(1440, 1440).outputFormat("JPG") .toOutputStream(response.getOutputStream()); } else { Thumbnails.of(pBlock).size(1680, 1680).outputFormat("JPG") .toOutputStream(response.getOutputStream()); } } catch (IOException e) { // TODO 自动生成的 catch 块 // 压缩失败时,尝试以源文件进行预览 try { Files.copy(pBlock.toPath(), response.getOutputStream()); } catch (IOException e1) { // TODO 自动生成的 catch 块 } } } } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { Folder testfolder = folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); // 若有重名,则判定该用户是否具备删除权限,这是能够覆盖的第一步 if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { // 接下来判断其是否具备冲突文件夹的访问权限,这是能够覆盖的第二步 if (ConfigureReader.instance().accessFolder(testfolder, account)) { cifr.setResult("coverOrBoth"); return gson.toJson(cifr); } } // 如果上述条件不满足,则只能允许保留两者 cifr.setResult("onlyBoth"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } } #location 39 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); cifr.setResult("repeatFolder"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } for (String pName : paths) { try { Folder target = flm.queryByParentId(folderId).parallelStream() .filter((e) -> e.getFolderName().equals(pName)).findAny().get(); if (ConfigureReader.instance().accessFolder(target, account)) { folderId = target.getFolderId();// 向下迭代直至将父路径全部迭代完毕并找到最终路径 } else { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } } catch (NoSuchElementException e) { Folder newFolder = fu.createNewFolder(flm.queryById(folderId), account, pName, folderConstraint); if (newFolder != null) { folderId = newFolder.getFolderId(); } else { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } } } String fileName = getFileNameFormPath(originalFileName); // 检查是否存在同名文件。存在则直接失败(确保上传的文件夹内容的原始性) final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(fileName))) { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); int i = 0; // 尽可能避免UUID重复的情况发生,重试10次 while (true) { try { if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(f2, account); synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADSUCCESS; } break; } catch (Exception e) { f2.setFileId(UUID.randomUUID().toString()); i++; } if (i >= 10) { break; } } synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return UPLOADERROR; } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean removeAddedAuthByFolderId(List<String> fIds) { if(fIds == null || fIds.size() == 0) { return false; } Set<String> configs=accountp.stringPropertieNames(); List<String> invalidConfigs = new ArrayList<>(); for(String fId:fIds) { for (String config:configs) { if(config.endsWith(".auth."+fId)) { invalidConfigs.add(config); } } } for(String config:invalidConfigs) { accountp.removeProperty(config); } try { accountp.store(new FileOutputStream(this.confdir + ACCOUNT_PROPERTIES_FILE), null); return true; } catch (Exception e) { Printer.instance.print("错误:更新账户配置文件时出现错误,请立即检查账户配置文件。"); return false; } } #location 18 #vulnerability type RESOURCE_LEAK
#fixed code public boolean removeAddedAuthByFolderId(List<String> fIds) { if (fIds == null || fIds.size() == 0) { return false; } Set<String> configs = accountp.stringPropertieNames(); List<String> invalidConfigs = new ArrayList<>(); for (String fId : fIds) { for (String config : configs) { if (config.endsWith(".auth." + fId)) { invalidConfigs.add(config); } } } for (String config : invalidConfigs) { accountp.removeProperty(config); } try (FileOutputStream accountSettingOut = new FileOutputStream(this.confdir + ACCOUNT_PROPERTIES_FILE)) { FileLock lock = accountSettingOut.getChannel().lock(); accountp.store(accountSettingOut, null); lock.release(); return true; } catch (Exception e) { Printer.instance.print("错误:更新账户配置文件时出现错误,请立即检查账户配置文件。"); return false; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别 int pc = folder.getFolderConstraint(); if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) { try { int ifc = Integer.parseInt(folderConstraint); if (ifc > 0 && account == null) { return UPLOADERROR; } if (ifc < pc) { return UPLOADERROR; } } catch (Exception e) { return UPLOADERROR; } } else { folderConstraint = pc + ""; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); // 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { Folder testfolder = folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); // 若有重名,则判定该用户是否具备删除权限,这是能够覆盖的第一步 if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { // 接下来判断其是否具备冲突文件夹的访问权限,这是能够覆盖的第二步 if (ConfigureReader.instance().accessFolder(testfolder, account)) { cifr.setResult("coverOrBoth"); return gson.toJson(cifr); } } // 如果上述条件不满足,则只能允许保留两者 cifr.setResult("onlyBoth"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); cifr.setResult("repeatFolder"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } // 比对上传钥匙,如果有则允许上传,否则丢弃该资源。该钥匙用完后立即销毁。 boolean isUpload = false; if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { for (Cookie c : request.getCookies()) { if (KIFTD_UPLOAD_KEY.equals(c.getName())) { synchronized (keyList) { if (keyList.contains(c.getValue())) {//比对钥匙有效性 isUpload = true; keyList.remove(c.getValue());//销毁这把钥匙 c.setMaxAge(0); response.addCookie(c); } else { return UPLOADERROR; } } } } } if (!isUpload) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息) case "cover": // 其中覆盖操作同时要求用户必须具备删除权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { return UPLOADERROR; } for (Node f : files) { if (f.getFileName().equals(originalFileName)) { File file2 = fbu.getFileFromBlocks(f); try { file.transferTo(file2); f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } if (fm.update(f) > 0) { this.lu.writeUploadFileEvent(request, f); return UPLOADSUCCESS; } else { return UPLOADERROR; } } catch (Exception e) { // TODO 自动生成的 catch 块 return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, files); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(request, f2); return UPLOADSUCCESS; } return UPLOADERROR; } #location 51 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } // 比对上传钥匙,如果有则允许上传,否则丢弃该资源。该钥匙用完后立即销毁。 boolean isUpload = false; for (Cookie c : request.getCookies()) { if (KIFTD_UPLOAD_KEY.equals(c.getName())) { synchronized (keyList) { if (keyList.contains(c.getValue())) {// 比对钥匙有效性 isUpload = true; keyList.remove(c.getValue());// 销毁这把钥匙 c.setMaxAge(0); response.addCookie(c); } else { return UPLOADERROR; } } } } if (!isUpload) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息) case "cover": // 其中覆盖操作同时要求用户必须具备删除权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { return UPLOADERROR; } for (Node f : files) { if (f.getFileName().equals(originalFileName)) { File file2 = fbu.getFileFromBlocks(f); try { file.transferTo(file2); f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } if (fm.update(f) > 0) { this.lu.writeUploadFileEvent(request, f); return UPLOADSUCCESS; } else { return UPLOADERROR; } } catch (Exception e) { // TODO 自动生成的 catch 块 return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, files); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(request, f2); return UPLOADSUCCESS; } return UPLOADERROR; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean deleteFromFileBlocks(Node f) { // 先判断一下文件块所在的存储区 File rootPath = new File(ConfigureReader.instance().getFileBlockPath()); if (!f.getFilePath().startsWith("file_")) {// 存放于主文件系统中 short index = Short.parseShort(f.getFilePath().substring(0, f.getFilePath().indexOf('_'))); rootPath = ConfigureReader.instance().getExtendStores().parallelStream() .filter((e) -> e.getIndex() == index).findAny().get().getPath(); } // 获取对应的文件块对象 File file = getFileFromBlocks(f); if (file != null) { if (file.delete()) { File parentPath = file.getParentFile(); while (parentPath != null && parentPath.isDirectory() && (!parentPath.equals(rootPath)) && parentPath.list().length == 0) { File thisPath = parentPath; parentPath = thisPath.getParentFile(); thisPath.delete(); } return true; } } return false; } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean deleteFromFileBlocks(Node f) { // 获取对应的文件块对象 File file = getFileFromBlocks(f); if (file != null) { return file.delete();// 执行删除操作 } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别 int pc = folder.getFolderConstraint(); if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) { try { int ifc = Integer.parseInt(folderConstraint); if (ifc > 0 && account == null) { return UPLOADERROR; } if (ifc < pc) { return UPLOADERROR; } } catch (Exception e) { return UPLOADERROR; } } else { folderConstraint = pc + ""; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); // 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } for (String pName : paths) { try { Folder target = flm.queryByParentId(folderId).parallelStream() .filter((e) -> e.getFolderName().equals(pName)).findAny().get(); if (ConfigureReader.instance().accessFolder(target, account)) { folderId = target.getFolderId();// 向下迭代直至将父路径全部迭代完毕并找到最终路径 } else { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } } catch (NoSuchElementException e) { Folder newFolder = fu.createNewFolder(flm.queryById(folderId), account, pName, folderConstraint); if (newFolder != null) { folderId = newFolder.getFolderId(); } else { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } } } String fileName = getFileNameFormPath(originalFileName); // 检查是否存在同名文件。存在则直接失败(确保上传的文件夹内容的原始性) final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(fileName))) { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); int i = 0; // 尽可能避免UUID重复的情况发生,重试10次 while (true) { try { if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(f2, account); synchronized (pathsKeys) { pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传 } return UPLOADSUCCESS; } break; } catch (Exception e) { f2.setFileId(UUID.randomUUID().toString()); i++; } if (i >= 10) { break; } } synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return UPLOADERROR; } #location 41 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String getVideoTranscodeStatus(HttpServletRequest request) { if (ConfigureReader.instance().isEnableFFMPEG()) { String fId = request.getParameter("fileId"); if (fId != null) { try { return vtu.getTranscodeProcess(fId); } catch (Exception e) { Printer.instance.print("错误:视频转码功能出现意外错误。详细信息:" + e.getMessage()); lu.writeException(e); } } } return "ERROR"; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String getVideoTranscodeStatus(HttpServletRequest request) { if (kfl.getFFMPEGExecutablePath() != null) { String fId = request.getParameter("fileId"); if (fId != null) { try { return vtu.getTranscodeProcess(fId); } catch (Exception e) { Printer.instance.print("错误:视频转码功能出现意外错误。详细信息:" + e.getMessage()); lu.writeException(e); } } } return "ERROR"; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { Folder testfolder = folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); // 若有重名,则判定该用户是否具备删除权限,这是能够覆盖的第一步 if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { // 接下来判断其是否具备冲突文件夹的访问权限,这是能够覆盖的第二步 if (ConfigureReader.instance().accessFolder(testfolder, account)) { cifr.setResult("coverOrBoth"); return gson.toJson(cifr); } } // 如果上述条件不满足,则只能允许保留两者 cifr.setResult("onlyBoth"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } } #location 37 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); cifr.setResult("repeatFolder"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } // 检查上传凭证,如果有则允许上传,否则丢弃该资源。该凭证用完后立即销毁。 String uploadKey = request.getParameter("uploadKey"); if (uploadKey != null) { synchronized (keyEffecMap) { UploadKeyCertificate c = keyEffecMap.get(uploadKey); if (c != null && c.isEffective()) {// 比对凭证有效性 c.checked();// 使用一次 account = c.getAccount(); if (!c.isEffective()) { keyEffecMap.remove(uploadKey);// 用完后销毁这个凭证 } } else { return UPLOADERROR; } } } else { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息) case "cover": // 其中覆盖操作同时要求用户必须具备删除权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { return UPLOADERROR; } for (Node f : files) { if (f.getFileName().equals(originalFileName)) { File file2 = fbu.getFileFromBlocks(f); try { file.transferTo(file2); f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } if (fm.update(f) > 0) { this.lu.writeUploadFileEvent(f, account); return UPLOADSUCCESS; } else { return UPLOADERROR; } } catch (Exception e) { // TODO 自动生成的 catch 块 return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, files); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); int i = 0; // 尽可能避免UUID重复的情况发生,重试10次 while (true) { try { if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(f2, account); return UPLOADSUCCESS; } break; } catch (Exception e) { f2.setFileId(UUID.randomUUID().toString()); i++; } if (i >= 10) { break; } } return UPLOADERROR; } #location 43 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } // 检查上传凭证,如果有则允许上传,否则丢弃该资源。该凭证用完后立即销毁。 String uploadKey = request.getParameter("uploadKey"); if (uploadKey != null) { synchronized (keyEffecMap) { UploadKeyCertificate c = keyEffecMap.get(uploadKey); if (c != null && c.isEffective()) {// 比对凭证有效性 c.checked();// 使用一次 account = c.getAccount(); if (!c.isEffective()) { keyEffecMap.remove(uploadKey);// 用完后销毁这个凭证 } } else { return UPLOADERROR; } } } else { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息) case "cover": // 其中覆盖操作同时要求用户必须具备删除权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { return UPLOADERROR; } for (Node f : files) { if (f.getFileName().equals(originalFileName)) { File file2 = fbu.getFileFromBlocks(f); try { file.transferTo(file2); f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } if (fm.update(f) > 0) { this.lu.writeUploadFileEvent(f, account); return UPLOADSUCCESS; } else { return UPLOADERROR; } } catch (Exception e) { // TODO 自动生成的 catch 块 return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, files); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); int i = 0; // 尽可能避免UUID重复的情况发生,重试10次 while (true) { try { if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(f2, account); return UPLOADSUCCESS; } break; } catch (Exception e) { f2.setFileId(UUID.randomUUID().toString()); i++; } if (i >= 10) { break; } } return UPLOADERROR; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void getLRContextByUTF8(String fileId, HttpServletRequest request, HttpServletResponse response) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); // 权限检查 if (fileId != null) { Node n = nm.queryById(fileId); if (n != null) { if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES, fu.getAllFoldersId(n.getFileParentFolder())) && ConfigureReader.instance().accessFolder(fm.queryById(n.getFileParentFolder()), account)) { File file = fbu.getFileFromBlocks(n); if (file != null && file.isFile()) { // 后缀检查 String suffix = ""; if (n.getFileName().indexOf(".") >= 0) { suffix = n.getFileName().substring(n.getFileName().lastIndexOf(".")).trim().toLowerCase(); } if (".lrc".equals(suffix)) { String contentType = "text/plain"; response.setContentType(contentType); // 执行转换并写出输出流 try { String inputFileEncode = tcg.getTxtCharset(new FileInputStream(file)); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(file), inputFileEncode)); BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(response.getOutputStream(), "UTF-8")); String line; while ((line = bufferedReader.readLine()) != null) { bufferedWriter.write(line); bufferedWriter.newLine(); } bufferedWriter.close(); bufferedReader.close(); return; } catch (IOException e) { } catch (Exception e) { Printer.instance.print(e.getMessage()); lu.writeException(e); } } } } } } try { response.sendError(500); } catch (Exception e1) { } } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void getLRContextByUTF8(String fileId, HttpServletRequest request, HttpServletResponse response) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); // 权限检查 if (fileId != null) { Node n = nm.queryById(fileId); if (n != null) { if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES, fu.getAllFoldersId(n.getFileParentFolder())) && ConfigureReader.instance().accessFolder(fm.queryById(n.getFileParentFolder()), account)) { File file = fbu.getFileFromBlocks(n); if (file != null && file.isFile()) { // 后缀检查 String suffix = ""; if (n.getFileName().indexOf(".") >= 0) { suffix = n.getFileName().substring(n.getFileName().lastIndexOf(".")).trim().toLowerCase(); } if (".lrc".equals(suffix)) { String contentType = "text/plain"; response.setContentType(contentType); response.setCharacterEncoding("UTF-8"); String lastModified = file.lastModified() + ""; response.setHeader("ETag", lastModified); response.setHeader("Last-Modified", lastModified); // 执行转换并写出输出流 try { String inputFileEncode = tcg.getTxtCharset(new FileInputStream(file)); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(new FileInputStream(file), inputFileEncode)); BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter(response.getOutputStream(), "UTF-8")); String line; while ((line = bufferedReader.readLine()) != null) { bufferedWriter.write(line); bufferedWriter.newLine(); } bufferedWriter.close(); bufferedReader.close(); return; } catch (IOException e) { } catch (Exception e) { Printer.instance.print(e.getMessage()); lu.writeException(e); } } } } } } try { response.sendError(500); } catch (Exception e1) { } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String checkLoginRequest(final HttpServletRequest request, final HttpSession session) { final String encrypted = request.getParameter("encrypted"); final String loginInfoStr = DecryptionUtil.dncryption(encrypted, ku.getPrivateKey()); try { final LoginInfoPojo info = gson.fromJson(loginInfoStr, LoginInfoPojo.class); if (System.currentTimeMillis() - Long.parseLong(info.getTime()) > TIME_OUT) { return "error"; } final String accountId = info.getAccountId(); if (!ConfigureReader.instance().foundAccount(accountId)) { return "accountnotfound"; } // 如果验证码开启且该账户已被关注,则要求提供验证码 if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) { synchronized (focusAccount) { if (focusAccount.contains(accountId)) { String reqVerCode = request.getParameter("vercode"); String trueVerCode = (String) session.getAttribute("VERCODE"); session.removeAttribute("VERCODE");// 确保一个验证码只会生效一次,无论对错 if (reqVerCode == null || trueVerCode == null || !trueVerCode.equals(reqVerCode.toLowerCase())) { return "needsubmitvercode"; } } } } if (ConfigureReader.instance().checkAccountPwd(accountId, info.getAccountPwd())) { session.setAttribute("ACCOUNT", (Object) accountId); // 如果该账户输入正确且是一个被关注的账户,则解除该账户的关注,释放空间 if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) { synchronized (focusAccount) { focusAccount.remove(accountId); } } return "permitlogin"; } // 如果账户密码不匹配,则将该账户加入到关注账户集合,避免对方进一步破解 synchronized (focusAccount) { if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) { focusAccount.add(accountId); } } return "accountpwderror"; } catch (Exception e) { return "error"; } } #location 14 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public String checkLoginRequest(final HttpServletRequest request, final HttpSession session) { final String encrypted = request.getParameter("encrypted"); try { final String loginInfoStr = DecryptionUtil.dncryption(encrypted, ku.getPrivateKey()); final LoginInfoPojo info = gson.fromJson(loginInfoStr, LoginInfoPojo.class); if (System.currentTimeMillis() - Long.parseLong(info.getTime()) > TIME_OUT) { return "error"; } final String accountId = info.getAccountId(); if (!ConfigureReader.instance().foundAccount(accountId)) { return "accountnotfound"; } // 如果验证码开启且该账户已被关注,则要求提供验证码 if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) { synchronized (focusAccount) { if (focusAccount.contains(accountId)) { String reqVerCode = request.getParameter("vercode"); String trueVerCode = (String) session.getAttribute("VERCODE"); session.removeAttribute("VERCODE");// 确保一个验证码只会生效一次,无论对错 if (reqVerCode == null || trueVerCode == null || !trueVerCode.equals(reqVerCode.toLowerCase())) { return "needsubmitvercode"; } } } } if (ConfigureReader.instance().checkAccountPwd(accountId, info.getAccountPwd())) { session.setAttribute("ACCOUNT", (Object) accountId); // 如果该账户输入正确且是一个被关注的账户,则解除该账户的关注,释放空间 if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) { synchronized (focusAccount) { focusAccount.remove(accountId); } } return "permitlogin"; } // 如果账户密码不匹配,则将该账户加入到关注账户集合,避免对方进一步破解 synchronized (focusAccount) { if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) { focusAccount.add(accountId); } } return "accountpwderror"; } catch (Exception e) { return "error"; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void deleteFolder(String folderId) throws SQLException { Folder f = selectFolderById(folderId); List<Node> nodes = selectNodesByFolderId(folderId); int size = nodes.size(); // 删除该文件夹内的所有文件 for (int i = 0; i < size && gono; i++) { deleteFile(nodes.get(i).getFileId()); } List<Folder> folders = getFoldersByParentId(folderId); size = folders.size(); // 迭代删除该文件夹内的所有文件夹 for (int i = 0; i < size && gono; i++) { deleteFolder(folders.get(i).getFolderId()); } per = 50; message = "正在删除文件夹:" + f.getFolderName(); // 删除自己的数据 if (deleteFolderById(folderId) > 0) { per = 100; return; } throw new SQLException(); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code private void deleteFolder(String folderId) throws SQLException { Folder f = selectFolderById(folderId); List<Node> nodes = selectNodesByFolderId(folderId); int size = nodes.size(); if(f==null) { return; } // 删除该文件夹内的所有文件 for (int i = 0; i < size && gono; i++) { deleteFile(nodes.get(i).getFileId()); } List<Folder> folders = getFoldersByParentId(folderId); size = folders.size(); // 迭代删除该文件夹内的所有文件夹 for (int i = 0; i < size && gono; i++) { deleteFolder(folders.get(i).getFolderId()); } per = 50; message = "正在删除文件夹:" + f.getFolderName(); // 删除自己的数据 if (deleteFolderById(folderId) > 0) { per = 100; return; } throw new SQLException(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别 int pc = folder.getFolderConstraint(); if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) { try { int ifc = Integer.parseInt(folderConstraint); if (ifc > 0 && account == null) { return UPLOADERROR; } if (ifc < pc) { return UPLOADERROR; } } catch (Exception e) { return UPLOADERROR; } } else { folderConstraint = pc + ""; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); // 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { Folder testfolder = folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); // 若有重名,则判定该用户是否具备删除权限,这是能够覆盖的第一步 if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { // 接下来判断其是否具备冲突文件夹的访问权限,这是能够覆盖的第二步 if (ConfigureReader.instance().accessFolder(testfolder, account)) { cifr.setResult("coverOrBoth"); return gson.toJson(cifr); } } // 如果上述条件不满足,则只能允许保留两者 cifr.setResult("onlyBoth"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String checkImportFolder(HttpServletRequest request) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String folderName = request.getParameter("folderName"); final String maxUploadFileSize = request.getParameter("maxSize"); CheckImportFolderRespons cifr = new CheckImportFolderRespons(); // 先行权限检查 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) { cifr.setResult(NO_AUTHORIZED); return gson.toJson(cifr); } // 开始文件上传体积限制检查 try { // 获取最大文件体积(以Byte为单位) long mufs = Long.parseLong(maxUploadFileSize); long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account); if (pMaxUploadSize >= 0) { if (mufs > pMaxUploadSize) { cifr.setResult("fileOverSize"); cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account))); return gson.toJson(cifr); } } } catch (Exception e) { cifr.setResult(ERROR_PARAMETER); return gson.toJson(cifr); } // 开始文件夹命名冲突检查,若无重名则允许上传。 final List<Folder> folders = flm.queryByParentId(folderId); try { folders.stream().parallel() .filter((n) -> n.getFolderName().equals( new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")))) .findAny().get(); cifr.setResult("repeatFolder"); return gson.toJson(cifr); } catch (NoSuchElementException e) { // 通过所有检查,允许上传 cifr.setResult("permitUpload"); return gson.toJson(cifr); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } // 比对上传钥匙,如果有则允许上传,否则丢弃该资源。该钥匙用完后立即销毁。 boolean isUpload = false; for (Cookie c : request.getCookies()) { if (KIFTD_UPLOAD_KEY.equals(c.getName())) { synchronized (keyList) { if (keyList.contains(c.getValue())) {// 比对钥匙有效性 isUpload = true; keyList.remove(c.getValue());// 销毁这把钥匙 c.setMaxAge(0); response.addCookie(c); } else { return UPLOADERROR; } } } } if (!isUpload) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息) case "cover": // 其中覆盖操作同时要求用户必须具备删除权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { return UPLOADERROR; } for (Node f : files) { if (f.getFileName().equals(originalFileName)) { File file2 = fbu.getFileFromBlocks(f); try { file.transferTo(file2); f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } if (fm.update(f) > 0) { this.lu.writeUploadFileEvent(request, f); return UPLOADSUCCESS; } else { return UPLOADERROR; } } catch (Exception e) { // TODO 自动生成的 catch 块 return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, files); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(request, f2); return UPLOADSUCCESS; } return UPLOADERROR; } #location 44 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response, final MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); final String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String fileName = originalFileName; final String repeType = request.getParameter("repeType"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } // 比对上传钥匙,如果有则允许上传,否则丢弃该资源。该钥匙用完后立即销毁。 boolean isUpload = false; for (Cookie c : request.getCookies()) { if (KIFTD_UPLOAD_KEY.equals(c.getName())) { synchronized (keyMap) { Integer i=keyMap.get(c.getValue()); if (i!=null) {// 比对钥匙有效性 isUpload = true; i--; if(i<=0) { keyMap.remove(c.getValue());// 销毁这把钥匙 c.setMaxAge(0); response.addCookie(c); } } else { return UPLOADERROR; } } } } if (!isUpload) { return UPLOADERROR; } // 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。 final List<Node> files = this.fm.queryByParentFolderId(folderId); if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) { // 针对存在同名文件的操作 if (repeType != null) { switch (repeType) { // 跳过则忽略上传请求并直接返回上传成功(跳过不应上传) case "skip": return UPLOADSUCCESS; // 覆盖则找到已存在文件节点的File并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息) case "cover": // 其中覆盖操作同时要求用户必须具备删除权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) { return UPLOADERROR; } for (Node f : files) { if (f.getFileName().equals(originalFileName)) { File file2 = fbu.getFileFromBlocks(f); try { file.transferTo(file2); f.setFileSize(fbu.getFileSize(file)); f.setFileCreationDate(ServerTimeUtil.accurateToDay()); if (account != null) { f.setFileCreator(account); } else { f.setFileCreator("\u533f\u540d\u7528\u6237"); } if (fm.update(f) > 0) { this.lu.writeUploadFileEvent(request, f); return UPLOADSUCCESS; } else { return UPLOADERROR; } } catch (Exception e) { // TODO 自动生成的 catch 块 return UPLOADERROR; } } } return UPLOADERROR; // 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2 case "both": // 设置新文件名为标号形式 fileName = FileNodeUtil.getNewNodeName(originalFileName, files); break; default: // 其他声明,容错,暂无效果 return UPLOADERROR; } } else { // 如果既有重复文件、同时又没声明如何操作,则直接上传失败。 return UPLOADERROR; } } // 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。 final String path = this.fbu.saveToFileBlocks(file); if (path.equals("ERROR")) { return UPLOADERROR; } final String fsize = this.fbu.getFileSize(file); final Node f2 = new Node(); f2.setFileId(UUID.randomUUID().toString()); if (account != null) { f2.setFileCreator(account); } else { f2.setFileCreator("\u533f\u540d\u7528\u6237"); } f2.setFileCreationDate(ServerTimeUtil.accurateToDay()); f2.setFileName(fileName); f2.setFileParentFolder(folderId); f2.setFilePath(path); f2.setFileSize(fsize); if (this.fm.insert(f2) > 0) { this.lu.writeUploadFileEvent(request, f2); return UPLOADSUCCESS; } return UPLOADERROR; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); final String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); //将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String pathskey = Arrays.toString(paths); synchronized (pathsKeys) { if(pathsKeys.contains(pathskey)) { return UPLOADERROR; }else { pathsKeys.add(pathskey); } } String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); synchronized (pathsKeys) { pathsKeys.remove(pathskey); } return result; } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String doImportFolder(HttpServletRequest request, MultipartFile file) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); String folderId = request.getParameter("folderId"); final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8")); String folderConstraint = request.getParameter("folderConstraint"); // 再次检查上传文件名与目标目录ID if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) { return UPLOADERROR; } Folder folder = flm.queryById(folderId); if (folder == null) { return UPLOADERROR; } // 检查上传权限 if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES) || !ConfigureReader.instance().accessFolder(folder, account)) { return UPLOADERROR; } // 检查上传文件体积是否超限 long mufs = ConfigureReader.instance().getUploadFileSize(account); if (mufs >= 0 && file.getSize() > mufs) { return UPLOADERROR; } // 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别 int pc = folder.getFolderConstraint(); if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) { try { int ifc = Integer.parseInt(folderConstraint); if (ifc > 0 && account == null) { return UPLOADERROR; } if (ifc < pc) { return UPLOADERROR; } } catch (Exception e) { return UPLOADERROR; } } else { folderConstraint = pc + ""; } // 计算相对路径的文件夹ID(即真正要保存的文件夹目标) String[] paths = getParentPath(originalFileName); // 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。 String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void createDefaultAccountPropertiesFile() { Printer.instance.print("正在生成初始账户配置文件(" + this.confdir + ACCOUNT_PROPERTIES_FILE + ")..."); final Properties dap = new Properties(); dap.setProperty(DEFAULT_ACCOUNT_ID + ".pwd", DEFAULT_ACCOUNT_PWD); dap.setProperty(DEFAULT_ACCOUNT_ID + ".auth", DEFAULT_ACCOUNT_AUTH); dap.setProperty("authOverall", DEFAULT_AUTH_OVERALL); try { dap.store(new FileOutputStream(this.confdir + ACCOUNT_PROPERTIES_FILE), "<This is the default kiftd account setting file. >"); Printer.instance.print("初始账户配置文件生成完毕。"); } catch (FileNotFoundException e) { Printer.instance.print("错误:无法生成初始账户配置文件,存储路径不存在。"); } catch (IOException e2) { Printer.instance.print("错误:无法生成初始账户配置文件,写入失败。"); } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code private void createDefaultAccountPropertiesFile() { Printer.instance.print("正在生成初始账户配置文件(" + this.confdir + ACCOUNT_PROPERTIES_FILE + ")..."); final Properties dap = new Properties(); dap.setProperty(DEFAULT_ACCOUNT_ID + ".pwd", DEFAULT_ACCOUNT_PWD); dap.setProperty(DEFAULT_ACCOUNT_ID + ".auth", DEFAULT_ACCOUNT_AUTH); dap.setProperty("authOverall", DEFAULT_AUTH_OVERALL); try (FileOutputStream accountSettingOut = new FileOutputStream(this.confdir + ACCOUNT_PROPERTIES_FILE)) { FileLock lock = accountSettingOut.getChannel().lock(); dap.store(accountSettingOut, "<This is the default kiftd account setting file. >"); lock.release(); Printer.instance.print("初始账户配置文件生成完毕。"); } catch (FileNotFoundException e) { Printer.instance.print("错误:无法生成初始账户配置文件,存储路径不存在。"); } catch (IOException e2) { Printer.instance.print("错误:无法生成初始账户配置文件,写入失败。"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void doDownloadFile(final HttpServletRequest request, final HttpServletResponse response) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) { final String fileId = request.getParameter("fileId"); if (fileId != null) { final Node f = this.fm.queryById(fileId); if (f != null) { final String fileBlocks = ConfigureReader.instance().getFileBlockPath(); final File fo = this.fbu.getFileFromBlocks(fileBlocks, f.getFilePath()); try { final FileInputStream fis = new FileInputStream(fo); response.setContentType("application/force-download"); response.setHeader("Content-Length", "" + fo.length()); response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(f.getFileName(), "UTF-8")); final int buffersize = ConfigureReader.instance().getBuffSize(); final byte[] buffer = new byte[buffersize]; final BufferedInputStream bis = new BufferedInputStream(fis); final OutputStream os = (OutputStream) response.getOutputStream(); int index = 0; while ((index = bis.read(buffer)) != -1) { os.write(buffer, 0, index); } bis.close(); fis.close(); this.lu.writeDownloadFileEvent(request, f); } catch (Exception ex) { } } } } } #location 27 #vulnerability type RESOURCE_LEAK
#fixed code public void doDownloadFile(final HttpServletRequest request, final HttpServletResponse response) { final String account = (String) request.getSession().getAttribute("ACCOUNT"); if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) { final String fileId = request.getParameter("fileId"); if (fileId != null) { final Node f = this.fm.queryById(fileId); if (f != null) { final String fileBlocks = ConfigureReader.instance().getFileBlockPath(); final File fo = this.fbu.getFileFromBlocks(fileBlocks, f.getFilePath()); downloadRangeFile(request, response, fo, f.getFileName());// 使用断点续传执行下载 this.lu.writeDownloadFileEvent(request, f); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public File getFileFromBlocks(Node f) { // 检查该节点对应的文件块存放于哪个位置(主文件系统/扩展存储区) try { File file = null; if (f.getFilePath().startsWith("file_")) {// 存放于主文件系统中 // 直接从主文件系统的文件块存放区获得对应的文件块 file = getBlockFromExtendPath(new File(ConfigureReader.instance().getFileBlockPath()), f.getFilePath()); } else {// 存放于扩展存储区 short index = Short.parseShort(f.getFilePath().substring(0, f.getFilePath().indexOf('_'))); // 根据编号查到对应的扩展存储区路径,进而获取对应的文件块 file = getBlockFromExtendPath(ConfigureReader.instance().getExtendStores().parallelStream() .filter((e) -> e.getIndex() == index).findAny().get().getPath(), f.getFilePath()); } if (file.isFile()) { return file; } } catch (Exception e) { lu.writeException(e); Printer.instance.print("错误:文件数据读取失败。详细信息:" + e.getMessage()); } return null; } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code public File getFileFromBlocks(Node f) { // 检查该节点对应的文件块存放于哪个位置(主文件系统/扩展存储区) try { File file = null; if (f.getFilePath().startsWith("file_")) {// 存放于主文件系统中 // 直接从主文件系统的文件块存放区获得对应的文件块 file = new File(ConfigureReader.instance().getFileBlockPath(), f.getFilePath()); } else {// 存放于扩展存储区 short index = Short.parseShort(f.getFilePath().substring(0, f.getFilePath().indexOf('_'))); // 根据编号查到对应的扩展存储区路径,进而获取对应的文件块 file = new File(ConfigureReader.instance().getExtendStores().parallelStream() .filter((e) -> e.getIndex() == index).findAny().get().getPath(), f.getFilePath()); } if (file.isFile()) { return file; } } catch (Exception e) { lu.writeException(e); Printer.instance.print("错误:文件数据读取失败。详细信息:" + e.getMessage()); } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean addAll(Collection<? extends T> collection) { boolean success = true; for (T element : collection) { success &= internalAdd(element, false); } refreshStorage(true); return success; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean addAll(Collection<? extends T> collection) { boolean success = true; for (T element : collection) { success &= internalAdd(element); } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void clear() { Map<String, String> savedHash = nest.hgetAll(); for (Map.Entry<String, String> entry : savedHash.entrySet()) { V value = JOhm.get(valueClazz, Integer.parseInt(entry.getValue())); value.delete(); nest.hdel(entry.getKey()); } nest.del(); refreshStorage(true); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void clear() { Map<String, String> savedHash = nest.hgetAll(); for (Map.Entry<String, String> entry : savedHash.entrySet()) { nest.hdel(entry.getKey()); } nest.del(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean addAll(Collection<? extends T> c) { boolean success = true; for (T element : c) { success &= internalAdd(element, false); } refreshStorage(true); return success; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean addAll(Collection<? extends T> c) { boolean success = true; for (T element : c) { success &= internalAdd(element); } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void clear() { nest.del(); refreshStorage(true); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void clear() { nest.del(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean add(T e) { return internalAdd(e, true); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean add(T e) { return internalAdd(e); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int size() { int repoSize = nest.llen(); if (repoSize != elements.size()) { refreshStorage(true); } return repoSize; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public int size() { int repoSize = nest.llen(); return repoSize; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean internalRemove(T element) { boolean success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName()) .srem(JOhmUtils.getId(element).toString()) > 0; unindexValue(element); return success; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean internalRemove(T element) { boolean success = false; if (element != null) { success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName()) .srem(JOhmUtils.getId(element).toString()) > 0; unindexValue(element); } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean internalAdd(T element) { boolean success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName()) .sadd(JOhmUtils.getId(element).toString()) > 0; indexValue(element); return success; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean internalAdd(T element) { boolean success = false; if (element != null) { success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName()) .sadd(JOhmUtils.getId(element).toString()) > 0; indexValue(element); } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean addAll(int index, Collection<? extends T> c) { for (T element : c) { internalIndexedAdd(index++, element, false); } refreshStorage(true); return true; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean addAll(int index, Collection<? extends T> c) { for (T element : c) { internalIndexedAdd(index++, element); } return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public T set(int index, T element) { T previousElement = this.get(index); internalIndexedAdd(index, element, true); return previousElement; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public T set(int index, T element) { T previousElement = this.get(index); internalIndexedAdd(index, element); return previousElement; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int size() { int repoSize = nest.hlen(); if (repoSize != backingMap.size()) { refreshStorage(true); } return repoSize; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public int size() { int repoSize = nest.hlen(); return repoSize; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean internalRemove(T element) { boolean success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName()) .srem(JOhmUtils.getId(element).toString()) > 0; unindexValue(element); return success; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean internalRemove(T element) { boolean success = false; if (element != null) { success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName()) .srem(JOhmUtils.getId(element).toString()) > 0; unindexValue(element); } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void clear() { Map<String, String> savedHash = nest.hgetAll(); for (Map.Entry<String, String> entry : savedHash.entrySet()) { V value = JOhm.get(valueClazz, Integer.parseInt(entry.getValue())); value.delete(); nest.hdel(entry.getKey()); } nest.del(); refreshStorage(true); } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void clear() { Map<String, String> savedHash = nest.hgetAll(); for (Map.Entry<String, String> entry : savedHash.entrySet()) { nest.hdel(entry.getKey()); } nest.del(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressWarnings("unchecked") public boolean removeAll(Collection<?> c) { Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); boolean success = true; while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalRemove(element, false); } refreshStorage(true); return success; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override @SuppressWarnings("unchecked") public boolean removeAll(Collection<?> c) { Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); boolean success = true; while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalRemove(element); } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressWarnings("unchecked") public boolean retainAll(Collection<?> c) { this.clear(); Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); boolean success = true; while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalAdd(element, false); } refreshStorage(true); return success; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override @SuppressWarnings("unchecked") public boolean retainAll(Collection<?> c) { this.clear(); Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); boolean success = true; while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalAdd(element); } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public V remove(Object key) { V value = get(key); value.delete(); nest.hdel(key.toString()); return value; } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public V remove(Object key) { V value = get(key); nest.hdel(key.toString()); return value; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public T remove(int index) { return internalIndexedRemove(index, true); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public T remove(int index) { return internalIndexedRemove(index); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void shouldSetCollectionAutomatically() { User user = new User(); assertNotNull(user.getLikes()); assertTrue(user.getLikes().getClass().equals(RedisList.class)); assertTrue(user.getPurchases().getClass().equals(RedisSet.class)); assertTrue(user.getFavoritePurchases().getClass() .equals(RedisMap.class)); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void shouldSetCollectionAutomatically() { User user = new User(); assertNotNull(user.getLikes()); assertTrue(user.getLikes().getClass().equals(RedisList.class)); assertTrue(user.getPurchases().getClass().equals(RedisSet.class)); assertTrue(user.getFavoritePurchases().getClass() .equals(RedisMap.class)); assertTrue(user.getOrderedPurchases().getClass().equals( RedisSortedSet.class)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean remove(Object o) { return internalRemove(o, true); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean remove(Object o) { return internalRemove(o); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public V put(K key, V value) { V previousValue = get(key); internalPut(key, value, true); return previousValue; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public V put(K key, V value) { V previousValue = get(key); internalPut(key, value); return previousValue; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void internalIndexedAdd(int index, T element) { nest.cat(JOhmUtils.getId(owner)).cat(field.getName()).lset(index, JOhmUtils.getId(element).toString()); indexValue(element); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private void internalIndexedAdd(int index, T element) { if (element != null) { nest.cat(JOhmUtils.getId(owner)).cat(field.getName()).lset(index, JOhmUtils.getId(element).toString()); indexValue(element); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public V remove(Object key) { V value = get(key); value.delete(); nest.hdel(key.toString()); return value; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public V remove(Object key) { V value = get(key); nest.hdel(key.toString()); return value; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override public boolean retainAll(Collection<?> c) { this.clear(); Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); boolean success = true; while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalAdd(element, false); } refreshStorage(true); return success; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override public boolean retainAll(Collection<?> c) { this.clear(); Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); boolean success = true; while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalAdd(element); } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean internalRemove(T element) { Integer lrem = nest.cat(JOhmUtils.getId(owner)).cat(field.getName()) .lrem(1, JOhmUtils.getId(element).toString()); unindexValue(element); return lrem > 0; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean internalRemove(T element) { boolean success = false; if (element != null) { Integer lrem = nest.cat(JOhmUtils.getId(owner)) .cat(field.getName()).lrem(1, JOhmUtils.getId(element).toString()); unindexValue(element); success = lrem > 0; } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void clear() { nest.del(); elements.clear(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void clear() { nest.del(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean remove(Object o) { return internalRemove(o, true); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean remove(Object o) { return internalRemove(o); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean add(T element) { return internalAdd(element, true); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean add(T element) { return internalAdd(element); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void putAll(Map<? extends K, ? extends V> mapToCopyIn) { for (Map.Entry<? extends K, ? extends V> entry : mapToCopyIn.entrySet()) { internalPut(entry.getKey(), entry.getValue(), false); } refreshStorage(true); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void putAll(Map<? extends K, ? extends V> mapToCopyIn) { for (Map.Entry<? extends K, ? extends V> entry : mapToCopyIn.entrySet()) { internalPut(entry.getKey(), entry.getValue()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Override public boolean removeAll(Collection<?> c) { boolean success = true; Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalRemove(element, false); } refreshStorage(true); return success; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") @Override public boolean removeAll(Collection<?> c) { boolean success = true; Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalRemove(element); } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void checkModelSearch() { User user1 = new User(); user1.setName("model1"); user1.setRoom("tworoom"); user1.setAge(88); user1.setSalary(9999.99f); user1.setInitial('m'); JOhm.save(user1); int id1 = user1.getId(); User user2 = new User(); user2.setName("zmodel2"); user2.setRoom("threeroom"); user2.setAge(8); user2.setInitial('z'); user2 = JOhm.save(user2); int id2 = user2.getId(); assertNotNull(JOhm.get(User.class, id1)); assertNotNull(JOhm.get(User.class, id2)); List<User> users = JOhm.find(User.class, "age", 88); assertEquals(1, users.size()); User user1Found = users.get(0); assertEquals(user1Found.getAge(), user1.getAge()); assertEquals(user1Found.getName(), user1.getName()); assertNull(user1Found.getRoom()); assertEquals(user1Found.getSalary(), user1.getSalary(), 0D); assertEquals(user1Found.getInitial(), user1.getInitial()); users = JOhm.find(User.class, "age", 8); assertEquals(1, users.size()); User user2Found = users.get(0); assertEquals(user2Found.getAge(), user2.getAge()); assertEquals(user2Found.getName(), user2.getName()); assertNull(user2Found.getRoom()); assertEquals(user2Found.getSalary(), user2.getSalary(), 0D); assertEquals(user2Found.getInitial(), user2.getInitial()); users = JOhm.find(User.class, "name", "model1"); assertEquals(1, users.size()); User user3Found = users.get(0); assertEquals(user3Found.getAge(), user1.getAge()); assertEquals(user3Found.getName(), user1.getName()); assertNull(user3Found.getRoom()); assertEquals(user3Found.getSalary(), user1.getSalary(), 0D); assertEquals(user3Found.getInitial(), user1.getInitial()); users = JOhm.find(User.class, "name", "zmodel2"); assertEquals(1, users.size()); User user4Found = users.get(0); assertEquals(user4Found.getAge(), user2.getAge()); assertEquals(user4Found.getName(), user2.getName()); assertNull(user4Found.getRoom()); assertEquals(user4Found.getSalary(), user2.getSalary(), 0D); assertEquals(user4Found.getInitial(), user2.getInitial()); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void checkModelSearch() { User user1 = new User(); user1.setName("model1"); user1.setRoom("tworoom"); user1.setAge(88); user1.setSalary(9999.99f); user1.setInitial('m'); JOhm.save(user1); Long id1 = user1.getId(); User user2 = new User(); user2.setName("zmodel2"); user2.setRoom("threeroom"); user2.setAge(8); user2.setInitial('z'); user2 = JOhm.save(user2); Long id2 = user2.getId(); assertNotNull(JOhm.get(User.class, id1)); assertNotNull(JOhm.get(User.class, id2)); List<User> users = JOhm.find(User.class, "age", 88); assertEquals(1, users.size()); User user1Found = users.get(0); assertEquals(user1Found.getAge(), user1.getAge()); assertEquals(user1Found.getName(), user1.getName()); assertNull(user1Found.getRoom()); assertEquals(user1Found.getSalary(), user1.getSalary(), 0D); assertEquals(user1Found.getInitial(), user1.getInitial()); users = JOhm.find(User.class, "age", 8); assertEquals(1, users.size()); User user2Found = users.get(0); assertEquals(user2Found.getAge(), user2.getAge()); assertEquals(user2Found.getName(), user2.getName()); assertNull(user2Found.getRoom()); assertEquals(user2Found.getSalary(), user2.getSalary(), 0D); assertEquals(user2Found.getInitial(), user2.getInitial()); users = JOhm.find(User.class, "name", "model1"); assertEquals(1, users.size()); User user3Found = users.get(0); assertEquals(user3Found.getAge(), user1.getAge()); assertEquals(user3Found.getName(), user1.getName()); assertNull(user3Found.getRoom()); assertEquals(user3Found.getSalary(), user1.getSalary(), 0D); assertEquals(user3Found.getInitial(), user1.getInitial()); users = JOhm.find(User.class, "name", "zmodel2"); assertEquals(1, users.size()); User user4Found = users.get(0); assertEquals(user4Found.getAge(), user2.getAge()); assertEquals(user4Found.getName(), user2.getName()); assertNull(user4Found.getRoom()); assertEquals(user4Found.getSalary(), user2.getSalary(), 0D); assertEquals(user4Found.getInitial(), user2.getInitial()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int size() { int repoSize = nest.smembers().size(); if (repoSize != elements.size()) { refreshStorage(true); } return repoSize; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public int size() { int repoSize = nest.smembers().size(); return repoSize; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @SuppressWarnings("unchecked") public boolean retainAll(Collection<?> c) { this.clear(); Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); boolean success = true; while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalAdd(element, false); } refreshStorage(true); return success; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override @SuppressWarnings("unchecked") public boolean retainAll(Collection<?> c) { this.clear(); Iterator<? extends Model> iterator = (Iterator<? extends Model>) c .iterator(); boolean success = true; while (iterator.hasNext()) { T element = (T) iterator.next(); success &= internalAdd(element); } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void add(int index, T element) { internalIndexedAdd(index, element, true); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void add(int index, T element) { internalIndexedAdd(index, element); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean internalAdd(T element) { boolean success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName()) .rpush(JOhmUtils.getId(element).toString()) > 0; indexValue(element); return success; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean internalAdd(T element) { boolean success = false; if (element != null) { success = nest.cat(JOhmUtils.getId(owner)).cat(field.getName()) .rpush(JOhmUtils.getId(element).toString()) > 0; indexValue(element); } return success; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void cannotSearchAfterDeletingIndexes() { User user = new User(); user.setAge(88); JOhm.save(user); user.setAge(77); // younger JOhm.save(user); user.setAge(66); // younger still JOhm.save(user); int id = user.getId(); assertNotNull(JOhm.get(User.class, id)); List<User> users = JOhm.find(User.class, "age", 88); assertEquals(0, users.size()); // index already updated users = JOhm.find(User.class, "age", 77); assertEquals(0, users.size()); // index already updated users = JOhm.find(User.class, "age", 66); assertEquals(1, users.size()); JOhm.delete(User.class, id); users = JOhm.find(User.class, "age", 88); assertEquals(0, users.size()); users = JOhm.find(User.class, "age", 77); assertEquals(0, users.size()); users = JOhm.find(User.class, "age", 66); assertEquals(0, users.size()); assertNull(JOhm.get(User.class, id)); } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void cannotSearchAfterDeletingIndexes() { User user = new User(); user.setAge(88); JOhm.save(user); user.setAge(77); // younger JOhm.save(user); user.setAge(66); // younger still JOhm.save(user); Long id = user.getId(); assertNotNull(JOhm.get(User.class, id)); List<User> users = JOhm.find(User.class, "age", 88); assertEquals(0, users.size()); // index already updated users = JOhm.find(User.class, "age", 77); assertEquals(0, users.size()); // index already updated users = JOhm.find(User.class, "age", 66); assertEquals(1, users.size()); JOhm.delete(User.class, id); users = JOhm.find(User.class, "age", 88); assertEquals(0, users.size()); users = JOhm.find(User.class, "age", 77); assertEquals(0, users.size()); users = JOhm.find(User.class, "age", 66); assertEquals(0, users.size()); assertNull(JOhm.get(User.class, id)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean hasNext() { return currentIteratorHasNext() || possibleChunksRemaining(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean hasNext() { if(currentIteratorHasNext()) { return true; } loadNextChunkIterator(); return currentIteratorHasNext(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void close() { if (isClosed()) return; try { sock.close(); din = null; dout = null; sock = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public FetchResponse fetch(RequestMeta meta) { if (riak == null) throw new IllegalStateException("Cannot fetch an object without a RiakClient"); FetchResponse r = riak.fetch(bucket, key, meta); if (r.isSuccess()) { this.copyData(r.getObject()); } return r; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public FetchResponse fetch(RequestMeta meta) { if (riak == null) throw new IllegalStateException("Cannot fetch an object without a RiakClient"); FetchResponse r = riak.fetch(bucket, key, meta); if (r.getObject() != null) { RiakObject other = r.getObject(); shallowCopy(other); r.setObject(this); } return r; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code RiakConnection getConnection() throws IOException { RiakConnection c = connections.get(); if (c == null || !c.endIdleAndCheckValid()) { c = new RiakConnection(addr, port); if (this.clientID != null) { setClientID(clientID); } } else { // we're fine! // } connections.set(null); return c; } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code RiakConnection getConnection() throws IOException { return getConnection(true); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RawFetchResponse fetch(String bucket, String key) { return fetch(bucket, key, null); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public RawFetchResponse fetch(String bucket, String key) { return doFetch(bucket, key, null, false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void receive_code(int code) throws IOException, RiakError { int len = din.readInt(); int get_code = din.read(); if (code == RiakClient.MSG_ErrorResp) { RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(din); throw new RiakError(err); } if (len != 1 || code != get_code) { throw new IOException("bad message code"); } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean findNext() throws IOException { if (currentPartStream != null && !currentPartStream.done()) { InputStream is = new OneTokenInputStream(stream, boundary); try { while (is.read() != -1) { /* nop */} } catch (IOException e) { throw new RuntimeException(e); } } if (stream.peek() != -1) { currentPartStream = new OneTokenInputStream(stream.branch(), boundary); return true; } return false; } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code private boolean findNext() throws IOException { if (currentPartStream != null) { InputStream is = currentPartStream.branch(); try { while (is.read() != -1) { /* nop */} // advance stream to end of next boundary finishReadingLine(stream); // and consume the rest of the boundary line including the newline } catch (IOException e) { throw new RuntimeException(e); } } if (stream.peek() != -1) { currentPartStream = new BranchableInputStream(new OneTokenInputStream(stream.branch(), boundary)); return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code byte[] receive(int code) throws IOException { int len = din.readInt(); int get_code = din.read(); byte[] data = null; if (len > 1) { data = new byte[len - 1]; din.readFully(data); } if (get_code == RiakClient.MSG_ErrorResp) { RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(data); throw new RiakError(err); } if (code != get_code) { throw new IOException("bad message code. Expected: " + code + " actual: " + get_code); } return data; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public WriteBucket enableForSearch() { httpOnly(client.getTransport(), Constants.FL_SCHEMA_SEARCH); builder.addPrecommitHook(NamedErlangFunction.SEARCH_PRECOMMIT_HOOK).search(true); return this; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public WriteBucket enableForSearch() { httpOnly(client.getTransport(), Constants.FL_SCHEMA_SEARCH); addPrecommitHook(NamedErlangFunction.SEARCH_PRECOMMIT_HOOK); builder.search(true); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void close() { if (isClosed()) return; try { sock.close(); din = null; dout = null; sock = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void readPlainTextValuesWithCoverageContextContinuouslyWithReturnBody() throws ExecutionException, InterruptedException, UnknownHostException { final Map<String, RiakObject> results = performFBReadWithCoverageContext(true, true); assertEquals(NUMBER_OF_TEST_VALUES, results.size()); for (int i=0; i<NUMBER_OF_TEST_VALUES; ++i) { final String key = "k"+i; assertTrue(results.containsKey(key)); final RiakObject ro = results.get(key); assertNotNull(ro); assertEquals("plain/text", ro.getContentType()); assertFalse(ro.isDeleted()); assertEquals("v"+i, ro.getValue().toStringUtf8()); } } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void readPlainTextValuesWithCoverageContextContinuouslyWithReturnBody() throws ExecutionException, InterruptedException, UnknownHostException { final Map<String, RiakObject> results = performFBReadWithCoverageContext(true, true, false); assertEquals(NUMBER_OF_TEST_VALUES, results.size()); verifyResults(results, true); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void testListBucketsStreaming(Namespace namespace) throws InterruptedException, ExecutionException { ListBuckets listBucketsCommand = new ListBuckets.Builder(namespace.getBucketType()).build(); final RiakFuture<ListBuckets.StreamingResponse, BinaryValue> streamingFuture = client.executeAsyncStreaming(listBucketsCommand, 500); Iterator<Namespace> iterator = streamingFuture.get().iterator(); assumeTrue(iterator.hasNext()); boolean found = false; while (iterator.hasNext()) { final Namespace next = iterator.next(); found = next.getBucketName().toString().equals(bucketName); } streamingFuture.await(); // Wait for command to finish, even if we've found our data assumeTrue(streamingFuture.isDone()); assertFalse(streamingFuture.get().iterator().hasNext()); assertEquals(namespace.getBucketType(), streamingFuture.getQueryInfo()); assertTrue(found); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code private void testListBucketsStreaming(Namespace namespace) throws InterruptedException, ExecutionException { ListBuckets listBucketsCommand = new ListBuckets.Builder(namespace.getBucketType()).build(); final RiakFuture<ListBuckets.StreamingResponse, BinaryValue> streamingFuture = client.executeAsyncStreaming(listBucketsCommand, 500); final ListBuckets.StreamingResponse streamResponse = streamingFuture.get(); final Iterator<Namespace> iterator = streamResponse.iterator(); assumeTrue(iterator.hasNext()); boolean found = false; for (Namespace ns : streamResponse) { if(!found) { found = ns.getBucketName().toString().equals(bucketName); } } streamingFuture.await(); // Wait for command to finish, even if we've found our data assumeTrue(streamingFuture.isDone()); assertFalse(iterator.hasNext()); assertEquals(namespace.getBucketType(), streamingFuture.getQueryInfo()); assertTrue(found); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Bucket execute() throws RiakRetryFailedException { final BucketProperties propsToStore = builder.build(); retrier.attempt(new Callable<Void>() { public Void call() throws Exception { client.updateBucket(name, propsToStore); return null; } }); BucketProperties properties = retrier.attempt(new Callable<BucketProperties>() { public BucketProperties call() throws Exception { return client.fetchBucket(name); } }); return new DefaultBucket(name, properties, client, retrier); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Bucket execute() throws RiakRetryFailedException { final BucketProperties propsToStore = builder.precommitHooks(precommitHooks).postcommitHooks(postcommitHooks).build(); retrier.attempt(new Callable<Void>() { public Void call() throws Exception { client.updateBucket(name, propsToStore); return null; } }); BucketProperties properties = retrier.attempt(new Callable<BucketProperties>() { public BucketProperties call() throws Exception { return client.fetchBucket(name); } }); return new DefaultBucket(name, properties, client, retrier); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void setClientID(ByteString id) throws IOException { if(id.size() > Constants.RIAK_CLIENT_ID_LENGTH) { id = ByteString.copyFrom(id.toByteArray(), 0, Constants.RIAK_CLIENT_ID_LENGTH); } RpbSetClientIdReq req = RPB.RpbSetClientIdReq.newBuilder().setClientId( id).build(); RiakConnection c = getConnection(false); try { c.send(MSG_SetClientIdReq, req); c.receive_code(MSG_SetClientIdResp); } finally { release(c); } this.clientID = id; } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code public void setClientID(ByteString id) throws IOException { if(id.size() > Constants.RIAK_CLIENT_ID_LENGTH) { id = ByteString.copyFrom(id.toByteArray(), 0, Constants.RIAK_CLIENT_ID_LENGTH); } this.clientId = id.toByteArray(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected SecondaryIndexQueryOperation.Response convert(List<Object> rawResponse) { SecondaryIndexQueryOperation.Response.Builder responseBuilder = new SecondaryIndexQueryOperation.Response.Builder(); for (Object o : rawResponse) { if (o instanceof RiakKvPB.RpbIndexBodyResp) { assert pbReq.getReturnBody(); final RiakKvPB.RpbIndexBodyResp bodyResp = (RiakKvPB.RpbIndexBodyResp)o; convertBodies(responseBuilder, bodyResp); if (bodyResp.hasContinuation()) { responseBuilder.withContinuation( BinaryValue.unsafeCreate(bodyResp.getContinuation().toByteArray())); } continue; } final RiakKvPB.RpbIndexResp pbEntry = (RiakKvPB.RpbIndexResp) o; /** * The 2i API is inconsistent on the Riak side. If it's not * a range query, return_terms is ignored it only returns the * list of object keys and you have to have * preserved the index key if you want to return it to the user * with the results. * * Also, the $key index queries just ignore return_terms altogether. */ if (pbReq.getReturnTerms() && !query.indexName.toString().equalsIgnoreCase(IndexNames.KEY)) { convertTerms(responseBuilder, pbEntry); } else { convertKeys(responseBuilder, pbEntry); } if (pbEntry.hasContinuation()) { responseBuilder.withContinuation( BinaryValue.unsafeCreate(pbEntry.getContinuation().toByteArray())); } } return responseBuilder.build(); } #location 35 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected SecondaryIndexQueryOperation.Response convert(List<Object> rawResponse) { SecondaryIndexQueryOperation.Response.Builder responseBuilder = new SecondaryIndexQueryOperation.Response.Builder(); final boolean isIndexBodyResp = rawResponse != null && !rawResponse.isEmpty() && objectIsIndexBodyResp(rawResponse.get(0)); for (Object o : rawResponse) { convertSingleResponse(responseBuilder, isIndexBodyResp, o); } return responseBuilder.build(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void close() { if (isClosed()) return; try { sock.close(); din = null; dout = null; sock = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public WriteBucket addPrecommitHook(NamedFunction preCommitHook) { httpOnly(client.getTransport(), Constants.FL_SCHEMA_PRECOMMIT); builder.addPrecommitHook(preCommitHook); return this; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public WriteBucket addPrecommitHook(NamedFunction preCommitHook) { httpOnly(client.getTransport(), Constants.FL_SCHEMA_PRECOMMIT); if(preCommitHook != null) { if(precommitHooks == null) { precommitHooks = new ArrayList<NamedFunction>(); } precommitHooks.add(preCommitHook); } return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void send(int code) throws IOException { dout.writeInt(1); dout.write(code); dout.flush(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code RiakConnection getConnection(boolean setClientId) throws IOException { RiakConnection c = connections.get(); if (c == null || !c.endIdleAndCheckValid()) { c = new RiakConnection(addr, port, bufferSizeKb); if (this.clientID != null && setClientId) { connections.set(c); setClientID(clientID); } } connections.set(null); return c; } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code RiakConnection getConnection() throws IOException { RiakConnection c = pool.getConnection(clientId); return c; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void warmUp() throws IOException { if (permits.tryAcquire(initialSize)) { for (int i = 0; i < this.initialSize; i++) { RiakConnection c = new RiakConnection(this.host, this.port, this.bufferSizeKb, this, TimeUnit.MILLISECONDS.convert(connectionWaitTimeoutNanos, TimeUnit.NANOSECONDS), requestTimeoutMillis); c.beginIdle(); available.add(c); } } else { throw new RuntimeException("Unable to create initial connections"); } } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code private void warmUp() throws IOException { for (int i = 0; i < this.initialSize; i++) { RiakConnection c = getConnection(); c.beginIdle(); available.add(c); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void close() { if (isClosed()) return; try { sock.close(); din = null; dout = null; sock = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void send(int code, MessageLite req) throws IOException { int len = req.getSerializedSize(); dout.writeInt(len + 1); dout.write(code); req.writeTo(dout); dout.flush(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getClientID() throws IOException { RiakConnection c = getConnection(); try { c.send(MSG_GetClientIdReq); byte[] data = c.receive(MSG_GetClientIdResp); if (data == null) return null; RpbGetClientIdResp res = RPB.RpbGetClientIdResp.parseFrom(data); clientID = res.getClientId(); return clientID.toStringUtf8(); } finally { release(c); } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code public String getClientID() throws IOException { RiakConnection c = getConnection(); try { c.send(MSG_GetClientIdReq); byte[] data = c.receive(MSG_GetClientIdResp); if (data == null) return null; RpbGetClientIdResp res = RPB.RpbGetClientIdResp.parseFrom(data); clientId = res.getClientId().toByteArray(); return CharsetUtils.asUTF8String(clientId); } finally { release(c); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public WriteBucket disableSearch() { httpOnly(client.getTransport(), Constants.FL_SCHEMA_SEARCH); if (existingPrecommitHooks != null) { synchronized (existingPrecommitHooks) { existingPrecommitHooks.remove(NamedErlangFunction.SEARCH_PRECOMMIT_HOOK); for (NamedFunction f : existingPrecommitHooks) { builder.addPrecommitHook(f); } } } builder.search(false); return this; } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public WriteBucket disableSearch() { httpOnly(client.getTransport(), Constants.FL_SCHEMA_SEARCH); if (precommitHooks != null) { precommitHooks.remove(NamedErlangFunction.SEARCH_PRECOMMIT_HOOK); } builder.search(false); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testInterruptedExceptionDealtWith() throws InterruptedException { final boolean[] caught = {false}; final InterruptedException[] ie = {null}; int timeout = 1000; Thread t = new Thread(() -> { try { @SuppressWarnings("unchecked") TransferQueue<FakeResponse> fakeQueue = (TransferQueue<FakeResponse>) mock(TransferQueue.class); when(fakeQueue.poll(timeout, TimeUnit.MILLISECONDS)).thenThrow(new InterruptedException( "foo")); @SuppressWarnings("unchecked") PBStreamingFutureOperation<FakeResponse, Void, Void> coreFuture = (PBStreamingFutureOperation<FakeResponse, Void, Void>) mock( PBStreamingFutureOperation.class); when(coreFuture.getResultsQueue()).thenReturn(fakeQueue); // ChunkedResponseIterator polls the response queue when created, // so we'll use that to simulate a Thread interrupt. new ChunkedResponseIterator<>(coreFuture, timeout, Long::new, FakeResponse::iterator); } catch (RuntimeException ex) { caught[0] = true; ie[0] = (InterruptedException) ex.getCause(); } catch (InterruptedException e) { // Mocking TransferQueue::poll(timeout) requires this CheckedException be dealt with // If we actually catch one here we've failed at our jobs. caught[0] = false; } assertTrue(Thread.currentThread().isInterrupted()); }); t.start(); t.join(); assertTrue(caught[0]); assertEquals("foo", ie[0].getMessage()); } #location 50 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testInterruptedExceptionDealtWith() throws InterruptedException { final Throwable[] ex = {null}; int timeout = 1000; Thread testThread = new Thread(() -> { try { @SuppressWarnings("unchecked") TransferQueue<FakeResponse> fakeQueue = (TransferQueue<FakeResponse>) mock(TransferQueue.class); when(fakeQueue.poll(timeout, TimeUnit.MILLISECONDS)).thenThrow(new InterruptedException("foo")); @SuppressWarnings("unchecked") PBStreamingFutureOperation<FakeResponse, Void, Void> coreFuture = (PBStreamingFutureOperation<FakeResponse, Void, Void>) mock(PBStreamingFutureOperation.class); when(coreFuture.getResultsQueue()).thenReturn(fakeQueue); // ChunkedResponseIterator polls the response queue when created, // so we'll use that to simulate a Thread interrupt. new ChunkedResponseIterator<>(coreFuture, timeout, Long::new, FakeResponse::iterator); } catch (RuntimeException rex) { ex[0] = rex; } catch (InterruptedException e) { // Mocking TransferQueue::poll(timeout) requires this CheckedException be dealt with // If we actually catch one here we've failed at our jobs. fail(e.getMessage()); } assertTrue(Thread.currentThread().isInterrupted()); }); testThread.start(); testThread.join(); Throwable caughtException = ex[0]; assertNotNull(caughtException); Throwable wrappedException = caughtException.getCause(); assertNotNull(caughtException.getMessage(), wrappedException); assertEquals("foo", wrappedException.getMessage()); assertTrue(wrappedException instanceof InterruptedException); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RawFetchResponse fetch(String bucket, String key) { return fetch(bucket, key, null); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public RawFetchResponse fetch(String bucket, String key) { return fetch(bucket, key, null, false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void extract() throws IOException { log.debug("Extract content of '{}' to '{}'", source, destination); // delete destination file if exists removeDirectory(destination); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { try { File file = new File(destination, zipEntry.getName()); // create intermediary directories - sometimes zip don't add them File dir = new File(file.getParent()); dir.mkdirs(); if (zipEntry.isDirectory()) { file.mkdirs(); } else { byte[] buffer = new byte[1024]; int length = 0; FileOutputStream fos = new FileOutputStream(file); while ((length = zipInputStream.read(buffer)) >= 0) { fos.write(buffer, 0, length); } fos.close(); } } catch (FileNotFoundException e) { log.error("File '{}' not found", zipEntry.getName()); } } zipInputStream.close(); } #location 27 #vulnerability type RESOURCE_LEAK
#fixed code public void extract() throws IOException { log.debug("Extract content of '{}' to '{}'", source, destination); // delete destination file if exists if (destination.exists() && destination.isDirectory()) { FileUtils.delete(destination.toPath()); } try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source))) { ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { try { File file = new File(destination, zipEntry.getName()); // create intermediary directories - sometimes zip don't add them File dir = new File(file.getParent()); dir.mkdirs(); if (zipEntry.isDirectory()) { file.mkdirs(); } else { byte[] buffer = new byte[1024]; int length; try (FileOutputStream fos = new FileOutputStream(file)) { while ((length = zipInputStream.read(buffer)) >= 0) { fos.write(buffer, 0, length); } } } } catch (FileNotFoundException e) { log.error("File '{}' not found", zipEntry.getName()); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Map<String, Set<String>> readIndexFiles() { // checking cache if (entries != null) { return entries; } entries = new HashMap<String, Set<String>>(); List<PluginWrapper> startedPlugins = pluginManager.getStartedPlugins(); for (PluginWrapper plugin : startedPlugins) { String pluginId = plugin.getDescriptor().getPluginId(); log.debug("Reading extensions index file for plugin '{}'", pluginId); Set<String> entriesPerPlugin = new HashSet<String>(); try { URL url = plugin.getPluginClassLoader().getResource(ExtensionsIndexer.EXTENSIONS_RESOURCE); log.debug("Read '{}'", url.getFile()); Reader reader = new InputStreamReader(url.openStream(), "UTF-8"); ExtensionsIndexer.readIndex(reader, entriesPerPlugin); if (entriesPerPlugin.isEmpty()) { log.debug("No extensions found"); } else { log.debug("Found possible {} extensions:", entriesPerPlugin.size()); for (String entry : entriesPerPlugin) { log.debug(" " + entry); } } entries.put(pluginId, entriesPerPlugin); } catch (IOException e) { log.error(e.getMessage(), e); } } return entries; } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code private Map<String, Set<String>> readIndexFiles() { // checking cache if (entries != null) { return entries; } entries = new HashMap<String, Set<String>>(); List<PluginWrapper> plugins = pluginManager.getPlugins(); for (PluginWrapper plugin : plugins) { String pluginId = plugin.getDescriptor().getPluginId(); log.debug("Reading extensions index file for plugin '{}'", pluginId); Set<String> entriesPerPlugin = new HashSet<String>(); try { URL url = plugin.getPluginClassLoader().getResource(ExtensionsIndexer.EXTENSIONS_RESOURCE); log.debug("Read '{}'", url.getFile()); Reader reader = new InputStreamReader(url.openStream(), "UTF-8"); ExtensionsIndexer.readIndex(reader, entriesPerPlugin); if (entriesPerPlugin.isEmpty()) { log.debug("No extensions found"); } else { log.debug("Found possible {} extensions:", entriesPerPlugin.size()); for (String entry : entriesPerPlugin) { log.debug(" " + entry); } } entries.put(pluginId, entriesPerPlugin); } catch (IOException e) { log.error(e.getMessage(), e); } } return entries; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void createDisabledFile() throws IOException { File file = testFolder.newFile("disabled.txt"); try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"))) { writer.write("plugin-2\r\n"); } file.createNewFile(); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code private void createDisabledFile() throws IOException { List<String> plugins = new ArrayList<>(); plugins.add("plugin-2"); writeLines(plugins, "disabled.txt"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void resolveDependencies() { DependencyResolver dependencyResolver = new DependencyResolver(unresolvedPlugins); resolvedPlugins = dependencyResolver.getSortedDependencies(); for (Plugin plugin : resolvedPlugins) { unresolvedPlugins.remove(plugin); uberClassLoader.addLoader(plugin.getWrapper().getPluginClassLoader()); } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private void resolveDependencies() throws PluginException { DependencyResolver dependencyResolver = new DependencyResolver(unresolvedPlugins); resolvedPlugins = dependencyResolver.getSortedPlugins(); for (PluginWrapper pluginWrapper : resolvedPlugins) { unresolvedPlugins.remove(pluginWrapper); uberClassLoader.addLoader(pluginWrapper.getPluginClassLoader()); LOG.info("Plugin '" + pluginWrapper.getDescriptor().getPluginId() + "' resolved"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void extract() throws IOException { log.debug("Extract content of '{}' to '{}'", source, destination); // delete destination file if exists removeDirectory(destination); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source)); ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { try { File file = new File(destination, zipEntry.getName()); // create intermediary directories - sometimes zip don't add them File dir = new File(file.getParent()); dir.mkdirs(); if (zipEntry.isDirectory()) { file.mkdirs(); } else { byte[] buffer = new byte[1024]; int length = 0; FileOutputStream fos = new FileOutputStream(file); while ((length = zipInputStream.read(buffer)) >= 0) { fos.write(buffer, 0, length); } fos.close(); } } catch (FileNotFoundException e) { log.error("File '{}' not found", zipEntry.getName()); } } zipInputStream.close(); } #location 27 #vulnerability type RESOURCE_LEAK
#fixed code public void extract() throws IOException { log.debug("Extract content of '{}' to '{}'", source, destination); // delete destination file if exists if (destination.exists() && destination.isDirectory()) { FileUtils.delete(destination.toPath()); } try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(source))) { ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { try { File file = new File(destination, zipEntry.getName()); // create intermediary directories - sometimes zip don't add them File dir = new File(file.getParent()); dir.mkdirs(); if (zipEntry.isDirectory()) { file.mkdirs(); } else { byte[] buffer = new byte[1024]; int length; try (FileOutputStream fos = new FileOutputStream(file)) { while ((length = zipInputStream.read(buffer)) >= 0) { fos.write(buffer, 0, length); } } } } catch (FileNotFoundException e) { log.error("File '{}' not found", zipEntry.getName()); } } } }
Below is the vulnerable code, please generate the patch based on the following information.