Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
18
19
content
stringlengths
177
10.5k
max_stars_repo_path
stringlengths
39
40
vul4j_data_VUL4J-65
static public File allocateFile(File dir, String name) { int q = name.indexOf('?'); if (q > 0) { name = name.substring(0, q); } File file = new File(dir, name); int dot = name.indexOf('.'); String prefix = dot < 0 ? name : name.substring(0, dot); String suffix = dot < 0 ? "" : name.substring(dot); int index = 2; while (file.exists()) { file = new File(dir, prefix + "-" + index++ + suffix); } file.getParentFile().mkdirs(); return file; } static public File allocateFile(File dir, String name) { int q = name.indexOf('?'); name = q > 0? name.substring(0, q):name; int dot = name.indexOf('.'); String prefix; String suffix; if(dot >= 0){ prefix = name.substring(0, dot); suffix = name.substring(dot); }else{ prefix = name; suffix = ""; } File file = new File(dir, name); if (!file.toPath().normalize().startsWith(dir.toPath().normalize())) { throw new IllegalArgumentException("Zip archives with files escaping their root directory are not allowed."); } for(int index = 2;file.exists();index++){ file = new File(dir, prefix + "-" + index + suffix); } File parentFile = file.getParentFile(); parentFile.mkdirs(); return file; }
./VJBench/llm-vul/VJBench-trans/VUL4J-65
vul4j_data_VUL4J-73
public boolean isPasswordValid(String encPass, String rawPass, Object salt) { String pass1 = encPass + ""; String pass2 = mergePasswordAndSalt(rawPass, salt, false); if (ignorePasswordCase) { pass1 = pass1.toLowerCase(Locale.ENGLISH); pass2 = pass2.toLowerCase(Locale.ENGLISH); } return PasswordEncoderUtils.equals(pass1, pass2); } public boolean isPasswordValid(String encPass, String rawPass, Object salt) { if (encPass == null) { return false; } String pass2 = mergePasswordAndSalt(rawPass, salt, false); String pass1 = encPass + ""; pass1 = ignorePasswordCase? pass1.toLowerCase(Locale.ENGLISH): pass1; pass2 = ignorePasswordCase? pass2.toLowerCase(Locale.ENGLISH): pass2; return PasswordEncoderUtils.equals(pass1, pass2); }
./VJBench/llm-vul/VJBench-trans/VUL4J-73
vul4j_data_VUL4J-4
protected Object doGetDocument(Exchange exchange, Object body) throws Exception { if (body == null) { return null; } Object answer = null; Class<?> type = getDocumentType(); Exception cause = null; if (type != null) { try { answer = exchange.getContext().getTypeConverter().convertTo(type, exchange, body); } catch (Exception e) { cause = e; } } if (answer == null) { if (body instanceof WrappedFile) { InputStream is = exchange.getContext().getTypeConverter().convertTo(InputStream.class, exchange, body); answer = new InputSource(is); } else if (body instanceof BeanInvocation) { BeanInvocation bi = exchange.getContext().getTypeConverter().convertTo(BeanInvocation.class, exchange, body); if (bi.getArgs() != null && bi.getArgs().length == 1 && bi.getArgs()[0] == null) { answer = null; } } else if (body instanceof String) { answer = new InputSource(new StringReader((String) body)); } } if (type == null && answer == null) { answer = body; } else if (answer == null) { if (cause != null) { throw cause; } else { throw new NoTypeConversionAvailableException(body, type); } } return answer; } // import TypeConverter protected Object doGetDocument(Exchange exchange, Object body) throws Exception { if (body != null) { Class<?> type = getDocumentType(); Exception cause = null; Object answer = null; if (type != null) { try { CamelContext context = exchange.getContext(); TypeConverter typeConverter = context.getTypeConverter(); answer = typeConverter.convertTo(type, exchange, body); } catch (Exception e) { cause = e; } } if (type != null || answer != null) { if (answer == null) { if (cause == null) { throw new NoTypeConversionAvailableException(body, type); } else { throw cause; } } }else{ answer = body; } return answer; } return null; }
./VJBench/llm-vul/VJBench-trans/VUL4J-4
vul4j_data_VUL4J-53
void setTo(Calendar c, int i) { c.set(field,i-offset); } void setTo(Calendar c, int i) { int n = Math.min(i-offset, c.getActualMaximum(field)); c.set(field, n); }
./VJBench/llm-vul/VJBench-trans/VUL4J-53
vul4j_data_VUL4J-43
public static void writeEntry(ZipFile zipFile, ZipEntry entry, File destDir) throws IOException { File outFile = new File(destDir, entry.getName()); if (entry.isDirectory()) { outFile.mkdirs(); } else { outFile.getParentFile().mkdirs(); try (InputStream in = zipFile.getInputStream(entry)) { IOUtil.writeStream(in, outFile); } } } public static void writeEntry(ZipFile zipFile, ZipEntry entry, File destDir) throws IOException { String entryName = entry.getName(); File outFile = new File(destDir,entryName); if (! outFile.getCanonicalFile().toPath().startsWith(destDir.toPath())) { throw new IOException("Zip entry outside destination directory: " + entry.getName()); } if (!entry.isDirectory()) { File parentFile = outFile.getParentFile(); parentFile.mkdirs(); try (InputStream in = zipFile.getInputStream(entry)) { IOUtil.writeStream(in, outFile); } } else { outFile.mkdirs(); } }
./VJBench/llm-vul/VJBench-trans/VUL4J-43
vul4j_data_VUL4J-61
private Stream<MapResult> xmlXpathToMapResult(@Name("url") String url, boolean simpleMode, String path, Map<String, Object> config) throws Exception { if (config == null) config = Collections.emptyMap(); boolean failOnError = (boolean) config.getOrDefault("failOnError", true); List<MapResult> result = new ArrayList<>(); try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setIgnoringElementContentWhitespace(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); FileUtils.checkReadAllowed(url); Map<String, Object> headers = (Map) config.getOrDefault( "headers", Collections.emptyMap() ); Document doc = documentBuilder.parse(Util.openInputStream(url, headers, null)); XPathFactory xPathFactory = XPathFactory.newInstance(); XPath xPath = xPathFactory.newXPath(); path = StringUtils.isEmpty(path) ? "/" : path; XPathExpression xPathExpression = xPath.compile(path); NodeList nodeList = (NodeList) xPathExpression.evaluate(doc, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); i++) { final Deque<Map<String, Object>> stack = new LinkedList<>(); handleNode(stack, nodeList.item(i), simpleMode); for (int index = 0; index < stack.size(); index++) { result.add(new MapResult(stack.pollFirst())); } } } catch (FileNotFoundException e){ if(!failOnError) return Stream.of(new MapResult(Collections.emptyMap())); else throw new FileNotFoundException(e.getMessage()); } catch (Exception e){ if(!failOnError) return Stream.of(new MapResult(Collections.emptyMap())); else throw new Exception(e); } return result.stream(); } private Stream<MapResult> xmlXpathToMapResult(@Name("url") String url, boolean simpleMode, String path, Map<String, Object> config) throws Exception { config = config == null? Collections.emptyMap():config; boolean failOnError = (boolean) config.getOrDefault("failOnError", true); List<MapResult> result = new ArrayList<>(); try { FileUtils.checkReadAllowed(url); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); XPathFactory xPathFactory = XPathFactory.newInstance(); documentBuilderFactory.setIgnoringElementContentWhitespace(true); documentBuilderFactory.setNamespaceAware(true); if(StringUtils.isEmpty(path) ){ path = "/" ; } XPathExpression xPathExpression = xPathFactory.newXPath().compile(path); documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); InputStream inputStream = Util.openInputStream(url, (Map) config.getOrDefault( "headers", Collections.emptyMap() ) , null); Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream); NodeList nodeList = (NodeList) xPathExpression.evaluate(doc, XPathConstants.NODESET); int i = 0; while ( i < nodeList.getLength()) { final Deque<Map<String, Object>> stack = new LinkedList<>(); handleNode(stack, nodeList.item(i), simpleMode); int index = 0; while ( index < stack.size()) { result.add(new MapResult(stack.pollFirst())); index++; } i++; } } catch (FileNotFoundException e){ if(failOnError){ String message = e.getMessage(); throw new FileNotFoundException(message); }else{ Map<String, Object> emptyMap =Collections.emptyMap(); MapResult mapResult = new MapResult(emptyMap); return Stream.of(mapResult); } } catch (Exception e){ if(failOnError){ throw new Exception(e); }else{ Map<String, Object> emptyMap =Collections.emptyMap(); MapResult mapResult = new MapResult(emptyMap); return Stream.of(mapResult); } } return result.stream(); }
./VJBench/llm-vul/VJBench-trans/VUL4J-61
vul4j_data_VUL4J-8
@Override public ByteBuffer encode(final String name) { final CharsetEncoder enc = newEncoder(); final CharBuffer cb = CharBuffer.wrap(name); CharBuffer tmp = null; ByteBuffer out = ByteBuffer.allocate(estimateInitialBufferSize(enc, cb.remaining())); while (cb.remaining() > 0) { final CoderResult res = enc.encode(cb, out, false); if (res.isUnmappable() || res.isMalformed()) { int spaceForSurrogate = estimateIncrementalEncodingSize(enc, 6 * res.length()); if (spaceForSurrogate > out.remaining()) { int charCount = 0; for (int i = cb.position() ; i < cb.limit(); i++) { charCount += !enc.canEncode(cb.get(i)) ? 6 : 1; } int totalExtraSpace = estimateIncrementalEncodingSize(enc, charCount); out = ZipEncodingHelper.growBufferBy(out, totalExtraSpace - out.remaining()); } if (tmp == null) { tmp = CharBuffer.allocate(6); } for (int i = 0; i < res.length(); ++i) { out = encodeFully(enc, encodeSurrogate(tmp, cb.get()), out); } } else if (res.isOverflow()) { int increment = estimateIncrementalEncodingSize(enc, cb.remaining()); out = ZipEncodingHelper.growBufferBy(out, increment); } } enc.encode(cb, out, true); out.limit(out.position()); out.rewind(); return out; } @Override public ByteBuffer encode(final String name) { final CharBuffer cb = CharBuffer.wrap(name); int initial_cbr = cb.remaining(); final CharsetEncoder enc = newEncoder(); int size = estimateInitialBufferSize(enc, initial_cbr); ByteBuffer out = ByteBuffer.allocate(size); CharBuffer tmp = null; while (cb.remaining() > 0) { final CoderResult res = enc.encode(cb, out, false); if (!res.isUnmappable() && !res.isMalformed()) { if (res.isOverflow()) { int cbr = cb.remaining(); out = ZipEncodingHelper.growBufferBy(out, estimateIncrementalEncodingSize(enc, cbr)); } else if (res.isUnderflow() || res.isError()) { break; } }else{ int l = 6 * res.length(); int spaceForSurrogate = estimateIncrementalEncodingSize(enc,l ); if (spaceForSurrogate > out.remaining()) { int charCount = 0; int i = cb.position() ; while ( i < cb.limit() ) { if(enc.canEncode(cb.get(i))){ charCount +=1; }else{ charCount +=6; } i++; } int outRemaining = out.remaining(); out = ZipEncodingHelper.growBufferBy(out, estimateIncrementalEncodingSize(enc, charCount) - outRemaining); } tmp = tmp == null? CharBuffer.allocate(6):tmp; int i = 0; while ( i < res.length()) { CharBuffer charBuffer = encodeSurrogate(tmp, cb.get()); out = encodeFully(enc, charBuffer , out); ++i; } } } enc.encode(cb, out, true); out.limit(out.position()); out.rewind(); return out; }
./VJBench/llm-vul/VJBench-trans/VUL4J-8
vul4j_data_VUL4J-66
protected static boolean isValid(String str) { if (str == null || str.length() == 0) return false; for (int i = 0; i < str.length(); i++) { switch (str.charAt(i)) { case '/': case '\\': case '?': case ':': case '<': case '>': case ';': case '(': case ')': case '@': case ',': case '[': case ']': case '=': return false; default: break; } } return true; } protected static boolean isValid(String str) { if (str != null && str.length() != 0){ int i =0; while(i < str.length()) { char c = str.charAt(i); i++; if (c == '\n' ||c == '/'|| c=='\\' || c == '?' || c == ':' || c== '<' || c == '>' || c == ';' || c== '(' || c== ')' || c =='@' || c == ',' || c == '[' || c == ']' || c == '='){ return false; } } return true; } return false; }
./VJBench/llm-vul/VJBench-trans/VUL4J-66
vul4j_data_VUL4J-26
public String getUrlRegex() { if (StringUtils.isNotEmpty(urlRegexExpression)) { return (String) parse(urlRegexExpression, String.class); } else if (StringUtils.isNotEmpty(urlRegex)) { return urlRegex; } else { return "^(https?|ftp):\\/\\/" + "(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+" + "(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+)?" + "@)?(#?" + ")((([a-z0-9]\\.|[a-z0-9][a-z0-9-]*[a-z0-9]\\.)*" + "[a-z][a-z0-9-]*[a-z0-9]" + "|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}" + "(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])" + ")(:\\d+)?" + ")(((\\/+([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)*" + "(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)" + "?)?)?" + "(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?" + "$"; } } public String getUrlRegex() { if (!StringUtils.isNotEmpty(urlRegexExpression)) { if (!StringUtils.isNotEmpty(urlRegex)) { return "^(https?|ftp):\\/\\/" + "(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+" + "(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+)?" + "@)?(#?" + ")((([a-z0-9]\\.|[a-z0-9][a-z0-9-]*[a-z0-9]\\.)*" + "[a-z][a-z0-9-]*[a-z0-9]" + "|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}" + "(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])" + ")(:\\d+)?" + ")(((\\/{0,1}([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)*" + "(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)" + "?)?)?" + "(#([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?" + "$"; } else { return urlRegex; } }else{ return (String) parse(urlRegexExpression, String.class); } }
./VJBench/llm-vul/VJBench-trans/VUL4J-26
vul4j_data_VUL4J-40
public boolean isAllowed(HttpServletRequest request) throws IOException { String requestBody = IOUtils.toString(request.getReader()); ScimUser scimUserFromRequest = JsonUtils.readValue(requestBody, ScimUser.class); String id = UaaUrlUtils.extractPathVariableFromUrl(USER_ID_PATH_PARAMETER_INDEX, UaaUrlUtils.getRequestPath(request)); String zoneId = IdentityZoneHolder.get().getId(); ScimUser scimUserFromDb; try { scimUserFromDb = scimUserProvisioning.retrieve(id, zoneId); } catch (ScimResourceNotFoundException e) { return true; } if (!scimUserFromDb.getPrimaryEmail().equals(scimUserFromRequest.getPrimaryEmail())) { return false; } if (!scimUserFromDb.getUserName().equals(scimUserFromRequest.getUserName())) { return false; } if (scimUserFromDb.isVerified() != scimUserFromRequest.isVerified()) { return false; } if (scimUserFromDb.isActive() != (scimUserFromRequest.isActive())) { return false; } if (!scimUserFromDb.getOrigin().equals(scimUserFromRequest.getOrigin())) { return false; } return true; } public boolean isAllowed(HttpServletRequest request) throws IOException { BufferedReader reader = request.getReader(); ScimUser scimUserFromRequest = JsonUtils.readValue(IOUtils.toString(reader), ScimUser.class); String pathInfo = UaaUrlUtils.getRequestPath(request); IdentityZone zone = IdentityZoneHolder.get(); ScimUser scimUserFromDb; try { scimUserFromDb = scimUserProvisioning.retrieve( UaaUrlUtils.extractPathVariableFromUrl(USER_ID_PATH_PARAMETER_INDEX, pathInfo), zone.getId()); } catch (ScimResourceNotFoundException e) { return true; } String dbEmail = scimUserFromDb.getPrimaryEmail(); String requestEmail = scimUserFromRequest.getPrimaryEmail(); if (dbEmail.equals(requestEmail)) { String dbUserName = scimUserFromDb.getUserName(); String requestUserName = scimUserFromRequest.getUserName(); if (!scimUserFromDb.getEmails().containsAll(scimUserFromRequest.getEmails())) { return false; } if (dbUserName.equals(requestUserName)) { if (scimUserFromDb.isVerified() == scimUserFromRequest.isVerified()) { if (scimUserFromDb.isActive() == (scimUserFromRequest.isActive())) { String dbOrigin = scimUserFromDb.getOrigin(); String requestOrigin = scimUserFromRequest.getOrigin(); if (dbOrigin.equals(requestOrigin)) { return true; }else{ return false; } }else{ return false; } }else{ return false; } }else{ return false; } }else{ return false; } }
./VJBench/llm-vul/VJBench-trans/VUL4J-40
vul4j_data_VUL4J-6
public void parseCentralDirectoryFormat(final byte[] data, final int offset, final int length) { this.format = ZipShort.getValue(data, offset); this.algId = EncryptionAlgorithm.getAlgorithmByCode(ZipShort.getValue(data, offset + 2)); this.bitlen = ZipShort.getValue(data, offset + 4); this.flags = ZipShort.getValue(data, offset + 6); this.rcount = ZipLong.getValue(data, offset + 8); if (rcount > 0) { this.hashAlg = HashAlgorithm.getAlgorithmByCode(ZipShort.getValue(data, offset + 12)); this.hashSize = ZipShort.getValue(data, offset + 14); for (int i = 0; i < this.rcount; i++) { for (int j = 0; j < this.hashSize; j++) { } } } } public void parseCentralDirectoryFormat(final byte[] data, final int offset, final int length) { this.rcount = ZipLong.getValue(data, offset + 8); this.flags = ZipShort.getValue(data, offset + 6); this.format = ZipShort.getValue(data, offset); this.bitlen = ZipShort.getValue(data, offset + 4); int zv2 = ZipShort.getValue(data, offset + 2); this.algId = EncryptionAlgorithm.getAlgorithmByCode(zv2); if (rcount <= 0) { return; } this.hashSize = ZipShort.getValue(data, offset + 14); int zv12 = ZipShort.getValue(data, offset + 12); this.hashAlg = HashAlgorithm.getAlgorithmByCode(zv12); }
./VJBench/llm-vul/VJBench-trans/VUL4J-6
vul4j_data_VUL4J-23
@Override public String encodeForJSString(String source) { return source == null ? null : Encode.forJavaScriptSource(source); } @Override public String encodeForJSString(String dataProvider) { if( dataProvider != null ){ return Encode.forJavaScript(source).replace("\\-", "\\u002D"); } return null; }
./VJBench/llm-vul/VJBench-trans/VUL4J-23
vul4j_data_VUL4J-50
private void writeSession(SessionInformations session, boolean displayUser) throws IOException { final String nextColumnAlignRight = "</td><td align='right'>"; final String nextColumnAlignCenter = "</td><td align='center'>"; write("<td><a href='?part=sessions&amp;sessionId="); write(htmlEncodeButNotSpace(session.getId())); write("'>"); write(htmlEncodeButNotSpace(session.getId())); write("</a>"); write(nextColumnAlignRight); write(durationFormat.format(session.getLastAccess())); write(nextColumnAlignRight); write(durationFormat.format(session.getAge())); write(nextColumnAlignRight); write(expiryFormat.format(session.getExpirationDate())); write(nextColumnAlignRight); write(integerFormat.format(session.getAttributeCount())); write(nextColumnAlignCenter); if (session.isSerializable()) { write("#oui#"); } else { write("<span class='severe'>#non#</span>"); } write(nextColumnAlignRight); write(integerFormat.format(session.getSerializedSize())); final String nextColumn = "</td><td>"; write(nextColumn); final String remoteAddr = session.getRemoteAddr(); if (remoteAddr == null) { write("&nbsp;"); } else { write(remoteAddr); } write(nextColumnAlignCenter); writeCountry(session); if (displayUser) { write(nextColumn); final String remoteUser = session.getRemoteUser(); if (remoteUser == null) { write("&nbsp;"); } else { writeDirectly(htmlEncodeButNotSpace(remoteUser)); } } write("</td><td align='center' class='noPrint'>"); write(A_HREF_PART_SESSIONS); write("&amp;action=invalidate_session&amp;sessionId="); write(urlEncode(session.getId())); write("' onclick=\"javascript:return confirm('" + getStringForJavascript("confirm_invalidate_session") + "');\">"); write("<img width='16' height='16' src='?resource=user-trash.png' alt='#invalidate_session#' title='#invalidate_session#' />"); write("</a>"); write("</td>"); } private void writeSession(SessionInformations session, boolean displayUser) throws IOException { final String sessionId = session.getId(); final String remoteAddr = session.getRemoteAddr(); write("<td><a href='?part=sessions&amp;sessionId="); String sessionIdHtmlEncode=htmlEncodeButNotSpace(sessionId); write(sessionIdHtmlEncode); write("'>"); write(sessionIdHtmlEncode); write("</a>"); final String nextColumnAlignRight = "</td><td align='right'>"; write(nextColumnAlignRight); String lastAccess = durationFormat.format(session.getLastAccess()); String age = durationFormat.format(session.getAge()); String exprDate = expiryFormat.format(session.getExpirationDate()); String attrCount = integerFormat.format(session.getAttributeCount()); String serializedSize = integerFormat.format(session.getSerializedSize()); write(lastAccess); write(nextColumnAlignRight); write(age); write(nextColumnAlignRight); write(exprDate); write(nextColumnAlignRight); write(attrCount); final String nextColumnAlignCenter = "</td><td align='center'>"; final String nextColumn = "</td><td>"; write(nextColumnAlignCenter); String s1 = !session.isSerializable()? "<span class='severe'>#non#</span>": "#oui#"; write(s1); write(nextColumnAlignRight); write(serializedSize); write(nextColumn); if (remoteAddr == null) { write("&nbsp;"); } else { writeDirectly(htmlEncodeButNotSpace(remoteAddr)); } write(nextColumnAlignCenter); writeCountry(session); final String remoteUser = session.getRemoteUser(); if (displayUser) { write(nextColumn); if (remoteUser != null) { String remoteUserhtmlEncode = htmlEncodeButNotSpace(remoteUser); writeDirectly(remoteUserhtmlEncode); } else { write("&nbsp;"); } } String sessionIdeEncoded =urlEncode(sessionId); write("</td><td align='center' class='noPrint'>"); write("<a href='?part=sessions"); write("&amp;action=invalidate_session&amp;sessionId="); write(sessionIdeEncoded); String str_from_js = getStringForJavascript("confirm_invalidate_session"); write("' onclick=\"javascript:return confirm('" + str_from_js + "');\">"); write("<img width='16' height='16' src='?resource=user-trash.png' alt='#invalidate_session#' title='#invalidate_session#' />"); write("</a>"); write("</td>"); }
./VJBench/llm-vul/VJBench-trans/VUL4J-50
vul4j_data_VUL4J-44
public String encodeCharacter( char[] immune, Character c ) { String cStr = String.valueOf(c.charValue()); byte[] bytes; StringBuilder sb; if(UNENCODED_SET.contains(c)) return cStr; bytes = toUtf8Bytes(cStr); sb = new StringBuilder(bytes.length * 3); for(byte b : bytes) appendTwoUpperHex(sb.append('%'), b); return sb.toString(); } public String encodeCharacter( char[] immune, Character c ) { char charValue = c.charValue(); String cStr = String.valueOf(charValue); if ( immune != null && containsCharacter( c.charValue(), immune ) ) return cStr; if(!UNENCODED_SET.contains(c)){ byte[] bytes = toUtf8Bytes(cStr); StringBuilder sb = new StringBuilder(bytes.length * 3); int i =0; while(i<bytes.length){ sb.append('%'); appendTwoUpperHex(sb, bytes[i]); i++; } return sb.toString(); } return cStr; }
./VJBench/llm-vul/VJBench-trans/VUL4J-44
vul4j_data_VUL4J-20
public float[] toFloatArray() { float[] retval = new float[size()]; for (int i = 0; i < size(); i++) { retval[i] = ((COSNumber)getObject( i )).floatValue(); } return retval; } public float[] toFloatArray() { int size = size(); float[] retval = new float[size]; int i = 0; while( i < size ) { COSBase base = getObject(i); retval[i] = base instanceof COSNumber ? ((COSNumber) base).floatValue() : 0; i++; } return retval; }
./VJBench/llm-vul/VJBench-trans/VUL4J-20
vul4j_data_VUL4J-30
public void validate(Object object) throws ValidationException { String fieldName = getFieldName(); Object value = this.getFieldValue(fieldName, object); if (value == null || value.toString().length() == 0) { return; } if (!(value.getClass().equals(String.class)) || !Pattern.compile(getUrlRegex(), Pattern.CASE_INSENSITIVE).matcher(String.valueOf(value)).matches()) { addFieldError(fieldName, object); } } public void validate(Object object) throws ValidationException { String fieldName = getFieldName(); Object value = this.getFieldValue(fieldName, object); if (value != null && value.toString().length() != 0) { Class value_class = value.getClass(); String urlRegex = getUrlRegex(); Pattern p = Pattern.compile(urlRegex, Pattern.CASE_INSENSITIVE); String s = String.valueOf(value).trim(); Matcher m = p.matcher(s); if (value_class.equals(String.class) && m.matches()) { return; } addFieldError(fieldName, object); } }
./VJBench/llm-vul/VJBench-trans/VUL4J-30
vul4j_data_VUL4J-39
@Override public String toString() { StringBuilder sb = new StringBuilder(); if (origin != null) { sb.append("remoteAddress=").append(origin); } if (clientId != null) { if (sb.length() > 0) { sb.append(", "); } sb.append("clientId=").append(clientId); } if (sessionId != null) { if (sb.length() > 0) { sb.append(", "); } sb.append("sessionId=").append(sessionId); } return sb.toString(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb= origin != null? sb.append("remoteAddress=").append(origin):sb; if (clientId != null) { sb =sb.length() > 0?sb.append(", "):sb; sb.append("clientId="); sb.append(clientId); } return sb.toString(); }
./VJBench/llm-vul/VJBench-trans/VUL4J-39
vul4j_data_VUL4J-12
private int extend(int v, final int t) { int vt = (1 << (t - 1)); while (v < vt) { vt = (-1 << t) + 1; v += vt; } return v; } private int extend(int v, final int t) { int vt = (1 << (t - 1)); if (v < vt) { vt = (-1 << t) + 1; v += vt; } return v; }
./VJBench/llm-vul/VJBench-trans/VUL4J-12
vul4j_data_VUL4J-19
@Override public void prepareForDecryption(PDEncryption encryption, COSArray documentIDArray, DecryptionMaterial decryptionMaterial) throws IOException { if(!(decryptionMaterial instanceof StandardDecryptionMaterial)) { throw new IOException("Decryption material is not compatible with the document"); } setDecryptMetadata(encryption.isEncryptMetaData()); StandardDecryptionMaterial material = (StandardDecryptionMaterial)decryptionMaterial; String password = material.getPassword(); if(password == null) { password = ""; } int dicPermissions = encryption.getPermissions(); int dicRevision = encryption.getRevision(); int dicLength = encryption.getVersion() == 1 ? 5 : encryption.getLength() / 8; byte[] documentIDBytes = getDocumentIDBytes(documentIDArray); boolean encryptMetadata = encryption.isEncryptMetaData(); byte[] userKey = encryption.getUserKey(); byte[] ownerKey = encryption.getOwnerKey(); byte[] ue = null, oe = null; Charset passwordCharset = Charsets.ISO_8859_1; if (dicRevision == 6 || dicRevision == 5) { passwordCharset = Charsets.UTF_8; ue = encryption.getUserEncryptionKey(); oe = encryption.getOwnerEncryptionKey(); } AccessPermission currentAccessPermission; if( isOwnerPassword(password.getBytes(passwordCharset), userKey, ownerKey, dicPermissions, documentIDBytes, dicRevision, dicLength, encryptMetadata) ) { currentAccessPermission = AccessPermission.getOwnerAccessPermission(); setCurrentAccessPermission(currentAccessPermission); byte[] computedPassword; if (dicRevision == 6 || dicRevision == 5) { computedPassword = password.getBytes(passwordCharset); } else { computedPassword = getUserPassword(password.getBytes(passwordCharset), ownerKey, dicRevision, dicLength ); } encryptionKey = computeEncryptedKey( computedPassword, ownerKey, userKey, oe, ue, dicPermissions, documentIDBytes, dicRevision, dicLength, encryptMetadata, true ); } else if( isUserPassword(password.getBytes(passwordCharset), userKey, ownerKey, dicPermissions, documentIDBytes, dicRevision, dicLength, encryptMetadata) ) { currentAccessPermission = new AccessPermission(dicPermissions); setCurrentAccessPermission(currentAccessPermission); encryptionKey = computeEncryptedKey( password.getBytes(passwordCharset), ownerKey, userKey, oe, ue, dicPermissions, documentIDBytes, dicRevision, dicLength, encryptMetadata, false ); } else { throw new InvalidPasswordException("Cannot decrypt PDF, the password is incorrect"); } if (dicRevision == 6 || dicRevision == 5) { validatePerms(encryption, dicPermissions, encryptMetadata); } if (encryption.getVersion() == 4 || encryption.getVersion() == 5) { PDCryptFilterDictionary stdCryptFilterDictionary = encryption.getStdCryptFilterDictionary(); if (stdCryptFilterDictionary != null) { COSName cryptFilterMethod = stdCryptFilterDictionary.getCryptFilterMethod(); setAES(COSName.AESV2.equals(cryptFilterMethod) || COSName.AESV3.equals(cryptFilterMethod)); } } } public void prepareForDecryption(PDEncryption encryption, COSArray documentIDArray, DecryptionMaterial decryptionMaterial) throws IOException { if((decryptionMaterial instanceof StandardDecryptionMaterial)) { byte[] userKey = encryption.getUserKey(); byte[] ownerKey = encryption.getOwnerKey(); StandardDecryptionMaterial material = (StandardDecryptionMaterial)decryptionMaterial; String password = material.getPassword(); boolean encryptMetadata = encryption.isEncryptMetaData(); setDecryptMetadata(encryptMetadata); if(password == null){ password = ""; } int dicLength = 0; if(encryption.getVersion() != 1 ){ dicLength = encryption.getLength() / 8; }else{ dicLength = 5; } byte[] documentIDBytes = getDocumentIDBytes(documentIDArray); int dicPermissions = encryption.getPermissions(); int dicRevision = encryption.getRevision(); byte[] ue = null; byte[] oe = null; Charset passwordCharset = Charsets.ISO_8859_1; if (dicRevision == 6 || dicRevision == 5) { passwordCharset = Charsets.UTF_8; ue = encryption.getUserEncryptionKey(); oe = encryption.getOwnerEncryptionKey(); } byte[] passwordByteArray = password.getBytes(passwordCharset); if( !isOwnerPassword(passwordByteArray, userKey, ownerKey, dicPermissions, documentIDBytes, dicRevision, dicLength, encryptMetadata) ) { if( !isUserPassword(passwordByteArray, userKey, ownerKey, dicPermissions, documentIDBytes, dicRevision, dicLength, encryptMetadata) ) { throw new InvalidPasswordException("Cannot decrypt PDF, the password is incorrect"); } else { AccessPermission currentAccessPermission = new AccessPermission(dicPermissions); currentAccessPermission.setReadOnly(); setCurrentAccessPermission(currentAccessPermission); encryptionKey = computeEncryptedKey( passwordByteArray, ownerKey, userKey, oe, ue, dicPermissions,documentIDBytes, dicRevision,dicLength, encryptMetadata, false ); } }else{ setCurrentAccessPermission(AccessPermission.getOwnerAccessPermission()); byte[] computedPassword; if ( dicRevision != 6 && dicRevision != 5) { computedPassword = getUserPassword(passwordByteArray, ownerKey, dicRevision, dicLength ); } else { computedPassword = passwordByteArray; } encryptionKey = computeEncryptedKey(computedPassword, ownerKey, userKey, oe, ue, dicPermissions, documentIDBytes, dicRevision,dicLength, encryptMetadata, true ); } if (dicRevision == 6 || dicRevision == 5) { validatePerms(encryption, dicPermissions, encryptMetadata); } if (encryption.getVersion() != 4 && encryption.getVersion() != 5) { return; }else{ PDCryptFilterDictionary stdCryptFilterDictionary = encryption.getStdCryptFilterDictionary(); if (stdCryptFilterDictionary == null) { return; } COSName cryptFilterMethod = stdCryptFilterDictionary.getCryptFilterMethod(); boolean aesv2 = COSName.AESV2.equals(cryptFilterMethod); boolean aesv3 = COSName.AESV3.equals(cryptFilterMethod); setAES( aesv2 || aesv3 ); } }else{ throw new IOException("Decryption material is not compatible with the document"); } }
./VJBench/llm-vul/VJBench-trans/VUL4J-19
vul4j_data_VUL4J-57
@SuppressWarnings({"unchecked", "rawtypes"}) @Override public boolean start() throws Exception { String job = step.getJob(); Item item = Jenkins.getActiveInstance().getItem(job, invokingRun.getParent(), Item.class); if (item == null) { throw new AbortException("No item named " + job + " found"); } if (step.getWait() && !(item instanceof Job)) { throw new AbortException("Waiting for non-job items is not supported"); } if (item instanceof ParameterizedJobMixIn.ParameterizedJob) { final ParameterizedJobMixIn.ParameterizedJob project = (ParameterizedJobMixIn.ParameterizedJob) item; listener.getLogger().println("Scheduling project: " + ModelHyperlinkNote.encodeTo(project)); node.addAction(new LabelAction(Messages.BuildTriggerStepExecution_building_(project.getFullDisplayName()))); List<Action> actions = new ArrayList<>(); if (step.getWait()) { StepContext context = getContext(); actions.add(new BuildTriggerAction(context, step.isPropagate())); LOGGER.log(Level.FINER, "scheduling a build of {0} from {1}", new Object[]{project, context}); } actions.add(new CauseAction(new Cause.UpstreamCause(invokingRun))); List<ParameterValue> parameters = step.getParameters(); if (parameters != null) { parameters = completeDefaultParameters(parameters, (Job) project); actions.add(new ParametersAction(parameters)); } Integer quietPeriod = step.getQuietPeriod(); if (quietPeriod == null) { quietPeriod = project.getQuietPeriod(); } QueueTaskFuture<?> f = new ParameterizedJobMixIn() { @Override protected Job asJob() { return (Job) project; } }.scheduleBuild2(quietPeriod, actions.toArray(new Action[actions.size()])); if (f == null) { throw new AbortException("Failed to trigger build of " + project.getFullName()); } } else if (item instanceof Queue.Task){ if (step.getParameters() != null && !step.getParameters().isEmpty()) { throw new AbortException("Item type does not support parameters"); } Queue.Task task = (Queue.Task) item; listener.getLogger().println("Scheduling item: " + ModelHyperlinkNote.encodeTo(item)); node.addAction(new LabelAction(Messages.BuildTriggerStepExecution_building_(task.getFullDisplayName()))); List<Action> actions = new ArrayList<>(); if (step.getWait()) { StepContext context = getContext(); actions.add(new BuildTriggerAction(context, step.isPropagate())); LOGGER.log(Level.FINER, "scheduling a build of {0} from {1}", new Object[]{task, context}); } actions.add(new CauseAction(new Cause.UpstreamCause(invokingRun))); Integer quietPeriod = step.getQuietPeriod(); if (quietPeriod == null) { try { Method getQuietPeriod = task.getClass().getMethod("getQuietPeriod"); if (getQuietPeriod.getReturnType().equals(int.class)) { quietPeriod = (Integer) getQuietPeriod.invoke(task); } } catch (NoSuchMethodException e) { } catch (IllegalAccessError | IllegalArgumentException | InvocationTargetException e) { LOGGER.log(Level.WARNING, "Could not determine quiet period of " + item.getFullName(), e); } } if (quietPeriod == null) { quietPeriod = Jenkins.getActiveInstance().getQuietPeriod(); } ScheduleResult scheduleResult = Jenkins.getActiveInstance().getQueue().schedule2(task, quietPeriod,actions); if (scheduleResult.isRefused()) { throw new AbortException("Failed to trigger build of " + item.getFullName()); } } else { throw new AbortException("The item named " + job + " is a " + (item instanceof Describable ? ((Describable) item).getDescriptor().getDisplayName() : item.getClass().getName()) + " which is not something that can be built"); } if (step.getWait()) { return false; } else { getContext().onSuccess(null); return true; } } @SuppressWarnings({"unchecked", "rawtypes"}) @Override public boolean start() throws Exception { String job = step.getJob(); Item item = Jenkins.getActiveInstance().getItem(job, invokingRun.getParent(), Item.class); if (item != null) { item.checkPermission(Item.BUILD); if ( !step.getWait() || (item instanceof Job)) { if(!(item instanceof ParameterizedJobMixIn.ParameterizedJob)){ if(!(item instanceof Queue.Task)){ String s; if(item instanceof Describable){ s = ((Describable) item).getDescriptor().getDisplayName(); }else{ s = item.getClass().getName(); } throw new AbortException("The item named " + job + " is a " + s + " which is not something that can be built"); }else{ if (step.getParameters() == null || step.getParameters().isEmpty()) { Queue.Task task = (Queue.Task) item; String itemEncoded = ModelHyperlinkNote.encodeTo(item); listener.getLogger().println("Scheduling item: " +itemEncoded ); String taskName = task.getFullDisplayName(); String name = Messages.BuildTriggerStepExecution_building_(taskName); LabelAction labelAction = new LabelAction(name); node.addAction(labelAction); List<Action> actions = new ArrayList<>(); if (step.getWait()) { StepContext context = getContext(); boolean isPropagate = step.isPropagate(); actions.add(new BuildTriggerAction(context, isPropagate )); LOGGER.log(Level.FINER, "scheduling a build of {0} from {1}", new Object[]{task, context}); } Cause.UpstreamCause cause = new Cause.UpstreamCause(invokingRun); CauseAction causeAction = new CauseAction(cause); actions.add( causeAction); Integer quietPeriod = step.getQuietPeriod(); if (quietPeriod == null) { try { Class taskClass = task.getClass(); Method getQuietPeriod = taskClass.getMethod("getQuietPeriod"); Class returnType = getQuietPeriod.getReturnType(); if (returnType.equals(int.class)) { quietPeriod = (Integer) getQuietPeriod.invoke(task); } } catch (NoSuchMethodException e) { } catch (IllegalAccessError | IllegalArgumentException | InvocationTargetException e) { LOGGER.log(Level.WARNING, "Could not determine quiet period of " + item.getFullName(), e); } } quietPeriod = quietPeriod == null? Jenkins.getActiveInstance().getQuietPeriod():quietPeriod; Jenkins activeInstance = Jenkins.getActiveInstance(); ScheduleResult scheduleResult = activeInstance.getQueue().schedule2(task, quietPeriod,actions); if (scheduleResult.isRefused()) { throw new AbortException("Failed to trigger build of " + item.getFullName()); } }else{ throw new AbortException("Item type does not support parameters"); } } }else{ final ParameterizedJobMixIn.ParameterizedJob project = (ParameterizedJobMixIn.ParameterizedJob) item; listener.getLogger().println("Scheduling project: " + ModelHyperlinkNote.encodeTo(project)); node.addAction(new LabelAction(Messages.BuildTriggerStepExecution_building_(project.getFullDisplayName()))); List<Action> actions = new ArrayList<>(); if (step.getWait()) { StepContext context = getContext(); boolean isPropagate = step.isPropagate(); actions.add(new BuildTriggerAction(context,isPropagate )); LOGGER.log(Level.FINER, "scheduling a build of {0} from {1}", new Object[]{project, context}); } Cause.UpstreamCause cause = new Cause.UpstreamCause(invokingRun); CauseAction causeAction = new CauseAction(cause); actions.add(causeAction); List<ParameterValue> parameters = step.getParameters(); if (parameters != null) { parameters = completeDefaultParameters(parameters, (Job) project); actions.add(new ParametersAction(parameters)); } Integer quietPeriod = step.getQuietPeriod(); if (quietPeriod == null) { quietPeriod = project.getQuietPeriod(); } QueueTaskFuture<?> f = new ParameterizedJobMixIn() { @Override protected Job asJob() { return (Job) project; } }.scheduleBuild2(quietPeriod, actions.toArray(new Action[actions.size()])); if (f == null) { throw new AbortException("Failed to trigger build of " + project.getFullName()); } } if (!step.getWait()) { getContext().onSuccess(null); return true; } else { return false; } }else{ throw new AbortException("Waiting for non-job items is not supported"); } }else{ throw new AbortException("No item named " + job + " found"); } }
./VJBench/llm-vul/VJBench-trans/VUL4J-57
vul4j_data_VUL4J-25
@Override @Nonnull public String getValidHref(final String url) { if (StringUtils.isNotEmpty(url)) { try { String unescapedURL = URLDecoder.decode(url, StandardCharsets.UTF_8.name()); unescapedURL = StringEscapeUtils.unescapeXml(unescapedURL); String encodedUrl = unescapedURL.replaceAll("\"", "%22") .replaceAll("'", "%27") .replaceAll(">", "%3E") .replaceAll("<", "%3C") .replaceAll("`", "%60") .replaceAll(" ", "%20"); int qMarkIx = encodedUrl.indexOf('?'); if (qMarkIx > 0) { encodedUrl = encodedUrl.substring(0, qMarkIx) + encodedUrl.substring(qMarkIx).replaceAll(":", "%3A"); } encodedUrl = mangleNamespaces(encodedUrl); if (xssFilter.isValidHref(encodedUrl)) { return encodedUrl; } } catch (UnsupportedEncodingException e) { LOGGER.error("Unable to decode url: {}.", url); } } return ""; } @Override @Nonnull public String getValidHref(final String url) { if (!StringUtils.isNotEmpty(url)) { return ""; } String encodedUrl = url.replaceAll("\"", "%22") .replaceAll("'", "%27") .replaceAll(">", "%3E") .replaceAll("<", "%3C") .replaceAll("`", "%60") .replaceAll(" ", "%20"); int qMarkIx = encodedUrl.indexOf('?'); if (qMarkIx > 0) { encodedUrl = encodedUrl.substring(0, qMarkIx) + encodedUrl.substring(qMarkIx).replaceAll(":", "%3A"); } encodedUrl = mangleNamespaces(encodedUrl); if (xssFilter.isValidHref(encodedUrl)) { return encodedUrl; } return ""; }
./VJBench/llm-vul/VJBench-trans/VUL4J-25
vul4j_data_VUL4J-74
public SecureRandom getObject() throws Exception { SecureRandom rnd = SecureRandom.getInstance(algorithm); if (seed != null) { byte[] seedBytes = FileCopyUtils.copyToByteArray(seed.getInputStream()); rnd.setSeed(seedBytes); } else { rnd.nextBytes(new byte[1]); } return rnd; } public SecureRandom getObject() throws Exception { SecureRandom rnd = SecureRandom.getInstance(algorithm); rnd.nextBytes(new byte[1]); if (seed !=null) { InputStream inputStream = seed.getInputStream(); rnd.setSeed(FileCopyUtils.copyToByteArray(inputStream)); } return rnd; }
./VJBench/llm-vul/VJBench-trans/VUL4J-74
vul4j_data_VUL4J-46
protected XmlFactory(ObjectCodec oc, int xpFeatures, int xgFeatures, XMLInputFactory xmlIn, XMLOutputFactory xmlOut, String nameForTextElem) { super(oc); _xmlParserFeatures = xpFeatures; _xmlGeneratorFeatures = xgFeatures; _cfgNameForTextElement = nameForTextElem; if (xmlIn == null) { xmlIn = XMLInputFactory.newInstance(); } if (xmlOut == null) { xmlOut = XMLOutputFactory.newInstance(); } _initFactories(xmlIn, xmlOut); _xmlInputFactory = xmlIn; _xmlOutputFactory = xmlOut; } protected XmlFactory(ObjectCodec oc, int xpFeatures, int xgFeatures, XMLInputFactory xmlIn, XMLOutputFactory xmlOut, String nameForTextElem) { super(oc); if (xmlOut == null) { xmlOut = XMLOutputFactory.newInstance(); } _xmlGeneratorFeatures = xgFeatures; if (xmlIn == null) { xmlIn = XMLInputFactory.newInstance(); xmlIn.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); } _cfgNameForTextElement = nameForTextElem; _xmlParserFeatures = xpFeatures; _initFactories(xmlIn, xmlOut); _xmlOutputFactory = xmlOut; _xmlInputFactory = xmlIn; }
./VJBench/llm-vul/VJBench-trans/VUL4J-46
vul4j_data_VUL4J-3
@Converter public SAXSource toSAXSourceFromStream(StreamSource source, Exchange exchange) throws SAXException { InputSource inputSource; if (source.getReader() != null) { inputSource = new InputSource(source.getReader()); } else { inputSource = new InputSource(source.getInputStream()); } inputSource.setSystemId(source.getSystemId()); inputSource.setPublicId(source.getPublicId()); XMLReader xmlReader = null; SAXParserFactory sfactory = null; try { if (exchange != null) { sfactory = exchange.getProperty(Exchange.SAXPARSER_FACTORY, SAXParserFactory.class); } if (sfactory == null) { sfactory = SAXParserFactory.newInstance(); try { sfactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (Exception e) { LOG.warn("SAXParser doesn't support the feature {} with value {}, due to {}.", new Object[]{javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, "true", e}); } } sfactory.setNamespaceAware(true); SAXParser parser = sfactory.newSAXParser(); xmlReader = parser.getXMLReader(); } catch (Exception ex) { LOG.warn("Cannot create the SAXParser XMLReader, due to {}", ex); } return new SAXSource(xmlReader, inputSource); } @Converter public SAXSource toSAXSourceFromStream(StreamSource source, Exchange exchange) throws SAXException { XMLReader xmlReader = null; SAXParserFactory sfactory = null; try { if (!(exchange == null)) { sfactory = exchange.getProperty(Exchange.SAXPARSER_FACTORY, SAXParserFactory.class); } if (sfactory != null) { sfactory.setNamespaceAware(true); xmlReader = sfactory.newSAXParser().getXMLReader(); }else{ sfactory = SAXParserFactory.newInstance(); try { sfactory.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true); } catch (Exception e) { LOG.warn("SAXParser doesn't support the feature {} with value {}, due to {}.", new Object[]{javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, "true", e}); } try { sfactory.setFeature("http://xml.org/sax/features/external-general-entities", false); } catch (SAXException e) { LOG.warn("SAXParser doesn't support the feature {} with value {}, due to {}." , new Object[]{"http://xml.org/sax/features/external-general-entities", false, e}); } sfactory.setNamespaceAware(true); xmlReader = sfactory.newSAXParser().getXMLReader(); } } catch (Exception ex) { LOG.warn("Cannot create the SAXParser XMLReader, due to {}", ex); } Reader reader = source.getReader(); InputSource inputSource = reader == null? new InputSource(source.getInputStream()):new InputSource(reader); String systemId = source.getSystemId(); inputSource.setSystemId(systemId); String publicId = source.getPublicId(); inputSource.setPublicId(publicId); return new SAXSource(xmlReader, inputSource); }
./VJBench/llm-vul/VJBench-trans/VUL4J-3
vul4j_data_VUL4J-5
private void expand(ArchiveEntrySupplier supplier, EntryWriter writer, File targetDirectory) throws IOException { String targetDirPath = targetDirectory.getCanonicalPath(); ArchiveEntry nextEntry = supplier.getNextReadableEntry(); while (nextEntry != null) { File f = new File(targetDirectory, nextEntry.getName()); if (!f.getCanonicalPath().startsWith(targetDirPath)) { throw new IOException("expanding " + nextEntry.getName() + " would create file outside of " + targetDirectory); } if (nextEntry.isDirectory()) { if (!f.isDirectory() && !f.mkdirs()) { throw new IOException("failed to create directory " + f); } } else { File parent = f.getParentFile(); if (!parent.isDirectory() && !parent.mkdirs()) { throw new IOException("failed to create directory " + parent); } try (OutputStream o = Files.newOutputStream(f.toPath())) { writer.writeEntryDataTo(nextEntry, o); } } nextEntry = supplier.getNextReadableEntry(); } } private void expand(ArchiveEntrySupplier supplier, EntryWriter writer, File targetDirectory) throws IOException { for (ArchiveEntry nextEntry = supplier.getNextReadableEntry(); nextEntry != null; nextEntry = supplier.getNextReadableEntry()) { String name = nextEntry.getName(); File f = new File(targetDirectory, name); String fpath = f.getCanonicalPath(); if (fpath.startsWith(targetDirectory.getCanonicalPath()+ File.separatorChar)) { if (!nextEntry.isDirectory()) { File parent = f.getParentFile(); if (parent.isDirectory() || parent.mkdirs()) { Path fp = f.toPath(); try (OutputStream o = Files.newOutputStream(fp)) { writer.writeEntryDataTo(nextEntry, o); } }else{ String s = "failed to create directory " + parent; throw new IOException(s); } } else { if (f.isDirectory() || f.mkdirs()) { continue; }else{ String s = "failed to create directory " + f; throw new IOException(s); } } }else{ String s = "expanding " + nextEntry.getName() + " would create file outside of " + targetDirectory; throw new IOException(s); } } }
./VJBench/llm-vul/VJBench-trans/VUL4J-5
vul4j_data_VUL4J-10
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); OutputStream output = getOutputStream(); if (cachedContent != null) { output.write(cachedContent); } else { FileInputStream input = new FileInputStream(dfosFile); IOUtils.copy(input, output); dfosFile.delete(); dfosFile = null; } output.close(); cachedContent = null; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); if (repository != null) { if (repository.isDirectory()) { // Check path for nulls if (repository.getPath().contains("\0")) { throw new IOException(format( "The repository [%s] contains a null character", repository.getPath())); } } else { throw new IOException(format( "The repository [%s] is not a directory", repository.getAbsolutePath())); } } OutputStream output = getOutputStream(); if (cachedContent == null) { IOUtils.copy(new FileInputStream(dfosFile), output); dfosFile.delete(); dfosFile = null; } else { output.write(cachedContent); } output.close(); cachedContent = null; }
./VJBench/llm-vul/VJBench-trans/VUL4J-10
vul4j_data_VUL4J-41
protected void extractFile( final File srcF, final File dir, final InputStream compressedInputStream, final String entryName, final Date entryDate, final boolean isDirectory, final Integer mode, String symlinkDestination ) throws IOException, ArchiverException { final File f = FileUtils.resolveFile( dir, entryName ); try { if ( !isOverwrite() && f.exists() && ( f.lastModified() >= entryDate.getTime() ) ) { return; } final File dirF = f.getParentFile(); if ( dirF != null ) { dirF.mkdirs(); } if ( !StringUtils.isEmpty( symlinkDestination ) ) { SymlinkUtils.createSymbolicLink( f, new File( symlinkDestination ) ); } else if ( isDirectory ) { f.mkdirs(); } else { OutputStream out = null; try { out = new FileOutputStream( f ); IOUtil.copy( compressedInputStream, out ); out.close(); out = null; } finally { IOUtil.close( out ); } } f.setLastModified( entryDate.getTime() ); if ( !isIgnorePermissions() && mode != null && !isDirectory ) { ArchiveEntryUtils.chmod( f, mode ); } } catch ( final FileNotFoundException ex ) { getLogger().warn( "Unable to expand to file " + f.getPath() ); } } protected void extractFile( final File srcF, final File dir, final InputStream compressedInputStream, final String entryName, final Date entryDate, final boolean isDirectory, final Integer mode, String symlinkDestination ) throws IOException, ArchiverException { final File f = FileUtils.resolveFile( dir, entryName ); String canonicalDirPath = dir.getCanonicalPath(); String canonicalDestPath = f.getCanonicalPath(); if ( !canonicalDestPath.startsWith( canonicalDirPath ) ) { throw new ArchiverException( "Entry is outside of the target directory (" + entryName + ")" ); } try{ if ( isOverwrite() || !f.exists() || f.lastModified() < entryDate.getTime() ) { final File dirF = f.getParentFile(); if ( dirF != null ) { dirF.mkdirs(); } if ( StringUtils.isEmpty( symlinkDestination ) ) { if (! isDirectory ) { OutputStream out = null; try { out = new FileOutputStream( f ); IOUtil.copy( compressedInputStream, out ); out.close(); out = null; } finally { IOUtil.close( out ); } } else { f.mkdirs(); } } else{ File file = new File( symlinkDestination ); SymlinkUtils.createSymbolicLink( f, file ); } long time = entryDate.getTime(); f.setLastModified( time ); if ( !isIgnorePermissions() && mode != null && !isDirectory ) { ArchiveEntryUtils.chmod( f, mode ); } }else{ return; } } catch ( final FileNotFoundException ex ) { String path = f.getPath(); getLogger().warn( "Unable to expand to file " + path ); } }
./VJBench/llm-vul/VJBench-trans/VUL4J-41
vul4j_data_VUL4J-7
private int readStored(final byte[] buffer, final int offset, final int length) throws IOException { if (current.hasDataDescriptor) { if (lastStoredEntry == null) { readStoredEntry(); } return lastStoredEntry.read(buffer, offset, length); } final long csize = current.entry.getSize(); if (current.bytesRead >= csize) { return -1; } if (buf.position() >= buf.limit()) { buf.position(0); final int l = in.read(buf.array()); if (l == -1) { return -1; } buf.limit(l); count(l); current.bytesReadFromStream += l; } int toRead = Math.min(buf.remaining(), length); if ((csize - current.bytesRead) < toRead) { toRead = (int) (csize - current.bytesRead); } buf.get(buffer, offset, toRead); current.bytesRead += toRead; return toRead; } private int readStored(final byte[] buffer, final int offset, final int length) throws IOException { if (!current.hasDataDescriptor) { final long csize = current.entry.getSize(); if (current.bytesRead < csize) { if (buf.position() >= buf.limit()) { buf.position(0); byte[] bufArray = buf.array(); final int l = in.read(bufArray); if (l != -1) { buf.limit(l); count(l); current.bytesReadFromStream += l; }else{ buf.limit(0); throw new IOException("Truncated ZIP file"); } } int bufRemaining = buf.remaining(); int toRead = Math.min(bufRemaining, length); if ((csize - current.bytesRead) < toRead) { toRead = (int) (csize - current.bytesRead); } buf.get(buffer, offset, toRead); current.bytesRead += toRead; return toRead; }else{ return -1; } }else{ if (lastStoredEntry == null) { readStoredEntry(); } return lastStoredEntry.read(buffer, offset, length); } }
./VJBench/llm-vul/VJBench-trans/VUL4J-7
vul4j_data_VUL4J-59
void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '\t': case '\n': case '\r': case '\f': case ' ': break; case '"': t.transition(AttributeValue_doubleQuoted); break; case '&': r.unconsume(); t.transition(AttributeValue_unquoted); break; case '\'': t.transition(AttributeValue_singleQuoted); break; case nullChar: t.error(this); t.tagPending.appendAttributeValue(replacementChar); t.transition(AttributeValue_unquoted); break; case eof: t.eofError(this); t.transition(Data); break; case '>': t.error(this); t.emitTagPending(); t.transition(Data); break; case '<': case '=': case '`': t.error(this); t.tagPending.appendAttributeValue(c); t.transition(AttributeValue_unquoted); break; default: r.unconsume(); t.transition(AttributeValue_unquoted); } } void read(Tokeniser t, CharacterReader r) { char c = r.consume(); if(c== eof){ t.eofError(this); t.emitTagPending(); t.transition(Data); return; } if (c == '\f' || c == '\n' || c== ' '|| c== '\r' || c == '\t'){ return; } if(c =='\'' ){ t.transition(AttributeValue_singleQuoted); return; } if( c== '>'){ t.error(this); t.emitTagPending(); t.transition(Data); return; } if(c == nullChar){ t.error(this); t.tagPending.appendAttributeValue(replacementChar); t.transition(AttributeValue_unquoted); return; } if(c == '"'){ t.transition(AttributeValue_doubleQuoted); return; } if(c =='&' ){ r.unconsume(); t.transition(AttributeValue_unquoted); return; } if ( c== '<' || c == '`' || c == '='){ t.error(this); t.tagPending.appendAttributeValue(c); t.transition(AttributeValue_unquoted); return; } r.unconsume(); t.transition(AttributeValue_unquoted); }
./VJBench/llm-vul/VJBench-trans/VUL4J-59
vul4j_data_VUL4J-1
@SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { final JSONLexer lexer = parser.lexer; if (lexer.token() == JSONToken.NULL) { lexer.nextToken(JSONToken.COMMA); return null; } if (lexer.token() == JSONToken.LITERAL_STRING) { byte[] bytes = lexer.bytesValue(); lexer.nextToken(JSONToken.COMMA); return (T) bytes; } Class componentClass; Type componentType; if (type instanceof GenericArrayType) { GenericArrayType clazz = (GenericArrayType) type; componentType = clazz.getGenericComponentType(); if (componentType instanceof TypeVariable) { TypeVariable typeVar = (TypeVariable) componentType; Type objType = parser.getContext().type; if (objType instanceof ParameterizedType) { ParameterizedType objParamType = (ParameterizedType) objType; Type objRawType = objParamType.getRawType(); Type actualType = null; if (objRawType instanceof Class) { TypeVariable[] objTypeParams = ((Class) objRawType).getTypeParameters(); for (int i = 0; i < objTypeParams.length; ++i) { if (objTypeParams[i].getName().equals(typeVar.getName())) { actualType = objParamType.getActualTypeArguments()[i]; } } } if (actualType instanceof Class) { componentClass = (Class) actualType; } else { componentClass = Object.class; } } else { componentClass = TypeUtils.getClass(typeVar.getBounds()[0]); } } else { componentClass = TypeUtils.getClass(componentType); } } else { Class clazz = (Class) type; componentType = componentClass = clazz.getComponentType(); } JSONArray array = new JSONArray(); parser.parseArray(componentClass, array, fieldName); return (T) toObjectArray(parser, componentClass, array); } @SuppressWarnings({ "unchecked", "rawtypes" }) public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) { final JSONLexer lexer = parser.lexer; switch (lexer.token()) { case JSONToken.LITERAL_STRING: byte[] bytes = lexer.bytesValue(); lexer.nextToken(JSONToken.COMMA); return (T) bytes; case JSONToken.NULL: lexer.nextToken(JSONToken.COMMA); return null; default: break; } JSONArray array = new JSONArray(); Class componentClass; Type componentType; if (!(type instanceof GenericArrayType)) { componentType = ((Class) type).getComponentType(); componentClass = ((Class) type).getComponentType(); } else { componentType = ((GenericArrayType) type).getGenericComponentType(); if (! (componentType instanceof TypeVariable)) { componentClass = TypeUtils.getClass(componentType); } else { TypeVariable typeVar = (TypeVariable) componentType; Type objType = parser.getContext().type; if (!(objType instanceof ParameterizedType)) { Type type_ = typeVar.getBounds()[0]; componentClass = TypeUtils.getClass(type_); } else { ParameterizedType objParamType = (ParameterizedType) objType; Type objRawType = objParamType.getRawType(); Type actualType = null; if (objRawType instanceof Class) { TypeVariable[] objTypeParams = ((Class) objRawType).getTypeParameters(); int i = 0; while( i < objTypeParams.length) { String i_name = objTypeParams[i].getName(); String typeVar_name = typeVar.getName(); if (!i_name.equals(typeVar_name)) { i++; continue; } actualType = objParamType.getActualTypeArguments()[i]; i++; } } componentClass = (actualType instanceof Class)? (Class) actualType:Object.class; } } } parser.parseArray(componentType, array, fieldName); return (T) toObjectArray(parser, componentClass, array); }
./VJBench/llm-vul/VJBench-trans/VUL4J-1
vul4j_data_VUL4J-22
public static String getContextPath(HttpServletRequest request) { String contextPath = (String) request.getAttribute(INCLUDE_CONTEXT_PATH_ATTRIBUTE); if (contextPath == null) { contextPath = request.getContextPath(); } if ("/".equals(contextPath)) { contextPath = ""; } return decodeRequestString(request, contextPath); } public static String getContextPath(HttpServletRequest request) { String contextPath = (String) request.getAttribute(INCLUDE_CONTEXT_PATH_ATTRIBUTE); contextPath = contextPath == null? request.getContextPath(): contextPath; contextPath = normalize(decodeRequestString(request, contextPath)); if (!"/".equals(contextPath)) return contextPath; else return ""; }
./VJBench/llm-vul/VJBench-trans/VUL4J-22
vul4j_data_VUL4J-47
protected XmlFactory(ObjectCodec oc, int xpFeatures, int xgFeatures, XMLInputFactory xmlIn, XMLOutputFactory xmlOut, String nameForTextElem) { super(oc); _xmlParserFeatures = xpFeatures; _xmlGeneratorFeatures = xgFeatures; _cfgNameForTextElement = nameForTextElem; if (xmlIn == null) { xmlIn = XMLInputFactory.newInstance(); xmlIn.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); } if (xmlOut == null) { xmlOut = XMLOutputFactory.newInstance(); } _initFactories(xmlIn, xmlOut); _xmlInputFactory = xmlIn; _xmlOutputFactory = xmlOut; } protected XmlFactory(ObjectCodec oc, int xpFeatures, int xgFeatures, XMLInputFactory xmlIn, XMLOutputFactory xmlOut, String nameForTextElem) { super(oc); if (xmlOut == null) { xmlOut = XMLOutputFactory.newInstance(); } _xmlGeneratorFeatures = xgFeatures; if (xmlIn == null) { xmlIn = XMLInputFactory.newInstance(); xmlIn.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); xmlIn.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); } _cfgNameForTextElement = nameForTextElem; _xmlParserFeatures = xpFeatures; _initFactories(xmlIn, xmlOut); _xmlOutputFactory = xmlOut; _xmlInputFactory = xmlIn; }
./VJBench/llm-vul/VJBench-trans/VUL4J-47
vul4j_data_VUL4J-64
final static private XMLStreamReader createXMLStreamReader(InputStream inputStream) throws XMLStreamException, IOException { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_COALESCING, true); factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, true); return factory.createXMLStreamReader(wrapPrefixRemovingInputStream(inputStream)); } final static private XMLStreamReader createXMLStreamReader(InputStream inputStream) throws XMLStreamException, IOException { XMLInputFactory factory = XMLInputFactory.newInstance(); factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, true); factory.setProperty(XMLInputFactory.IS_COALESCING, true); factory.setProperty(XMLInputFactory.SUPPORT_DTD, false); InputStream in = wrapPrefixRemovingInputStream(inputStream); return factory.createXMLStreamReader(in); }
./VJBench/llm-vul/VJBench-trans/VUL4J-64
vul4j_data_VUL4J-18
public String getForwardPage( HttpServletRequest request ) { return request.getPathInfo(); } public String getForwardPage( HttpServletRequest request ) { return "Wiki.jsp"; }
./VJBench/llm-vul/VJBench-trans/VUL4J-18
vul4j_data_VUL4J-55
public Calendar ceil(Calendar cal) { Calendar twoYearsFuture = (Calendar) cal.clone(); twoYearsFuture.add(Calendar.YEAR, 2); OUTER: while (true) { if (cal.compareTo(twoYearsFuture) > 0) { throw new RareOrImpossibleDateException(); } for (CalendarField f : CalendarField.ADJUST_ORDER) { int cur = f.valueOf(cal); int next = f.ceil(this,cur); if (cur==next) continue; for (CalendarField l=f.lowerField; l!=null; l=l.lowerField) l.clear(cal); if (next<0) { f.rollUp(cal, 1); f.setTo(cal,f.first(this)); continue OUTER; } else { f.setTo(cal,next); if (f.redoAdjustmentIfModified) continue OUTER; } } return cal; } } public Calendar ceil(Calendar cal) { Calendar twoYearsFuture = (Calendar) cal.clone(); twoYearsFuture.add(Calendar.YEAR, 2); OUTER: while (true) { if (cal.compareTo(twoYearsFuture) <= 0) { int i =0; while (i< CalendarField.ADJUST_ORDER.length) { CalendarField f = CalendarField.ADJUST_ORDER[i++]; int cur = f.valueOf(cal); int next = f.ceil(this,cur); if (cur==next) continue; CalendarField l=f.lowerField; while (l!=null){ l.clear(cal); l=l.lowerField; } if (next>=0) { f.setTo(cal,next); if (f.valueOf(cal) != next) { // we need to roll over to the next field. f.rollUp(cal, 1); f.setTo(cal,f.first(this)); // since higher order field is affected by this, we need to restart from all over continue OUTER; } if (f.redoAdjustmentIfModified) continue OUTER; } else { f.rollUp(cal, 1); f.setTo(cal,f.first(this)); continue OUTER; } } return cal; }else{ throw new RareOrImpossibleDateException(); } } }
./VJBench/llm-vul/VJBench-trans/VUL4J-55
README.md exists but content is empty.
Downloads last month
1