input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
System.out.printf("Log files: %s/logs/%n", NACOS_HOME);
System.out.printf("Conf files: %s/conf/%n", NACOS_HOME);
System.out.printf("Data files: %s/data/%n", NACOS_HOME);
if (!STANDALONE_MODE) {
try {
List<String> clusterConf = readClusterConf();
System.out.printf("The server IP list of Nacos is %s%n", clusterConf);
} catch (IOException e) {
logger.error("read cluster conf fail", e);
}
}
System.out.println();
}
#location 3
#vulnerability type CHECKERS_PRINTF_ARGS | #fixed code
@Override
public void contextPrepared(ConfigurableApplicationContext context) {
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void checkLocalConfig(CacheData cacheData) {
final String dataId = cacheData.dataId;
final String group = cacheData.group;
final String tenant = cacheData.tenant;
File path = LocalConfigInfoProcessor.getFailoverFile(agent.getName(), dataId, group, tenant);
// 没有 -> 有
if (!cacheData.isUseLocalConfigInfo() && path.exists()) {
String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant);
String md5 = MD5.getInstance().getMD5String(content);
cacheData.setUseLocalConfigInfo(true);
cacheData.setLocalConfigInfoVersion(path.lastModified());
cacheData.setContent(content);
LOGGER.warn("[{}] [failover-change] failover file created. dataId={}, group={}, tenant={}, md5={}, content={}",
agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content));
return;
}
// 有 -> 没有。不通知业务监听器,从server拿到配置后通知。
if (cacheData.isUseLocalConfigInfo() && !path.exists()) {
cacheData.setUseLocalConfigInfo(false);
LOGGER.warn("[{}] [failover-change] failover file deleted. dataId={}, group={}, tenant={}", agent.getName(),
dataId, group, tenant);
return;
}
// 有变更
if (cacheData.isUseLocalConfigInfo() && path.exists()
&& cacheData.getLocalConfigInfoVersion() != path.lastModified()) {
String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant);
String md5 = MD5.getInstance().getMD5String(content);
cacheData.setUseLocalConfigInfo(true);
cacheData.setLocalConfigInfoVersion(path.lastModified());
cacheData.setContent(content);
LOGGER.warn("[{}] [failover-change] failover file changed. dataId={}, group={}, tenant={}, md5={}, content={}",
agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content));
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
private void checkLocalConfig(CacheData cacheData) {
final String dataId = cacheData.dataId;
final String group = cacheData.group;
final String tenant = cacheData.tenant;
File path = LocalConfigInfoProcessor.getFailoverFile(agent.getName(), dataId, group, tenant);
// 没有 -> 有
if (!cacheData.isUseLocalConfigInfo() && path.exists()) {
String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant);
String md5 = MD5Utils.md5Hex(content, Constants.ENCODE);
cacheData.setUseLocalConfigInfo(true);
cacheData.setLocalConfigInfoVersion(path.lastModified());
cacheData.setContent(content);
LOGGER.warn("[{}] [failover-change] failover file created. dataId={}, group={}, tenant={}, md5={}, content={}",
agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content));
return;
}
// 有 -> 没有。不通知业务监听器,从server拿到配置后通知。
if (cacheData.isUseLocalConfigInfo() && !path.exists()) {
cacheData.setUseLocalConfigInfo(false);
LOGGER.warn("[{}] [failover-change] failover file deleted. dataId={}, group={}, tenant={}", agent.getName(),
dataId, group, tenant);
return;
}
// 有变更
if (cacheData.isUseLocalConfigInfo() && path.exists()
&& cacheData.getLocalConfigInfoVersion() != path.lastModified()) {
String content = LocalConfigInfoProcessor.getFailover(agent.getName(), dataId, group, tenant);
String md5 = MD5Utils.md5Hex(content, Constants.ENCODE);
cacheData.setUseLocalConfigInfo(true);
cacheData.setLocalConfigInfoVersion(path.lastModified());
cacheData.setContent(content);
LOGGER.warn("[{}] [failover-change] failover file changed. dataId={}, group={}, tenant={}, md5={}, content={}",
agent.getName(), dataId, group, tenant, md5, ContentUtils.truncateContent(content));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException {
Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral));
List<Instance> currentIPs = service.allIPs(ephemeral);
Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size());
Set<Integer> currentInstanceIndexes = Sets.newHashSet();
for (Instance instance : currentIPs) {
currentInstances.put(instance.toIPAddr(), instance);
if (instance.getInstanceIndex() != null) {
currentInstanceIndexes.add(instance.getInstanceIndex());
}
}
Map<String, Instance> instanceMap;
if (datum != null) {
instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances);
} else {
instanceMap = new HashMap<>(ips.length);
}
for (Instance instance : ips) {
if (!service.getClusterMap().containsKey(instance.getClusterName())) {
Cluster cluster = new Cluster(instance.getClusterName(), service);
cluster.init();
service.getClusterMap().put(instance.getClusterName(), cluster);
Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.",
instance.getClusterName(), instance.toJSON());
}
if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) {
instanceMap.remove(instance.getDatumKey());
} else {
// Generate instance index
int instanceIndex = 0;
while (currentInstanceIndexes.contains(instanceIndex)) {
instanceIndex++;
}
currentInstanceIndexes.add(instanceIndex);
instance.setInstanceIndex(instanceIndex);
instanceMap.put(instance.getDatumKey(), instance);
}
}
if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) {
throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: "
+ JSON.toJSONString(instanceMap.values()));
}
return new ArrayList<>(instanceMap.values());
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException {
Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral));
List<Instance> currentIPs = service.allIPs(ephemeral);
Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size());
Set<String> currentInstanceIds = Sets.newHashSet();
for (Instance instance : currentIPs) {
currentInstances.put(instance.toIPAddr(), instance);
currentInstanceIds.add(instance.getInstanceId());
}
Map<String, Instance> instanceMap;
if (datum != null) {
instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances);
} else {
instanceMap = new HashMap<>(ips.length);
}
for (Instance instance : ips) {
if (!service.getClusterMap().containsKey(instance.getClusterName())) {
Cluster cluster = new Cluster(instance.getClusterName(), service);
cluster.init();
service.getClusterMap().put(instance.getClusterName(), cluster);
Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.",
instance.getClusterName(), instance.toJSON());
}
if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) {
instanceMap.remove(instance.getDatumKey());
} else {
instance.setInstanceId(instance.generateInstanceId(currentInstanceIds));
instanceMap.put(instance.getDatumKey(), instance);
}
}
if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) {
throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: "
+ JSON.toJSONString(instanceMap.values()));
}
return new ArrayList<>(instanceMap.values());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@RequestMapping("/updateClusterConf")
public JSONObject updateClusterConf(HttpServletRequest request) throws IOException {
JSONObject result = new JSONObject();
String ipSpliter = ",";
String ips = BaseServlet.optional(request, "ips", "");
String action = BaseServlet.required(request, "action");
if (SwitchEntry.ACTION_ADD.equals(action)) {
List<String> oldList =
IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (String ip : oldList) {
sb.append(ip).append("\r\n");
}
for (String ip : ips.split(ipSpliter)) {
sb.append(ip).append("\r\n");
}
Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString());
IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8");
return result;
}
if (SwitchEntry.ACTION_REPLACE.equals(action)) {
StringBuilder sb = new StringBuilder();
for (String ip : ips.split(ipSpliter)) {
sb.append(ip).append("\r\n");
}
Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString());
IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8");
return result;
}
if (SwitchEntry.ACTION_DELETE.equals(action)) {
Set<String> removeIps = new HashSet<>();
for (String ip : ips.split(ipSpliter)) {
removeIps.add(ip);
}
List<String> oldList =
IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8"));
Iterator<String> iterator = oldList.iterator();
while (iterator.hasNext()) {
String ip = iterator.next();
if (removeIps.contains(ip)) {
iterator.remove();
}
}
StringBuilder sb = new StringBuilder();
for (String ip : oldList) {
sb.append(ip).append("\r\n");
}
IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8");
return result;
}
if (SwitchEntry.ACTION_VIEW.equals(action)) {
List<String> oldList =
IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8"));
result.put("list", oldList);
return result;
}
throw new InvalidParameterException("action is not qualified, action: " + action);
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
@RequestMapping("/updateClusterConf")
public JSONObject updateClusterConf(HttpServletRequest request) throws IOException {
JSONObject result = new JSONObject();
String ipSpliter = ",";
String ips = BaseServlet.optional(request, "ips", "");
String action = BaseServlet.required(request, "action");
if (SwitchEntry.ACTION_ADD.equals(action)) {
List<String> oldList = readClusterConf();
StringBuilder sb = new StringBuilder();
for (String ip : oldList) {
sb.append(ip).append("\r\n");
}
for (String ip : ips.split(ipSpliter)) {
sb.append(ip).append("\r\n");
}
Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString());
writeClusterConf(sb.toString());
return result;
}
if (SwitchEntry.ACTION_REPLACE.equals(action)) {
StringBuilder sb = new StringBuilder();
for (String ip : ips.split(ipSpliter)) {
sb.append(ip).append("\r\n");
}
Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString());
writeClusterConf(sb.toString());
return result;
}
if (SwitchEntry.ACTION_DELETE.equals(action)) {
Set<String> removeIps = new HashSet<>();
for (String ip : ips.split(ipSpliter)) {
removeIps.add(ip);
}
List<String> oldList = readClusterConf();
Iterator<String> iterator = oldList.iterator();
while (iterator.hasNext()) {
String ip = iterator.next();
if (removeIps.contains(ip)) {
iterator.remove();
}
}
StringBuilder sb = new StringBuilder();
for (String ip : oldList) {
sb.append(ip).append("\r\n");
}
writeClusterConf(sb.toString());
return result;
}
if (SwitchEntry.ACTION_VIEW.equals(action)) {
List<String> oldList = readClusterConf();
result.put("list", oldList);
return result;
}
throw new InvalidParameterException("action is not qualified, action: " + action);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void update(SwitchDomain newSwitchDomain) {
switchDomain.setMasters(newSwitchDomain.getMasters());
switchDomain.setAdWeightMap(newSwitchDomain.getAdWeightMap());
switchDomain.setDefaultPushCacheMillis(newSwitchDomain.getDefaultPushCacheMillis());
switchDomain.setClientBeatInterval(newSwitchDomain.getClientBeatInterval());
switchDomain.setDefaultCacheMillis(newSwitchDomain.getDefaultCacheMillis());
switchDomain.setDistroThreshold(newSwitchDomain.getDistroThreshold());
switchDomain.setHealthCheckEnabled(newSwitchDomain.isHealthCheckEnabled());
switchDomain.setDistroEnabled(newSwitchDomain.isDistroEnabled());
switchDomain.setPushEnabled(newSwitchDomain.isPushEnabled());
switchDomain.setEnableStandalone(newSwitchDomain.isEnableStandalone());
switchDomain.setCheckTimes(newSwitchDomain.getCheckTimes());
switchDomain.setHttpHealthParams(newSwitchDomain.getHttpHealthParams());
switchDomain.setTcpHealthParams(newSwitchDomain.getTcpHealthParams());
switchDomain.setMysqlHealthParams(newSwitchDomain.getMysqlHealthParams());
switchDomain.setIncrementalList(newSwitchDomain.getIncrementalList());
switchDomain.setServerStatusSynchronizationPeriodMillis(newSwitchDomain.getServerStatusSynchronizationPeriodMillis());
switchDomain.setServiceStatusSynchronizationPeriodMillis(newSwitchDomain.getServiceStatusSynchronizationPeriodMillis());
switchDomain.setDisableAddIP(newSwitchDomain.isDisableAddIP());
switchDomain.setSendBeatOnly(newSwitchDomain.isSendBeatOnly());
switchDomain.setLimitedUrlMap(newSwitchDomain.getLimitedUrlMap());
switchDomain.setDistroServerExpiredMillis(newSwitchDomain.getDistroServerExpiredMillis());
switchDomain.setPushGoVersion(newSwitchDomain.getPushGoVersion());
switchDomain.setPushJavaVersion(newSwitchDomain.getPushJavaVersion());
switchDomain.setPushPythonVersion(newSwitchDomain.getPushPythonVersion());
switchDomain.setPushCVersion(newSwitchDomain.getPushCVersion());
switchDomain.setEnableAuthentication(newSwitchDomain.isEnableAuthentication());
switchDomain.setOverriddenServerStatus(newSwitchDomain.getOverriddenServerStatus());
switchDomain.setServerMode(newSwitchDomain.getServerMode());
}
#location 29
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void update(SwitchDomain newSwitchDomain) {
switchDomain.setMasters(newSwitchDomain.getMasters());
switchDomain.setAdWeightMap(newSwitchDomain.getAdWeightMap());
switchDomain.setDefaultPushCacheMillis(newSwitchDomain.getDefaultPushCacheMillis());
switchDomain.setClientBeatInterval(newSwitchDomain.getClientBeatInterval());
switchDomain.setDefaultCacheMillis(newSwitchDomain.getDefaultCacheMillis());
switchDomain.setDistroThreshold(newSwitchDomain.getDistroThreshold());
switchDomain.setHealthCheckEnabled(newSwitchDomain.isHealthCheckEnabled());
switchDomain.setDistroEnabled(newSwitchDomain.isDistroEnabled());
switchDomain.setPushEnabled(newSwitchDomain.isPushEnabled());
switchDomain.setEnableStandalone(newSwitchDomain.isEnableStandalone());
switchDomain.setCheckTimes(newSwitchDomain.getCheckTimes());
switchDomain.setHttpHealthParams(newSwitchDomain.getHttpHealthParams());
switchDomain.setTcpHealthParams(newSwitchDomain.getTcpHealthParams());
switchDomain.setMysqlHealthParams(newSwitchDomain.getMysqlHealthParams());
switchDomain.setIncrementalList(newSwitchDomain.getIncrementalList());
switchDomain.setServerStatusSynchronizationPeriodMillis(newSwitchDomain.getServerStatusSynchronizationPeriodMillis());
switchDomain.setServiceStatusSynchronizationPeriodMillis(newSwitchDomain.getServiceStatusSynchronizationPeriodMillis());
switchDomain.setDisableAddIP(newSwitchDomain.isDisableAddIP());
switchDomain.setSendBeatOnly(newSwitchDomain.isSendBeatOnly());
switchDomain.setLimitedUrlMap(newSwitchDomain.getLimitedUrlMap());
switchDomain.setDistroServerExpiredMillis(newSwitchDomain.getDistroServerExpiredMillis());
switchDomain.setPushGoVersion(newSwitchDomain.getPushGoVersion());
switchDomain.setPushJavaVersion(newSwitchDomain.getPushJavaVersion());
switchDomain.setPushPythonVersion(newSwitchDomain.getPushPythonVersion());
switchDomain.setPushCVersion(newSwitchDomain.getPushCVersion());
switchDomain.setEnableAuthentication(newSwitchDomain.isEnableAuthentication());
switchDomain.setOverriddenServerStatus(newSwitchDomain.getOverriddenServerStatus());
switchDomain.setDefaultInstanceEphemeral(newSwitchDomain.isDefaultInstanceEphemeral());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@NeedAuth
@RequestMapping("/remvIP4Dom")
public String remvIP4Dom(HttpServletRequest request) throws Exception {
String dom = WebUtils.required(request, "dom");
String ipListString = WebUtils.required(request, "ipList");
Loggers.DEBUG_LOG.debug("[REMOVE-IP] full arguments: serviceName:" + dom + ", iplist:" + ipListString);
List<IpAddress> newIPs = new ArrayList<>();
List<String> ipList = new ArrayList<>();
if (Boolean.parseBoolean(WebUtils.optional(request, SwitchEntry.PARAM_JSON, Boolean.FALSE.toString()))) {
newIPs = JSON.parseObject(ipListString, new TypeReference<List<IpAddress>>() {
});
} else {
ipList = Arrays.asList(ipListString.split(","));
}
List<IpAddress> ipObjList = new ArrayList<>(ipList.size());
if (Boolean.parseBoolean(WebUtils.optional(request, SwitchEntry.PARAM_JSON, Boolean.FALSE.toString()))) {
ipObjList = newIPs;
} else {
for (String ip : ipList) {
ipObjList.add(IpAddress.fromJSON(ip));
}
}
domainsManager.easyRemvIP4Dom(dom, ipObjList);
Loggers.EVT_LOG.info("{" + dom + "} {POS} {IP-REMV}" + " dead: "
+ ipList + " operator: "
+ WebUtils.optional(request, "clientIP", "unknown"));
return "ok";
}
#location 27
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@NeedAuth
@RequestMapping("/remvIP4Dom")
public String remvIP4Dom(HttpServletRequest request) throws Exception {
String dom = WebUtils.required(request, "dom");
String ipListString = WebUtils.required(request, "ipList");
Map<String, String> proxyParams = new HashMap<>(16);
for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
proxyParams.put(entry.getKey(), entry.getValue()[0]);
}
if (Loggers.DEBUG_LOG.isDebugEnabled()) {
Loggers.DEBUG_LOG.debug("[REMOVE-IP] full arguments: params:" + proxyParams);
}
List<String> ipList = new ArrayList<>();
List<IpAddress> ipObjList = new ArrayList<>(ipList.size());
if (Boolean.parseBoolean(WebUtils.optional(request, SwitchEntry.PARAM_JSON, Boolean.FALSE.toString()))) {
ipList = Arrays.asList(ipListString);
ipObjList = JSON.parseObject(ipListString, new TypeReference<List<IpAddress>>() {
});
} else {
ipList = Arrays.asList(ipListString.split(","));
for (String ip : ipList) {
ipObjList.add(IpAddress.fromJSON(ip));
}
}
if (!RaftCore.isLeader()) {
Loggers.RAFT.info("I'm not leader, will proxy to leader.");
if (RaftCore.getLeader() == null) {
throw new IllegalArgumentException("no leader now.");
}
RaftPeer leader = RaftCore.getLeader();
String server = leader.ip;
if (!server.contains(UtilsAndCommons.CLUSTER_CONF_IP_SPLITER)) {
server = server + UtilsAndCommons.CLUSTER_CONF_IP_SPLITER + RunningConfig.getServerPort();
}
String url = "http://" + server
+ RunningConfig.getContextPath() + UtilsAndCommons.NACOS_NAMING_CONTEXT + "/api/remvIP4Dom";
HttpClient.HttpResult result1 = HttpClient.httpPost(url, null, proxyParams);
if (result1.code != HttpURLConnection.HTTP_OK) {
Loggers.SRV_LOG.warn("failed to remove ip for dom, caused " + result1.content);
throw new IllegalArgumentException("failed to remove ip for dom, caused " + result1.content);
}
return "ok";
}
VirtualClusterDomain domain = (VirtualClusterDomain) domainsManager.getDomain(dom);
if (domain == null) {
throw new IllegalStateException("dom doesn't exist: " + dom);
}
if (CollectionUtils.isEmpty(ipObjList)) {
throw new IllegalArgumentException("Empty ip list");
}
String key = UtilsAndCommons.getIPListStoreKey(domainsManager.getDomain(dom));
long timestamp = 1;
if (RaftCore.getDatum(key) != null) {
timestamp = RaftCore.getDatum(key).timestamp.get();
}
if (RaftCore.isLeader()) {
try {
RaftCore.OPERATE_LOCK.lock();
proxyParams.put("clientIP", NetUtils.localServer());
proxyParams.put("notify", "true");
proxyParams.put("term", String.valueOf(RaftCore.getPeerSet().local().term));
proxyParams.put("timestamp", String.valueOf(timestamp));
onRemvIP4Dom(MockHttpRequest.buildRequest2(proxyParams));
if (domain.getEnableHealthCheck() && !domain.getEnableClientBeat()) {
syncOnRemvIP4Dom(dom, ipList, proxyParams, WebUtils.optional(request, "clientIP", "unknown"));
} else {
asyncOnRemvIP4Dom(dom, ipList, proxyParams, WebUtils.optional(request, "clientIP", "unknown"));
}
} finally {
RaftCore.OPERATE_LOCK.unlock();
}
Loggers.EVT_LOG.info("{" + dom + "} {POS} {IP-REMV}" + " new: "
+ ipListString + " operatorIP: "
+ WebUtils.optional(request, "clientIP", "unknown"));
}
return "ok";
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@RequestMapping("/updateClusterConf")
public JSONObject updateClusterConf(HttpServletRequest request) throws IOException {
JSONObject result = new JSONObject();
String ipSpliter = ",";
String ips = BaseServlet.optional(request, "ips", "");
String action = BaseServlet.required(request, "action");
if (SwitchEntry.ACTION_ADD.equals(action)) {
List<String> oldList =
IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (String ip : oldList) {
sb.append(ip).append("\r\n");
}
for (String ip : ips.split(ipSpliter)) {
sb.append(ip).append("\r\n");
}
Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString());
IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8");
return result;
}
if (SwitchEntry.ACTION_REPLACE.equals(action)) {
StringBuilder sb = new StringBuilder();
for (String ip : ips.split(ipSpliter)) {
sb.append(ip).append("\r\n");
}
Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString());
IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8");
return result;
}
if (SwitchEntry.ACTION_DELETE.equals(action)) {
Set<String> removeIps = new HashSet<>();
for (String ip : ips.split(ipSpliter)) {
removeIps.add(ip);
}
List<String> oldList =
IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8"));
Iterator<String> iterator = oldList.iterator();
while (iterator.hasNext()) {
String ip = iterator.next();
if (removeIps.contains(ip)) {
iterator.remove();
}
}
StringBuilder sb = new StringBuilder();
for (String ip : oldList) {
sb.append(ip).append("\r\n");
}
IoUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "utf-8");
return result;
}
if (SwitchEntry.ACTION_VIEW.equals(action)) {
List<String> oldList =
IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8"));
result.put("list", oldList);
return result;
}
throw new InvalidParameterException("action is not qualified, action: " + action);
}
#location 47
#vulnerability type RESOURCE_LEAK | #fixed code
@RequestMapping("/updateClusterConf")
public JSONObject updateClusterConf(HttpServletRequest request) throws IOException {
JSONObject result = new JSONObject();
String ipSpliter = ",";
String ips = BaseServlet.optional(request, "ips", "");
String action = BaseServlet.required(request, "action");
if (SwitchEntry.ACTION_ADD.equals(action)) {
List<String> oldList = readClusterConf();
StringBuilder sb = new StringBuilder();
for (String ip : oldList) {
sb.append(ip).append("\r\n");
}
for (String ip : ips.split(ipSpliter)) {
sb.append(ip).append("\r\n");
}
Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString());
writeClusterConf(sb.toString());
return result;
}
if (SwitchEntry.ACTION_REPLACE.equals(action)) {
StringBuilder sb = new StringBuilder();
for (String ip : ips.split(ipSpliter)) {
sb.append(ip).append("\r\n");
}
Loggers.SRV_LOG.info("[UPDATE-CLUSTER] new ips:" + sb.toString());
writeClusterConf(sb.toString());
return result;
}
if (SwitchEntry.ACTION_DELETE.equals(action)) {
Set<String> removeIps = new HashSet<>();
for (String ip : ips.split(ipSpliter)) {
removeIps.add(ip);
}
List<String> oldList = readClusterConf();
Iterator<String> iterator = oldList.iterator();
while (iterator.hasNext()) {
String ip = iterator.next();
if (removeIps.contains(ip)) {
iterator.remove();
}
}
StringBuilder sb = new StringBuilder();
for (String ip : oldList) {
sb.append(ip).append("\r\n");
}
writeClusterConf(sb.toString());
return result;
}
if (SwitchEntry.ACTION_VIEW.equals(action)) {
List<String> oldList = readClusterConf();
result.put("list", oldList);
return result;
}
throw new InvalidParameterException("action is not qualified, action: " + action);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Instance selectOneHealthyInstance(String serviceName, String groupName, List<String> clusters, boolean subscribe) throws NacosException {
if (subscribe) {
return Balancer.RandomByWeight.selectHost(
hostReactor.getServiceInfo(groupName + Constants.SERVICE_INFO_SPLITER + serviceName, StringUtils.join(clusters, ",")));
} else {
return Balancer.RandomByWeight.selectHost(
hostReactor.getServiceInfoDirectlyFromServer(groupName + Constants.SERVICE_INFO_SPLITER + serviceName, StringUtils.join(clusters, ",")));
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Instance selectOneHealthyInstance(String serviceName, String groupName, List<String> clusters, boolean subscribe) throws NacosException {
if (subscribe) {
return Balancer.RandomByWeight.selectHost(
hostReactor.getServiceInfo(NamingUtils.getGroupedName(serviceName, groupName), StringUtils.join(clusters, ",")));
} else {
return Balancer.RandomByWeight.selectHost(
hostReactor.getServiceInfoDirectlyFromServer(NamingUtils.getGroupedName(serviceName, groupName), StringUtils.join(clusters, ",")));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException {
Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral));
List<Instance> currentIPs = service.allIPs(ephemeral);
Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size());
for (Instance instance : currentIPs) {
currentInstances.put(instance.toIPAddr(), instance);
}
Map<String, Instance> instanceMap = null;
if (datum != null) {
instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances);
}
for (Instance instance : ips) {
if (!service.getClusterMap().containsKey(instance.getClusterName())) {
Cluster cluster = new Cluster(instance.getClusterName(), service);
cluster.init();
service.getClusterMap().put(instance.getClusterName(), cluster);
Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.",
instance.getClusterName(), instance.toJSON());
}
if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) {
instanceMap.remove(instance.getDatumKey());
} else {
instanceMap.put(instance.getDatumKey(), instance);
}
}
if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) {
throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: "
+ JSON.toJSONString(instanceMap.values()));
}
return new ArrayList<>(instanceMap.values());
}
#location 29
#vulnerability type NULL_DEREFERENCE | #fixed code
public List<Instance> updateIpAddresses(Service service, String action, boolean ephemeral, Instance... ips) throws NacosException {
Datum datum = consistencyService.get(KeyBuilder.buildInstanceListKey(service.getNamespaceId(), service.getName(), ephemeral));
List<Instance> currentIPs = service.allIPs(ephemeral);
Map<String, Instance> currentInstances = new HashMap<>(currentIPs.size());
for (Instance instance : currentIPs) {
currentInstances.put(instance.toIPAddr(), instance);
}
Map<String, Instance> instanceMap;
if (datum != null) {
instanceMap = setValid(((Instances) datum.value).getInstanceList(), currentInstances);
} else {
instanceMap = new HashMap<>(ips.length);
}
for (Instance instance : ips) {
if (!service.getClusterMap().containsKey(instance.getClusterName())) {
Cluster cluster = new Cluster(instance.getClusterName(), service);
cluster.init();
service.getClusterMap().put(instance.getClusterName(), cluster);
Loggers.SRV_LOG.warn("cluster: {} not found, ip: {}, will create new cluster with default configuration.",
instance.getClusterName(), instance.toJSON());
}
if (UtilsAndCommons.UPDATE_INSTANCE_ACTION_REMOVE.equals(action)) {
instanceMap.remove(instance.getDatumKey());
} else {
instanceMap.put(instance.getDatumKey(), instance);
}
}
if (instanceMap.size() <= 0 && UtilsAndCommons.UPDATE_INSTANCE_ACTION_ADD.equals(action)) {
throw new IllegalArgumentException("ip list can not be empty, service: " + service.getName() + ", ip list: "
+ JSON.toJSONString(instanceMap.values()));
}
return new ArrayList<>(instanceMap.values());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@RequestMapping("/updateClusterConf")
public JSONObject updateClusterConf(HttpServletRequest request) throws IOException {
JSONObject result = new JSONObject();
String ipSpliter = ",";
String ips = BaseServlet.optional(request, "ips", "");
String action = BaseServlet.required(request, "action");
if (SwitchEntry.ACTION_ADD.equals(action)) {
List<String> oldList =
IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "UTF-8"));
StringBuilder sb = new StringBuilder();
for (String ip : oldList) {
sb.append(ip).append("\r\n");
}
for (String ip : ips.split(ipSpliter)) {
sb.append(ip).append("\r\n");
}
Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString());
IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8");
return result;
}
if (SwitchEntry.ACTION_REPLACE.equals(action)) {
StringBuilder sb = new StringBuilder();
for (String ip : ips.split(ipSpliter)) {
sb.append(ip).append("\r\n");
}
Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString());
IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8");
return result;
}
if (SwitchEntry.ACTION_DELETE.equals(action)) {
Set<String> removeIps = new HashSet<>();
for (String ip : ips.split(ipSpliter)) {
removeIps.add(ip);
}
List<String> oldList =
IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8"));
Iterator<String> iterator = oldList.iterator();
while (iterator.hasNext()) {
String ip = iterator.next();
if (removeIps.contains(ip)) {
iterator.remove();
}
}
StringBuilder sb = new StringBuilder();
for (String ip : oldList) {
sb.append(ip).append("\r\n");
}
IoUtils.writeStringToFile(new File(UtilsAndCommons.getConfFile()), sb.toString(), "utf-8");
return result;
}
if (SwitchEntry.ACTION_VIEW.equals(action)) {
List<String> oldList =
IoUtils.readLines(new InputStreamReader(new FileInputStream(UtilsAndCommons.getConfFile()), "utf-8"));
result.put("list", oldList);
return result;
}
throw new InvalidParameterException("action is not qualified, action: " + action);
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
@RequestMapping("/updateClusterConf")
public JSONObject updateClusterConf(HttpServletRequest request) throws IOException {
JSONObject result = new JSONObject();
String ipSpliter = ",";
String ips = BaseServlet.optional(request, "ips", "");
String action = BaseServlet.required(request, "action");
if (SwitchEntry.ACTION_ADD.equals(action)) {
List<String> oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8");
StringBuilder sb = new StringBuilder();
for (String ip : oldList) {
sb.append(ip).append("\r\n");
}
for (String ip : ips.split(ipSpliter)) {
sb.append(ip).append("\r\n");
}
Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString());
FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8");
return result;
}
if (SwitchEntry.ACTION_REPLACE.equals(action)) {
StringBuilder sb = new StringBuilder();
for (String ip : ips.split(ipSpliter)) {
sb.append(ip).append("\r\n");
}
Loggers.SRV_LOG.info("UPDATE-CLUSTER", "new ips:" + sb.toString());
FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8");
return result;
}
if (SwitchEntry.ACTION_DELETE.equals(action)) {
Set<String> removeIps = new HashSet<>();
for (String ip : ips.split(ipSpliter)) {
removeIps.add(ip);
}
List<String> oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8");
Iterator<String> iterator = oldList.iterator();
while (iterator.hasNext()) {
String ip = iterator.next();
if (removeIps.contains(ip)) {
iterator.remove();
}
}
StringBuilder sb = new StringBuilder();
for (String ip : oldList) {
sb.append(ip).append("\r\n");
}
FileUtils.writeStringToFile(UtilsAndCommons.getConfFile(), sb.toString(), "UTF-8");
return result;
}
if (SwitchEntry.ACTION_VIEW.equals(action)) {
List<String> oldList = FileUtils.readLines(UtilsAndCommons.getConfFile(), "UTF-8");
result.put("list", oldList);
return result;
}
throw new InvalidParameterException("action is not qualified, action: " + action);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void initNamespace(Properties properties) {
String namespaceTmp = null;
String isUseCloudNamespaceParsing =
properties.getProperty(PropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
System.getProperty(SystemPropertyKeyConst.IS_USE_CLOUD_NAMESPACE_PARSING,
String.valueOf(Constants.DEFAULT_USE_CLOUD_NAMESPACE_PARSING)));
if (Boolean.parseBoolean(isUseCloudNamespaceParsing)) {
namespaceTmp = TemplateUtils.stringBlankAndThenExecute(namespaceTmp, new Callable<String>() {
@Override
public String call() {
return TenantUtil.getUserTenantForAcm();
}
});
namespaceTmp = TemplateUtils.stringBlankAndThenExecute(namespaceTmp, new Callable<String>() {
@Override
public String call() {
String namespace = System.getenv(PropertyKeyConst.SystemEnv.ALIBABA_ALIWARE_NAMESPACE);
return StringUtils.isNotBlank(namespace) ? namespace : EMPTY;
}
});
}
if (StringUtils.isBlank(namespaceTmp)) {
namespaceTmp = properties.getProperty(PropertyKeyConst.NAMESPACE);
}
namespace = StringUtils.isNotBlank(namespaceTmp) ? namespaceTmp.trim() : EMPTY;
properties.put(PropertyKeyConst.NAMESPACE, namespace);
}
#location 29
#vulnerability type NULL_DEREFERENCE | #fixed code
private void initNamespace(Properties properties) {
namespace = ParamUtil.parseNamespace(properties);
properties.put(PropertyKeyConst.NAMESPACE, namespace);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void subTypes() throws Exception {
VCard vcard = new VCard();
//one sub type
AddressType adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
vcard.addAddress(adr);
//two types
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
vcard.addAddress(adr);
//three types
//make sure it properly escapes sub type values that have special chars
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
adr.getSubTypes().put("TEXT", "123 \"Main\" St\r\nAustin, ;TX; 12345");
vcard.addAddress(adr);
//2.1
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1, null);
vcw.setAddProdId(false);
vcw.write(vcard);
String actual = sw.toString();
StringBuilder sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:2.1\r\n");
sb.append("ADR;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR;LANGUAGE=es;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR;LANGUAGE=es;TEXT=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\";X-DOORMAN=true:;;;;;;\r\n");
sb.append("END:VCARD\r\n");
String expected = sb.toString();
assertEquals(expected, actual);
//3.0
sw = new StringWriter();
vcw = new VCardWriter(sw, VCardVersion.V3_0, null);
vcw.setAddProdId(false);
vcw.write(vcard);
actual = sw.toString();
sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:3.0\r\n");
sb.append("ADR;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR,es;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR,es;TEXT=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\";X-DOORMAN=true:;;;;;;\r\n");
sb.append("END:VCARD\r\n");
expected = sb.toString();
assertEquals(expected, actual);
}
#location 30
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void subTypes() throws Exception {
VCard vcard = new VCard();
//one sub type
AddressType adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
vcard.addAddress(adr);
//two types
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
vcard.addAddress(adr);
//three types
//make sure it properly escapes sub type values that have special chars
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
adr.getSubTypes().put("TEXT", "123 \"Main\" St\r\nAustin, ;TX; 12345");
vcard.addAddress(adr);
//2.1
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1, null, "\r\n");
vcw.setAddProdId(false);
vcw.write(vcard);
String actual = sw.toString();
StringBuilder sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:2.1\r\n");
sb.append("ADR;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR;LANGUAGE=es;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR;LANGUAGE=es;TEXT=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\";X-DOORMAN=true:;;;;;;\r\n");
sb.append("END:VCARD\r\n");
String expected = sb.toString();
assertEquals(expected, actual);
//3.0
sw = new StringWriter();
vcw = new VCardWriter(sw, VCardVersion.V3_0, null, "\r\n");
vcw.setAddProdId(false);
vcw.write(vcard);
actual = sw.toString();
sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:3.0\r\n");
sb.append("ADR;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR,es;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR,es;TEXT=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\";X-DOORMAN=true:;;;;;;\r\n");
sb.append("END:VCARD\r\n");
expected = sb.toString();
assertEquals(expected, actual);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void evolutionVCard() throws Exception {
VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("John_Doe_EVOLUTION.vcf")));
reader.setCompatibilityMode(CompatibilityMode.EVOLUTION);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType t = it.next();
assertEquals("http://www.ibm.com", t.getValue());
assertEquals("0abc9b8d-0845-47d0-9a91-3db5bb74620d", t.getSubTypes().getFirst("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType t = it.next();
assertEquals("905-666-1234", t.getValue());
Set<TelephoneTypeParameter> types = t.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertEquals("c2fa1caa-2926-4087-8971-609cfc7354ce", t.getSubTypes().getFirst("X-COUCHDB-UUID"));
t = it.next();
assertEquals("905-555-1234", t.getValue());
types = t.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertEquals("fbfb2722-4fd8-4dbf-9abd-eeb24072fd8e", t.getSubTypes().getFirst("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
}
//UID
{
UidType t = vcard.getUid();
assertEquals("477343c8e6bf375a9bac1f96a5000837", t.getValue());
}
//N
{
StructuredNameType t = vcard.getStructuredName();
assertEquals("Doe", t.getFamily());
assertEquals("John", t.getGiven());
List<String> list = t.getAdditional();
assertEquals(Arrays.asList("Richter, James"), list);
list = t.getPrefixes();
assertEquals(Arrays.asList("Mr."), list);
list = t.getSuffixes();
assertEquals(Arrays.asList("Sr."), list);
}
//FN
{
FormattedNameType t = vcard.getFormattedName();
assertEquals("Mr. John Richter, James Doe Sr.", t.getValue());
}
//NICKNAME
{
NicknameType t = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), t.getValues());
}
//ORG
{
OrganizationType t = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting", "Dungeon"), t.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType t = it.next();
assertEquals("Money Counter", t.getValue());
assertFalse(it.hasNext());
}
//CATEGORIES
{
CategoriesType t = vcard.getCategories();
assertEquals(Arrays.asList("VIP"), t.getValues());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType t = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", t.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType t = it.next();
assertEquals("[email protected]", t.getValue());
Set<EmailTypeParameter> types = t.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(new EmailTypeParameter("work"))); //non-standard type
assertEquals("83a75a5d-2777-45aa-bab5-76a4bd972490", t.getSubTypes().getFirst("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType t = it.next();
assertEquals("ASB-123", t.getPoBox());
assertEquals(null, t.getExtendedAddress());
assertEquals("15 Crescent moon drive", t.getStreetAddress());
assertEquals("Albaney", t.getLocality());
assertEquals("New York", t.getRegion());
assertEquals("12345", t.getPostalCode());
//the space between "United" and "States" is lost because it was included with the folding character and ignored (see .vcf file)
assertEquals("UnitedStates of America", t.getCountry());
Set<AddressTypeParameter> types = t.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType t = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 22);
Date expected = c.getTime();
assertEquals(expected, t.getDate());
}
//REV
{
RevisionType t = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 5);
c.set(Calendar.HOUR_OF_DAY, 13);
c.set(Calendar.MINUTE, 32);
c.set(Calendar.SECOND, 54);
assertEquals(c.getTime(), t.getTimestamp());
}
//extended types
{
assertEquals(7, countExtTypes(vcard));
Iterator<RawType> it = vcard.getExtendedType("X-COUCHDB-APPLICATION-ANNOTATIONS").iterator();
RawType t = it.next();
assertEquals("X-COUCHDB-APPLICATION-ANNOTATIONS", t.getTypeName());
assertEquals("{\"Evolution\":{\"revision\":\"2012-03-05T13:32:54Z\"}}", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedType("X-AIM").iterator();
t = it.next();
assertEquals("X-AIM", t.getTypeName());
assertEquals("[email protected]", t.getValue());
assertEquals("HOME", t.getSubTypes().getType());
assertEquals("cb9e11fc-bb97-4222-9cd8-99820c1de454", t.getSubTypes().getFirst("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
it = vcard.getExtendedType("X-EVOLUTION-FILE-AS").iterator();
t = it.next();
assertEquals("X-EVOLUTION-FILE-AS", t.getTypeName());
assertEquals("Doe\\, John", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedType("X-EVOLUTION-SPOUSE").iterator();
t = it.next();
assertEquals("X-EVOLUTION-SPOUSE", t.getTypeName());
assertEquals("Maria", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedType("X-EVOLUTION-MANAGER").iterator();
t = it.next();
assertEquals("X-EVOLUTION-MANAGER", t.getTypeName());
assertEquals("Big Blue", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedType("X-EVOLUTION-ASSISTANT").iterator();
t = it.next();
assertEquals("X-EVOLUTION-ASSISTANT", t.getTypeName());
assertEquals("Little Red", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedType("X-EVOLUTION-ANNIVERSARY").iterator();
t = it.next();
assertEquals("X-EVOLUTION-ANNIVERSARY", t.getTypeName());
assertEquals("1980-03-22", t.getValue());
assertFalse(it.hasNext());
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void evolutionVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_EVOLUTION.vcf"));
reader.setCompatibilityMode(CompatibilityMode.EVOLUTION);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType t = it.next();
assertEquals("http://www.ibm.com", t.getValue());
assertEquals("0abc9b8d-0845-47d0-9a91-3db5bb74620d", t.getSubTypes().getFirst("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType t = it.next();
assertEquals("905-666-1234", t.getValue());
Set<TelephoneTypeParameter> types = t.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertEquals("c2fa1caa-2926-4087-8971-609cfc7354ce", t.getSubTypes().getFirst("X-COUCHDB-UUID"));
t = it.next();
assertEquals("905-555-1234", t.getValue());
types = t.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertEquals("fbfb2722-4fd8-4dbf-9abd-eeb24072fd8e", t.getSubTypes().getFirst("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
}
//UID
{
UidType t = vcard.getUid();
assertEquals("477343c8e6bf375a9bac1f96a5000837", t.getValue());
}
//N
{
StructuredNameType t = vcard.getStructuredName();
assertEquals("Doe", t.getFamily());
assertEquals("John", t.getGiven());
List<String> list = t.getAdditional();
assertEquals(Arrays.asList("Richter, James"), list);
list = t.getPrefixes();
assertEquals(Arrays.asList("Mr."), list);
list = t.getSuffixes();
assertEquals(Arrays.asList("Sr."), list);
}
//FN
{
FormattedNameType t = vcard.getFormattedName();
assertEquals("Mr. John Richter, James Doe Sr.", t.getValue());
}
//NICKNAME
{
NicknameType t = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), t.getValues());
}
//ORG
{
OrganizationType t = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting", "Dungeon"), t.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType t = it.next();
assertEquals("Money Counter", t.getValue());
assertFalse(it.hasNext());
}
//CATEGORIES
{
CategoriesType t = vcard.getCategories();
assertEquals(Arrays.asList("VIP"), t.getValues());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType t = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", t.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType t = it.next();
assertEquals("[email protected]", t.getValue());
Set<EmailTypeParameter> types = t.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(new EmailTypeParameter("work"))); //non-standard type
assertEquals("83a75a5d-2777-45aa-bab5-76a4bd972490", t.getSubTypes().getFirst("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType t = it.next();
assertEquals("ASB-123", t.getPoBox());
assertEquals(null, t.getExtendedAddress());
assertEquals("15 Crescent moon drive", t.getStreetAddress());
assertEquals("Albaney", t.getLocality());
assertEquals("New York", t.getRegion());
assertEquals("12345", t.getPostalCode());
//the space between "United" and "States" is lost because it was included with the folding character and ignored (see .vcf file)
assertEquals("UnitedStates of America", t.getCountry());
Set<AddressTypeParameter> types = t.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType t = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 22);
Date expected = c.getTime();
assertEquals(expected, t.getDate());
}
//REV
{
RevisionType t = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 5);
c.set(Calendar.HOUR_OF_DAY, 13);
c.set(Calendar.MINUTE, 32);
c.set(Calendar.SECOND, 54);
assertEquals(c.getTime(), t.getTimestamp());
}
//extended types
{
assertEquals(7, countExtTypes(vcard));
Iterator<RawType> it = vcard.getExtendedType("X-COUCHDB-APPLICATION-ANNOTATIONS").iterator();
RawType t = it.next();
assertEquals("X-COUCHDB-APPLICATION-ANNOTATIONS", t.getTypeName());
assertEquals("{\"Evolution\":{\"revision\":\"2012-03-05T13:32:54Z\"}}", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedType("X-AIM").iterator();
t = it.next();
assertEquals("X-AIM", t.getTypeName());
assertEquals("[email protected]", t.getValue());
assertEquals("HOME", t.getSubTypes().getType());
assertEquals("cb9e11fc-bb97-4222-9cd8-99820c1de454", t.getSubTypes().getFirst("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
it = vcard.getExtendedType("X-EVOLUTION-FILE-AS").iterator();
t = it.next();
assertEquals("X-EVOLUTION-FILE-AS", t.getTypeName());
assertEquals("Doe\\, John", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedType("X-EVOLUTION-SPOUSE").iterator();
t = it.next();
assertEquals("X-EVOLUTION-SPOUSE", t.getTypeName());
assertEquals("Maria", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedType("X-EVOLUTION-MANAGER").iterator();
t = it.next();
assertEquals("X-EVOLUTION-MANAGER", t.getTypeName());
assertEquals("Big Blue", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedType("X-EVOLUTION-ASSISTANT").iterator();
t = it.next();
assertEquals("X-EVOLUTION-ASSISTANT", t.getTypeName());
assertEquals("Little Red", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedType("X-EVOLUTION-ANNIVERSARY").iterator();
t = it.next();
assertEquals("X-EVOLUTION-ANNIVERSARY", t.getTypeName());
assertEquals("1980-03-22", t.getValue());
assertFalse(it.hasNext());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void subTypes() throws Exception {
VCard vcard = new VCard();
//one sub type
AddressType adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
vcard.addAddress(adr);
//two types
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
vcard.addAddress(adr);
//three types
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
adr.getSubTypes().put("X-PARKING", "10");
vcard.addAddress(adr);
//2.1
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1);
vcw.setAddGenerator(false);
vcw.write(vcard);
String actual = sw.toString();
StringBuilder sb = new StringBuilder();
sb.append("BEGIN: vcard\r\n");
sb.append("VERSION: 2.1\r\n");
sb.append("ADR;X-DOORMAN=true: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR;X-PARKING=10: ;;;;;;\r\n");
sb.append("END: vcard\r\n");
String expected = sb.toString();
assertEquals(expected, actual);
//3.0
sw = new StringWriter();
vcw = new VCardWriter(sw, VCardVersion.V3_0);
vcw.setAddGenerator(false);
vcw.write(vcard);
actual = sw.toString();
sb = new StringBuilder();
sb.append("BEGIN: vcard\r\n");
sb.append("VERSION: 3.0\r\n");
sb.append("ADR;X-DOORMAN=true: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es,FR: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es,FR;X-PARKING=10: ;;;;;;\r\n");
sb.append("END: vcard\r\n");
expected = sb.toString();
assertEquals(expected, actual);
}
#location 29
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void subTypes() throws Exception {
VCard vcard = new VCard();
//one sub type
AddressType adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
vcard.addAddress(adr);
//two types
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
vcard.addAddress(adr);
//three types
//make sure it properly escapes sub type values that have special chars
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
adr.getSubTypes().put("LABEL", "123 \"Main\" St\r\nAustin, ;TX; 12345");
vcard.addAddress(adr);
//2.1
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1, null);
vcw.setAddGenerator(false);
vcw.write(vcard);
String actual = sw.toString();
StringBuilder sb = new StringBuilder();
sb.append("BEGIN: vcard\r\n");
sb.append("VERSION: 2.1\r\n");
sb.append("ADR;X-DOORMAN=true: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR;LABEL=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\": ;;;;;;\r\n");
sb.append("END: vcard\r\n");
String expected = sb.toString();
assertEquals(expected, actual);
//3.0
sw = new StringWriter();
vcw = new VCardWriter(sw, VCardVersion.V3_0, null);
vcw.setAddGenerator(false);
vcw.write(vcard);
actual = sw.toString();
sb = new StringBuilder();
sb.append("BEGIN: vcard\r\n");
sb.append("VERSION: 3.0\r\n");
sb.append("ADR;X-DOORMAN=true: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es,FR: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es,FR;LABEL=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\": ;;;;;;\r\n");
sb.append("END: vcard\r\n");
expected = sb.toString();
assertEquals(expected, actual);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
VCard vcard = new VCard();
StructuredNameType n = new StructuredNameType();
n.setFamily("Angstadt");
n.setGiven("Michael");
n.addPrefix("Mr");
vcard.setStructuredName(n);
vcard.setFormattedName(new FormattedNameType("Michael Angstadt"));
EmailType email = new EmailType("[email protected]");
email.addType(EmailTypeParameter.HOME);
vcard.addEmail(email);
TelephoneType tel = new TelephoneType("+1 555-555-1234");
tel.addType(TelephoneTypeParameter.CELL);
vcard.addTelephoneNumber(tel);
tel = new TelephoneType("+1 555-555-9876");
tel.addType(TelephoneTypeParameter.HOME);
vcard.addTelephoneNumber(tel);
UrlType url = new UrlType("http://mikeangstadt.name");
url.setType("home");
vcard.addUrl(url);
url = new UrlType("http://code.google.com/p/ez-vcard");
url.setType("work");
vcard.addUrl(url);
CategoriesType categories = new CategoriesType();
categories.addValue("Java software engineer");
categories.addValue("vCard expert");
categories.addValue("Nice guy");
vcard.setCategories(categories);
vcard.setGeo(new GeoType(39.95, 75.1667));
NicknameType nickname = new NicknameType();
nickname.addValue("Mike");
vcard.setNickname(nickname);
vcard.setTimezone(new TimezoneType(-5, 0, "America/New_York"));
File profile = new File("portrait.jpg");
byte data[] = new byte[(int) profile.length()];
InputStream in = new FileInputStream(profile);
in.read(data);
in.close();
PhotoType photo = new PhotoType(data, ImageTypeParameter.JPEG);
vcard.addPhoto(photo);
//vcard.setUid(UidType.random());
vcard.setUid(new UidType("urn:uuid:dd418720-c754-4631-a869-db89d02b831b"));
vcard.addSource(new SourceType("http://mikeangstadt.name/mike-angstadt.vcf"));
vcard.setRevision(new RevisionType(new Date()));
vcard.setVersion(VCardVersion.V3_0);
vcard.write(new File("mike-angstadt.vcf"));
}
#location 63
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception {
VCard vcard = new VCard();
StructuredNameType n = new StructuredNameType();
n.setFamily("Angstadt");
n.setGiven("Michael");
n.addPrefix("Mr");
vcard.setStructuredName(n);
vcard.setFormattedName(new FormattedNameType("Michael Angstadt"));
NicknameType nickname = new NicknameType();
nickname.addValue("Mike");
vcard.setNickname(nickname);
vcard.addTitle(new TitleType("Software Engineer"));
EmailType email = new EmailType("[email protected]");
vcard.addEmail(email);
UrlType url = new UrlType("http://mikeangstadt.name");
vcard.addUrl(url);
CategoriesType categories = new CategoriesType();
categories.addValue("Java software engineer");
categories.addValue("vCard expert");
categories.addValue("Nice guy!!");
vcard.setCategories(categories);
vcard.setGeo(new GeoType(39.95, -75.1667));
vcard.setTimezone(new TimezoneType(-5, 0, "America/New_York"));
byte portrait[] = getFileBytes("portrait.jpg");
PhotoType photo = new PhotoType(portrait, ImageTypeParameter.JPEG);
vcard.addPhoto(photo);
byte pronunciation[] = getFileBytes("pronunciation.ogg");
SoundType sound = new SoundType(pronunciation, SoundTypeParameter.OGG);
vcard.addSound(sound);
//vcard.setUid(UidType.random());
vcard.setUid(new UidType("urn:uuid:dd418720-c754-4631-a869-db89d02b831b"));
vcard.addSource(new SourceType("http://mikeangstadt.name/mike-angstadt.vcf"));
vcard.setRevision(new RevisionType(new Date()));
//write vCard to file
Writer writer = new FileWriter("mike-angstadt.vcf");
VCardWriter vcw = new VCardWriter(writer, VCardVersion.V3_0);
vcw.write(vcard);
List<String> warnings = vcw.getWarnings();
System.out.println("Completed with " + warnings.size() + " warnings.");
for (String warning : warnings) {
System.out.println("* " + warning);
}
writer.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void test() throws Exception {
VCard vcard = new VCard();
StructuredNameType n = new StructuredNameType();
n.setGiven("Michael");
n.setFamily("Angstadt");
vcard.setStructuredName(n);
FormattedNameType fn = new FormattedNameType("Michael Angstadt");
vcard.setFormattedName(fn);
PhotoType photo = new PhotoType();
photo.setUrl("http://example.com/image.jpg");
vcard.getPhotos().add(photo);
VCardWriter vcw = new VCardWriter(new OutputStreamWriter(System.out));
vcw.write(vcard);
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void test() throws Exception {
VCard vcard = new VCard();
StructuredNameType n = new StructuredNameType();
n.setGiven("Michael");
n.setFamily("Angstadt");
vcard.setStructuredName(n);
FormattedNameType fn = new FormattedNameType("Michael Angstadt");
vcard.setFormattedName(fn);
PhotoType photo = new PhotoType();
photo.setUrl("http://example.com/image.jpg");
vcard.getPhotos().add(photo);
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1);
vcw.write(vcard);
System.out.println(sw.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void doUnmarshalValue() throws Exception {
//Note: Marshalling of 2.1 AGENT types is tested in VCardWriterTest
VCardVersion version = VCardVersion.V3_0;
List<String> warnings = new ArrayList<String>();
CompatibilityMode compatibilityMode = CompatibilityMode.RFC;
VCardSubTypes subTypes = new VCardSubTypes();
AgentType t;
//@formatter:off
StringBuilder sb = new StringBuilder();
sb.append("BEGIN: VCARD\\n");
sb.append("VERSION: 3.0\\n");
sb.append("FN: Agent 007\\n");
sb.append("EMAIL\\;TYPE=internet: [email protected]\\n");
sb.append("AGENT: ");
sb.append("BEGIN: VCARD\\\\n");
sb.append("VERSION: 3.0\\\\n");
sb.append("FN: Agent 009\\\\n");
sb.append("EMAIL\\\\\\;TYPE=internet: [email protected]\\\\n");
sb.append("END: VCARD\\\\n\\n");
sb.append("END: VCARD\\n");
//@formatter:on
t = new AgentType();
t.unmarshalValue(subTypes, sb.toString(), version, warnings, compatibilityMode);
VCard agent1 = t.getVcard();
assertEquals("Agent 007", agent1.getFormattedName().getValue());
assertEquals("[email protected]", agent1.getEmails().get(0).getValue());
assertTrue(agent1.getEmails().get(0).getTypes().contains(EmailTypeParameter.INTERNET));
VCard agent2 = agent1.getAgent().getVcard();
assertEquals("Agent 009", agent2.getFormattedName().getValue());
assertEquals("[email protected]", agent2.getEmails().get(0).getValue());
assertTrue(agent2.getEmails().get(0).getTypes().contains(EmailTypeParameter.INTERNET));
}
#location 29
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void doUnmarshalValue() throws Exception {
VCardVersion version = VCardVersion.V3_0;
List<String> warnings = new ArrayList<String>();
CompatibilityMode compatibilityMode = CompatibilityMode.RFC;
VCardSubTypes subTypes;
AgentType t;
//with URL
t = new AgentType();
subTypes = new VCardSubTypes();
subTypes.setValue(ValueParameter.URL);
t.unmarshalValue(subTypes, "http://mi5.co.uk/007", version, warnings, compatibilityMode);
assertEquals("http://mi5.co.uk/007", t.getUrl());
assertNull(t.getVcard());
//with vCard
VCard vcard = new VCard();
t = new AgentType();
subTypes = new VCardSubTypes();
try {
t.unmarshalValue(subTypes, "BEGIN:VCARD\\nEND:VCARD", version, warnings, compatibilityMode);
fail();
} catch (EmbeddedVCardException e) {
//should be thrown
e.injectVCard(vcard);
}
assertNull(t.getUrl());
assertEquals(vcard, t.getVcard());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void msOutlookVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MS_OUTLOOK.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V2_1, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("en-us", f.getSubTypes().getLanguage());
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter", "James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter James Doe Sr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY GEORGE EL-HADDAD ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GEORGE EL-HADDAD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", f.getValue());
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("(905) 555-1234", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(905) 666-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Cresent moon drive", f.getStreetAddress());
assertEquals("Albaney", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
assertEquals("Cresent moon drive\r\nAlbaney, New York 12345", f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertTrue(types.contains(AddressTypeParameter.PREF));
f = it.next();
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Silicon Alley 5,", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
assertEquals("Silicon Alley 5,\r\nNew York, New York 12345", f.getLabel());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertFalse(it.hasNext());
}
//LABEL
{
assertTrue(vcard.getOrphanedLabels().isEmpty());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("Counting Money", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 22);
assertEquals(c.getTime(), f.getDate());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.PREF));
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(860, f.getData().length);
assertFalse(it.hasNext());
}
//REV
{
RevisionType f = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 5);
c.set(Calendar.HOUR_OF_DAY, 13);
c.set(Calendar.MINUTE, 19);
c.set(Calendar.SECOND, 33);
assertEquals(c.getTime(), f.getTimestamp());
}
//extended types
{
assertEquals(6, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0);
assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName());
assertEquals("2", f.getValue());
f = vcard.getExtendedProperties("X-MS-ANNIVERSARY").get(0);
assertEquals("X-MS-ANNIVERSARY", f.getTypeName());
assertEquals("20110113", f.getValue());
f = vcard.getExtendedProperties("X-MS-IMADDRESS").get(0);
assertEquals("X-MS-IMADDRESS", f.getTypeName());
assertEquals("[email protected]", f.getValue());
f = vcard.getExtendedProperties("X-MS-OL-DESIGN").get(0);
assertEquals("X-MS-OL-DESIGN", f.getTypeName());
assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue());
assertEquals("utf-8", f.getSubTypes().getCharset());
f = vcard.getExtendedProperties("X-MS-MANAGER").get(0);
assertEquals("X-MS-MANAGER", f.getTypeName());
assertEquals("Big Blue", f.getValue());
f = vcard.getExtendedProperties("X-MS-ASSISTANT").get(0);
assertEquals("X-MS-ASSISTANT", f.getTypeName());
assertEquals("Jenny", f.getValue());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void msOutlookVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MS_OUTLOOK.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V2_1, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("en-us", f.getSubTypes().getLanguage());
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter", "James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter James Doe Sr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY GEORGE EL-HADDAD ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GEORGE EL-HADDAD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", f.getValue());
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("(905) 555-1234", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(905) 666-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Cresent moon drive", f.getStreetAddress());
assertEquals("Albaney", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
assertEquals("Cresent moon drive\r\nAlbaney, New York 12345", f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertTrue(types.contains(AddressTypeParameter.PREF));
f = it.next();
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Silicon Alley 5,", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
assertEquals("Silicon Alley 5,\r\nNew York, New York 12345", f.getLabel());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertFalse(it.hasNext());
}
//LABEL
{
assertTrue(vcard.getOrphanedLabels().isEmpty());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("Counting Money", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 22);
assertEquals(c.getTime(), f.getDate());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.PREF));
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(860, f.getData().length);
assertFalse(it.hasNext());
}
//REV
{
RevisionType f = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 5);
c.set(Calendar.HOUR_OF_DAY, 13);
c.set(Calendar.MINUTE, 19);
c.set(Calendar.SECOND, 33);
assertEquals(c.getTime(), f.getTimestamp());
}
//extended types
{
assertEquals(6, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0);
assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName());
assertEquals("2", f.getValue());
f = vcard.getExtendedProperties("X-MS-ANNIVERSARY").get(0);
assertEquals("X-MS-ANNIVERSARY", f.getTypeName());
assertEquals("20110113", f.getValue());
f = vcard.getExtendedProperties("X-MS-IMADDRESS").get(0);
assertEquals("X-MS-IMADDRESS", f.getTypeName());
assertEquals("[email protected]", f.getValue());
f = vcard.getExtendedProperties("X-MS-OL-DESIGN").get(0);
assertEquals("X-MS-OL-DESIGN", f.getTypeName());
assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue());
assertEquals("utf-8", f.getSubTypes().getCharset());
f = vcard.getExtendedProperties("X-MS-MANAGER").get(0);
assertEquals("X-MS-MANAGER", f.getTypeName());
assertEquals("Big Blue", f.getValue());
f = vcard.getExtendedProperties("X-MS-ASSISTANT").get(0);
assertEquals("X-MS-ASSISTANT", f.getTypeName());
assertEquals("Jenny", f.getValue());
}
assertWarnings(0, reader.getWarnings());
assertNull(reader.readNext());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void lotusNotesVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_LOTUS_NOTES.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//PRODID
{
ProdIdType f = vcard.getProdId();
assertEquals("-//Apple Inc.//Address Book 6.1//EN", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Johny"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("I"), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. Doe John I Johny", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny,JayJay"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "SUN"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Generic Accountant", f.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("WORK")));
assertTrue(types.contains(EmailTypeParameter.PREF));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("WORK")));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("+1 (212) 204-34456", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertTrue(types.contains(TelephoneTypeParameter.PREF));
f = it.next();
assertEquals("00-1-212-555-7777", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals("item1", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("25334" + NEWLINE + "South cresent drive, Building 5, 3rd floo r", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("NYC887", f.getPostalCode());
assertEquals("U.S.A.", f.getCountry());
assertNull(f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PREF));
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" + NEWLINE + "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO , THE" + NEWLINE + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR P URPOSE" + NEWLINE + "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTOR S BE" + NEWLINE + "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" + NEWLINE + "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" + NEWLINE + " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS " + NEWLINE + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" + NEWLINE + " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)" + NEWLINE + "A RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" + NEWLINE + " POSSIBILITY OF SUCH DAMAGE.", f.getValue());
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("item2", f.getGroup());
assertEquals("http://www.sun.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MAY);
c.set(Calendar.DAY_OF_MONTH, 21);
assertEquals(c.getTime(), f.getDate());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(7957, f.getData().length);
assertFalse(it.hasNext());
}
//UID
{
UidType f = vcard.getUid();
assertEquals("0e7602cc-443e-4b82-b4b1-90f62f99a199", f.getValue());
}
//GEO
{
GeoType f = vcard.getGeo();
assertEquals(-2.6, f.getLatitude(), .01);
assertEquals(3.4, f.getLongitude(), .01);
}
//CLASS
{
ClassificationType f = vcard.getClassification();
assertEquals("Public", f.getValue());
}
//PROFILE
{
ProfileType f = vcard.getProfile();
assertEquals("VCard", f.getValue());
}
//TZ
{
TimezoneType f = vcard.getTimezone();
assertIntEquals(1, f.getHourOffset());
assertIntEquals(0, f.getMinuteOffset());
}
//LABEL
{
Iterator<LabelType> it = vcard.getOrphanedLabels().iterator();
LabelType f = it.next();
assertEquals("John Doe" + NEWLINE + "New York, NewYork," + NEWLINE + "South Crecent Drive," + NEWLINE + "Building 5, floor 3," + NEWLINE + "USA", f.getValue());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PARCEL));
assertTrue(types.contains(AddressTypeParameter.PREF));
assertFalse(it.hasNext());
}
//SORT-STRING
{
SortStringType f = vcard.getSortString();
assertEquals("JOHN", f.getValue());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("Counting Money", f.getValue());
assertFalse(it.hasNext());
}
//SOURCE
{
Iterator<SourceType> it = vcard.getSources().iterator();
SourceType f = it.next();
assertEquals("Whatever", f.getValue());
assertFalse(it.hasNext());
}
//MAILER
{
MailerType f = vcard.getMailer();
assertEquals("Mozilla Thunderbird", f.getValue());
}
//NAME
{
SourceDisplayTextType f = vcard.getSourceDisplayText();
assertEquals("VCard for John Doe", f.getValue());
}
//extended types
{
assertEquals(4, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-ABLABEL").get(0);
assertEquals("item2", f.getGroup());
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("_$!<HomePage>!$_", f.getValue());
f = vcard.getExtendedProperties("X-ABUID").get(0);
assertEquals("X-ABUID", f.getTypeName());
assertEquals("0E7602CC-443E-4B82-B4B1-90F62F99A199:ABPerson", f.getValue());
f = vcard.getExtendedProperties("X-GENERATOR").get(0);
assertEquals("X-GENERATOR", f.getTypeName());
assertEquals("Cardme Generator", f.getValue());
f = vcard.getExtendedProperties("X-LONG-STRING").get(0);
assertEquals("X-LONG-STRING", f.getTypeName());
assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", f.getValue());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void lotusNotesVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_LOTUS_NOTES.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//PRODID
{
ProdIdType f = vcard.getProdId();
assertEquals("-//Apple Inc.//Address Book 6.1//EN", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Johny"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("I"), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. Doe John I Johny", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny,JayJay"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "SUN"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Generic Accountant", f.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("WORK")));
assertTrue(types.contains(EmailTypeParameter.PREF));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("WORK")));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("+1 (212) 204-34456", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertTrue(types.contains(TelephoneTypeParameter.PREF));
f = it.next();
assertEquals("00-1-212-555-7777", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals("item1", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("25334" + NEWLINE + "South cresent drive, Building 5, 3rd floo r", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("NYC887", f.getPostalCode());
assertEquals("U.S.A.", f.getCountry());
assertNull(f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PREF));
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" + NEWLINE + "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO , THE" + NEWLINE + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR P URPOSE" + NEWLINE + "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTOR S BE" + NEWLINE + "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" + NEWLINE + "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" + NEWLINE + " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS " + NEWLINE + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" + NEWLINE + " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)" + NEWLINE + "A RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" + NEWLINE + " POSSIBILITY OF SUCH DAMAGE.", f.getValue());
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("item2", f.getGroup());
assertEquals("http://www.sun.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MAY);
c.set(Calendar.DAY_OF_MONTH, 21);
assertEquals(c.getTime(), f.getDate());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(7957, f.getData().length);
assertFalse(it.hasNext());
}
//UID
{
UidType f = vcard.getUid();
assertEquals("0e7602cc-443e-4b82-b4b1-90f62f99a199", f.getValue());
}
//GEO
{
GeoType f = vcard.getGeo();
assertEquals(-2.6, f.getLatitude(), .01);
assertEquals(3.4, f.getLongitude(), .01);
}
//CLASS
{
ClassificationType f = vcard.getClassification();
assertEquals("Public", f.getValue());
}
//PROFILE
{
ProfileType f = vcard.getProfile();
assertEquals("VCard", f.getValue());
}
//TZ
{
TimezoneType f = vcard.getTimezone();
assertIntEquals(1, f.getHourOffset());
assertIntEquals(0, f.getMinuteOffset());
}
//LABEL
{
Iterator<LabelType> it = vcard.getOrphanedLabels().iterator();
LabelType f = it.next();
assertEquals("John Doe" + NEWLINE + "New York, NewYork," + NEWLINE + "South Crecent Drive," + NEWLINE + "Building 5, floor 3," + NEWLINE + "USA", f.getValue());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PARCEL));
assertTrue(types.contains(AddressTypeParameter.PREF));
assertFalse(it.hasNext());
}
//SORT-STRING
{
SortStringType f = vcard.getSortString();
assertEquals("JOHN", f.getValue());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("Counting Money", f.getValue());
assertFalse(it.hasNext());
}
//SOURCE
{
Iterator<SourceType> it = vcard.getSources().iterator();
SourceType f = it.next();
assertEquals("Whatever", f.getValue());
assertFalse(it.hasNext());
}
//MAILER
{
MailerType f = vcard.getMailer();
assertEquals("Mozilla Thunderbird", f.getValue());
}
//NAME
{
SourceDisplayTextType f = vcard.getSourceDisplayText();
assertEquals("VCard for John Doe", f.getValue());
}
//extended types
{
assertEquals(4, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-ABLABEL").get(0);
assertEquals("item2", f.getGroup());
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("_$!<HomePage>!$_", f.getValue());
f = vcard.getExtendedProperties("X-ABUID").get(0);
assertEquals("X-ABUID", f.getTypeName());
assertEquals("0E7602CC-443E-4B82-B4B1-90F62F99A199:ABPerson", f.getValue());
f = vcard.getExtendedProperties("X-GENERATOR").get(0);
assertEquals("X-GENERATOR", f.getTypeName());
assertEquals("Cardme Generator", f.getValue());
f = vcard.getExtendedProperties("X-LONG-STRING").get(0);
assertEquals("X-LONG-STRING", f.getTypeName());
assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", f.getValue());
}
assertWarnings(0, reader.getWarnings());
assertNull(reader.readNext());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public T find(V value) {
return find(value, false, false);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public T find(V value) {
checkInit();
for (T obj : preDefined) {
if (matches(obj, value)) {
return obj;
}
}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void subTypes() throws Exception {
VCard vcard = new VCard();
//one sub type
AddressType adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
vcard.addAddress(adr);
//two types
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
vcard.addAddress(adr);
//three types
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
adr.getSubTypes().put("X-PARKING", "10");
vcard.addAddress(adr);
//2.1
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1);
vcw.setAddGenerator(false);
vcw.write(vcard);
String actual = sw.toString();
StringBuilder sb = new StringBuilder();
sb.append("BEGIN: vcard\r\n");
sb.append("VERSION: 2.1\r\n");
sb.append("ADR;X-DOORMAN=true: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR;X-PARKING=10: ;;;;;;\r\n");
sb.append("END: vcard\r\n");
String expected = sb.toString();
assertEquals(expected, actual);
//3.0
sw = new StringWriter();
vcw = new VCardWriter(sw, VCardVersion.V3_0);
vcw.setAddGenerator(false);
vcw.write(vcard);
actual = sw.toString();
sb = new StringBuilder();
sb.append("BEGIN: vcard\r\n");
sb.append("VERSION: 3.0\r\n");
sb.append("ADR;X-DOORMAN=true: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es,FR: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es,FR;X-PARKING=10: ;;;;;;\r\n");
sb.append("END: vcard\r\n");
expected = sb.toString();
assertEquals(expected, actual);
}
#location 29
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void subTypes() throws Exception {
VCard vcard = new VCard();
//one sub type
AddressType adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
vcard.addAddress(adr);
//two types
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
vcard.addAddress(adr);
//three types
//make sure it properly escapes sub type values that have special chars
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
adr.getSubTypes().put("LABEL", "123 \"Main\" St\r\nAustin, ;TX; 12345");
vcard.addAddress(adr);
//2.1
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1, null);
vcw.setAddGenerator(false);
vcw.write(vcard);
String actual = sw.toString();
StringBuilder sb = new StringBuilder();
sb.append("BEGIN: vcard\r\n");
sb.append("VERSION: 2.1\r\n");
sb.append("ADR;X-DOORMAN=true: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es;LANGUAGE=FR;LABEL=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\": ;;;;;;\r\n");
sb.append("END: vcard\r\n");
String expected = sb.toString();
assertEquals(expected, actual);
//3.0
sw = new StringWriter();
vcw = new VCardWriter(sw, VCardVersion.V3_0, null);
vcw.setAddGenerator(false);
vcw.write(vcard);
actual = sw.toString();
sb = new StringBuilder();
sb.append("BEGIN: vcard\r\n");
sb.append("VERSION: 3.0\r\n");
sb.append("ADR;X-DOORMAN=true: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es,FR: ;;;;;;\r\n");
sb.append("ADR;X-DOORMAN=true;LANGUAGE=es,FR;LABEL=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\": ;;;;;;\r\n");
sb.append("END: vcard\r\n");
expected = sb.toString();
assertEquals(expected, actual);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void doUnmarshalValue(String value, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) {
value = VCardStringUtils.unescape(value);
if (subTypes.getValue() != null) {
url = value;
} else {
VCardReader reader = new VCardReader(new StringReader(value));
reader.setCompatibilityMode(compatibilityMode);
try {
vcard = reader.readNext();
} catch (IOException e) {
//reading from a string
}
for (String w : reader.getWarnings()) {
warnings.add("AGENT unmarshal warning: " + w);
}
}
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
protected void doUnmarshalValue(String value, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) {
if (subTypes.getValue() != null) {
setUrl(VCardStringUtils.unescape(value));
} else {
//instruct the marshaller to look for an embedded vCard
throw new EmbeddedVCardException(new EmbeddedVCardException.InjectionCallback() {
public void injectVCard(VCard vcard) {
setVcard(vcard);
}
});
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void outlook2007VCard() throws Exception {
VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("outlook-2007.vcf")));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V2_1, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("en-us", f.getSubTypes().getLanguage());
assertEquals("Angstadt", f.getFamily());
assertEquals("Michael", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Jr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. Michael Angstadt Jr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Mike"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("TheCompany", "TheDepartment"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("TheJobTitle", f.getValue());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is the NOTE field \r\nI assume it encodes this text inside a NOTE vCard type.\r\nBut I'm not sure because there's text formatting going on here.\r\nIt does not preserve the formatting", f.getValue());
assertEquals("us-ascii", f.getSubTypes().getCharset());
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("(111) 555-1111", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(111) 555-2222", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(111) 555-4444", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(111) 555-3333", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.FAX));
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("TheOffice", f.getExtendedAddress());
assertEquals("222 Broadway", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("NY", f.getRegion());
assertEquals("99999", f.getPostalCode());
assertEquals("USA", f.getCountry());
assertEquals("222 Broadway\r\nNew York, NY 99999\r\nUSA", f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertTrue(types.contains(AddressTypeParameter.PREF));
assertFalse(it.hasNext());
}
//LABEL
{
assertTrue(vcard.getOrphanedLabels().isEmpty());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://mikeangstadt.name", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("HOME"));
f = it.next();
assertEquals("http://mikeangstadt.name", f.getValue());
types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("TheProfession", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1922);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 10);
assertEquals(c.getTime(), f.getDate());
}
//KEY
{
Iterator<KeyType> it = vcard.getKeys().iterator();
KeyType f = it.next();
assertEquals(KeyTypeParameter.X509, f.getContentType());
assertEquals(514, f.getData().length);
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.PREF));
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(2324, f.getData().length);
assertFalse(it.hasNext());
}
//FBURL
{
//a 4.0 property in a 2.1 vCard...
Iterator<FbUrlType> it = vcard.getFbUrls().iterator();
FbUrlType f = it.next();
assertEquals("http://website.com/mycal", f.getValue());
assertFalse(it.hasNext());
}
//REV
{
RevisionType f = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.AUGUST);
c.set(Calendar.DAY_OF_MONTH, 1);
c.set(Calendar.HOUR_OF_DAY, 18);
c.set(Calendar.MINUTE, 46);
c.set(Calendar.SECOND, 31);
assertEquals(c.getTime(), f.getTimestamp());
}
//extended types
{
assertEquals(8, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-MS-TEL").get(0);
assertEquals("X-MS-TEL", f.getTypeName());
assertEquals("(111) 555-4444", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(2, types.size());
assertTrue(types.contains("VOICE"));
assertTrue(types.contains("CALLBACK"));
f = vcard.getExtendedType("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0);
assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName());
assertEquals("2", f.getValue());
f = vcard.getExtendedType("X-MS-ANNIVERSARY").get(0);
assertEquals("X-MS-ANNIVERSARY", f.getTypeName());
assertEquals("20120801", f.getValue());
f = vcard.getExtendedType("X-MS-IMADDRESS").get(0);
assertEquals("X-MS-IMADDRESS", f.getTypeName());
assertEquals("[email protected]", f.getValue());
f = vcard.getExtendedType("X-MS-OL-DESIGN").get(0);
assertEquals("X-MS-OL-DESIGN", f.getTypeName());
assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telcell\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Mobile</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue());
assertEquals("utf-8", f.getSubTypes().getCharset());
f = vcard.getExtendedType("X-MS-MANAGER").get(0);
assertEquals("X-MS-MANAGER", f.getTypeName());
assertEquals("TheManagerName", f.getValue());
f = vcard.getExtendedType("X-MS-ASSISTANT").get(0);
assertEquals("X-MS-ASSISTANT", f.getTypeName());
assertEquals("TheAssistantName", f.getValue());
f = vcard.getExtendedType("X-MS-SPOUSE").get(0);
assertEquals("X-MS-SPOUSE", f.getTypeName());
assertEquals("TheSpouse", f.getValue());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void outlook2007VCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2007.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V2_1, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("en-us", f.getSubTypes().getLanguage());
assertEquals("Angstadt", f.getFamily());
assertEquals("Michael", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Jr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. Michael Angstadt Jr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Mike"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("TheCompany", "TheDepartment"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("TheJobTitle", f.getValue());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is the NOTE field \r\nI assume it encodes this text inside a NOTE vCard type.\r\nBut I'm not sure because there's text formatting going on here.\r\nIt does not preserve the formatting", f.getValue());
assertEquals("us-ascii", f.getSubTypes().getCharset());
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("(111) 555-1111", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(111) 555-2222", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(111) 555-4444", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(111) 555-3333", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.FAX));
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("TheOffice", f.getExtendedAddress());
assertEquals("222 Broadway", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("NY", f.getRegion());
assertEquals("99999", f.getPostalCode());
assertEquals("USA", f.getCountry());
assertEquals("222 Broadway\r\nNew York, NY 99999\r\nUSA", f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertTrue(types.contains(AddressTypeParameter.PREF));
assertFalse(it.hasNext());
}
//LABEL
{
assertTrue(vcard.getOrphanedLabels().isEmpty());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://mikeangstadt.name", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("HOME"));
f = it.next();
assertEquals("http://mikeangstadt.name", f.getValue());
types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("TheProfession", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1922);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 10);
assertEquals(c.getTime(), f.getDate());
}
//KEY
{
Iterator<KeyType> it = vcard.getKeys().iterator();
KeyType f = it.next();
assertEquals(KeyTypeParameter.X509, f.getContentType());
assertEquals(514, f.getData().length);
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.PREF));
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(2324, f.getData().length);
assertFalse(it.hasNext());
}
//FBURL
{
//a 4.0 property in a 2.1 vCard...
Iterator<FbUrlType> it = vcard.getFbUrls().iterator();
FbUrlType f = it.next();
assertEquals("http://website.com/mycal", f.getValue());
assertFalse(it.hasNext());
}
//REV
{
RevisionType f = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.AUGUST);
c.set(Calendar.DAY_OF_MONTH, 1);
c.set(Calendar.HOUR_OF_DAY, 18);
c.set(Calendar.MINUTE, 46);
c.set(Calendar.SECOND, 31);
assertEquals(c.getTime(), f.getTimestamp());
}
//extended types
{
assertEquals(8, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-MS-TEL").get(0);
assertEquals("X-MS-TEL", f.getTypeName());
assertEquals("(111) 555-4444", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(2, types.size());
assertTrue(types.contains("VOICE"));
assertTrue(types.contains("CALLBACK"));
f = vcard.getExtendedType("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0);
assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName());
assertEquals("2", f.getValue());
f = vcard.getExtendedType("X-MS-ANNIVERSARY").get(0);
assertEquals("X-MS-ANNIVERSARY", f.getTypeName());
assertEquals("20120801", f.getValue());
f = vcard.getExtendedType("X-MS-IMADDRESS").get(0);
assertEquals("X-MS-IMADDRESS", f.getTypeName());
assertEquals("[email protected]", f.getValue());
f = vcard.getExtendedType("X-MS-OL-DESIGN").get(0);
assertEquals("X-MS-OL-DESIGN", f.getTypeName());
assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telcell\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Mobile</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue());
assertEquals("utf-8", f.getSubTypes().getCharset());
f = vcard.getExtendedType("X-MS-MANAGER").get(0);
assertEquals("X-MS-MANAGER", f.getTypeName());
assertEquals("TheManagerName", f.getValue());
f = vcard.getExtendedType("X-MS-ASSISTANT").get(0);
assertEquals("X-MS-ASSISTANT", f.getTypeName());
assertEquals("TheAssistantName", f.getValue());
f = vcard.getExtendedType("X-MS-SPOUSE").get(0);
assertEquals("X-MS-SPOUSE", f.getTypeName());
assertEquals("TheSpouse", f.getValue());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void outlook2007VCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2007.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V2_1, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("en-us", f.getSubTypes().getLanguage());
assertEquals("Angstadt", f.getFamily());
assertEquals("Michael", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Jr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. Michael Angstadt Jr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Mike"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("TheCompany", "TheDepartment"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("TheJobTitle", f.getValue());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is the NOTE field \r\nI assume it encodes this text inside a NOTE vCard type.\r\nBut I'm not sure because there's text formatting going on here.\r\nIt does not preserve the formatting", f.getValue());
assertEquals("us-ascii", f.getSubTypes().getCharset());
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("(111) 555-1111", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(111) 555-2222", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(111) 555-4444", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(111) 555-3333", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.FAX));
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("TheOffice", f.getExtendedAddress());
assertEquals("222 Broadway", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("NY", f.getRegion());
assertEquals("99999", f.getPostalCode());
assertEquals("USA", f.getCountry());
assertEquals("222 Broadway\r\nNew York, NY 99999\r\nUSA", f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertTrue(types.contains(AddressTypeParameter.PREF));
assertFalse(it.hasNext());
}
//LABEL
{
assertTrue(vcard.getOrphanedLabels().isEmpty());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://mikeangstadt.name", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("HOME"));
f = it.next();
assertEquals("http://mikeangstadt.name", f.getValue());
types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("TheProfession", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1922);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 10);
assertEquals(c.getTime(), f.getDate());
}
//KEY
{
Iterator<KeyType> it = vcard.getKeys().iterator();
KeyType f = it.next();
assertEquals(KeyTypeParameter.X509, f.getContentType());
assertEquals(514, f.getData().length);
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.PREF));
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(2324, f.getData().length);
assertFalse(it.hasNext());
}
//FBURL
{
//a 4.0 property in a 2.1 vCard...
Iterator<FbUrlType> it = vcard.getFbUrls().iterator();
FbUrlType f = it.next();
assertEquals("http://website.com/mycal", f.getValue());
assertFalse(it.hasNext());
}
//REV
{
RevisionType f = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.AUGUST);
c.set(Calendar.DAY_OF_MONTH, 1);
c.set(Calendar.HOUR_OF_DAY, 18);
c.set(Calendar.MINUTE, 46);
c.set(Calendar.SECOND, 31);
assertEquals(c.getTime(), f.getTimestamp());
}
//extended types
{
assertEquals(8, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-MS-TEL").get(0);
assertEquals("X-MS-TEL", f.getTypeName());
assertEquals("(111) 555-4444", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(2, types.size());
assertTrue(types.contains("VOICE"));
assertTrue(types.contains("CALLBACK"));
f = vcard.getExtendedProperties("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0);
assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName());
assertEquals("2", f.getValue());
f = vcard.getExtendedProperties("X-MS-ANNIVERSARY").get(0);
assertEquals("X-MS-ANNIVERSARY", f.getTypeName());
assertEquals("20120801", f.getValue());
f = vcard.getExtendedProperties("X-MS-IMADDRESS").get(0);
assertEquals("X-MS-IMADDRESS", f.getTypeName());
assertEquals("[email protected]", f.getValue());
f = vcard.getExtendedProperties("X-MS-OL-DESIGN").get(0);
assertEquals("X-MS-OL-DESIGN", f.getTypeName());
assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telcell\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Mobile</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue());
assertEquals("utf-8", f.getSubTypes().getCharset());
f = vcard.getExtendedProperties("X-MS-MANAGER").get(0);
assertEquals("X-MS-MANAGER", f.getTypeName());
assertEquals("TheManagerName", f.getValue());
f = vcard.getExtendedProperties("X-MS-ASSISTANT").get(0);
assertEquals("X-MS-ASSISTANT", f.getTypeName());
assertEquals("TheAssistantName", f.getValue());
f = vcard.getExtendedProperties("X-MS-SPOUSE").get(0);
assertEquals("X-MS-SPOUSE", f.getTypeName());
assertEquals("TheSpouse", f.getValue());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void outlook2007VCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2007.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V2_1, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("en-us", f.getSubTypes().getLanguage());
assertEquals("Angstadt", f.getFamily());
assertEquals("Michael", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Jr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. Michael Angstadt Jr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Mike"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("TheCompany", "TheDepartment"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("TheJobTitle", f.getValue());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is the NOTE field \r\nI assume it encodes this text inside a NOTE vCard type.\r\nBut I'm not sure because there's text formatting going on here.\r\nIt does not preserve the formatting", f.getValue());
assertEquals("us-ascii", f.getSubTypes().getCharset());
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("(111) 555-1111", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(111) 555-2222", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(111) 555-4444", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(111) 555-3333", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.FAX));
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("TheOffice", f.getExtendedAddress());
assertEquals("222 Broadway", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("NY", f.getRegion());
assertEquals("99999", f.getPostalCode());
assertEquals("USA", f.getCountry());
assertEquals("222 Broadway\r\nNew York, NY 99999\r\nUSA", f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertTrue(types.contains(AddressTypeParameter.PREF));
assertFalse(it.hasNext());
}
//LABEL
{
assertTrue(vcard.getOrphanedLabels().isEmpty());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://mikeangstadt.name", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("HOME"));
f = it.next();
assertEquals("http://mikeangstadt.name", f.getValue());
types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("TheProfession", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1922);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 10);
assertEquals(c.getTime(), f.getDate());
}
//KEY
{
Iterator<KeyType> it = vcard.getKeys().iterator();
KeyType f = it.next();
assertEquals(KeyTypeParameter.X509, f.getContentType());
assertEquals(514, f.getData().length);
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.PREF));
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(2324, f.getData().length);
assertFalse(it.hasNext());
}
//FBURL
{
//a 4.0 property in a 2.1 vCard...
Iterator<FbUrlType> it = vcard.getFbUrls().iterator();
FbUrlType f = it.next();
assertEquals("http://website.com/mycal", f.getValue());
assertFalse(it.hasNext());
}
//REV
{
RevisionType f = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.AUGUST);
c.set(Calendar.DAY_OF_MONTH, 1);
c.set(Calendar.HOUR_OF_DAY, 18);
c.set(Calendar.MINUTE, 46);
c.set(Calendar.SECOND, 31);
assertEquals(c.getTime(), f.getTimestamp());
}
//extended types
{
assertEquals(8, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-MS-TEL").get(0);
assertEquals("X-MS-TEL", f.getTypeName());
assertEquals("(111) 555-4444", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(2, types.size());
assertTrue(types.contains("VOICE"));
assertTrue(types.contains("CALLBACK"));
f = vcard.getExtendedProperties("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0);
assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName());
assertEquals("2", f.getValue());
f = vcard.getExtendedProperties("X-MS-ANNIVERSARY").get(0);
assertEquals("X-MS-ANNIVERSARY", f.getTypeName());
assertEquals("20120801", f.getValue());
f = vcard.getExtendedProperties("X-MS-IMADDRESS").get(0);
assertEquals("X-MS-IMADDRESS", f.getTypeName());
assertEquals("[email protected]", f.getValue());
f = vcard.getExtendedProperties("X-MS-OL-DESIGN").get(0);
assertEquals("X-MS-OL-DESIGN", f.getTypeName());
assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telcell\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Mobile</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue());
assertEquals("utf-8", f.getSubTypes().getCharset());
f = vcard.getExtendedProperties("X-MS-MANAGER").get(0);
assertEquals("X-MS-MANAGER", f.getTypeName());
assertEquals("TheManagerName", f.getValue());
f = vcard.getExtendedProperties("X-MS-ASSISTANT").get(0);
assertEquals("X-MS-ASSISTANT", f.getTypeName());
assertEquals("TheAssistantName", f.getValue());
f = vcard.getExtendedProperties("X-MS-SPOUSE").get(0);
assertEquals("X-MS-SPOUSE", f.getTypeName());
assertEquals("TheSpouse", f.getValue());
}
assertWarnings(0, reader.getWarnings());
assertNull(reader.readNext());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void gmailVCard() throws Exception {
VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("John_Doe_GMAIL.vcf")));
reader.setCompatibilityMode(CompatibilityMode.GMAIL);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter, James Doe Sr.", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter, James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("home")));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("905-555-1234", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
f = it.next();
assertEquals("905-666-1234", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("Crescent moon drive" + newline + "555-asd" + newline + "Nice Area, Albaney, New York12345" + newline + "United States of America", f.getExtendedAddress());
assertEquals(null, f.getStreetAddress());
assertEquals(null, f.getLocality());
assertEquals(null, f.getRegion());
assertEquals(null, f.getPostalCode());
assertEquals(null, f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertFalse(it.hasNext());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 22);
assertEquals(c.getTime(), f.getDate());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + newline + "Favotire Color: Blue", f.getValue());
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(6, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-PHONETIC-FIRST-NAME").get(0);
assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName());
assertEquals("Jon", f.getValue());
f = vcard.getExtendedType("X-PHONETIC-LAST-NAME").get(0);
assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName());
assertEquals("Dow", f.getValue());
f = vcard.getExtendedType("X-ABDATE").get(0);
assertEquals("X-ABDATE", f.getTypeName());
assertEquals("1975-03-01", f.getValue());
assertEquals("item1", f.getGroup());
f = vcard.getExtendedType("X-ABLABEL").get(0);
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("_$!<Anniversary>!$_", f.getValue());
assertEquals("item1", f.getGroup());
f = vcard.getExtendedType("X-ABLABEL").get(1);
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("_$!<Spouse>!$_", f.getValue());
assertEquals("item2", f.getGroup());
f = vcard.getExtendedType("X-ABRELATEDNAMES").get(0);
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("Jenny", f.getValue());
assertEquals("item2", f.getGroup());
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void gmailVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_GMAIL.vcf"));
reader.setCompatibilityMode(CompatibilityMode.GMAIL);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter, James Doe Sr.", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter, James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("home")));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("905-555-1234", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
f = it.next();
assertEquals("905-666-1234", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("Crescent moon drive" + newline + "555-asd" + newline + "Nice Area, Albaney, New York12345" + newline + "United States of America", f.getExtendedAddress());
assertEquals(null, f.getStreetAddress());
assertEquals(null, f.getLocality());
assertEquals(null, f.getRegion());
assertEquals(null, f.getPostalCode());
assertEquals(null, f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertFalse(it.hasNext());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 22);
assertEquals(c.getTime(), f.getDate());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + newline + "Favotire Color: Blue", f.getValue());
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(6, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-PHONETIC-FIRST-NAME").get(0);
assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName());
assertEquals("Jon", f.getValue());
f = vcard.getExtendedType("X-PHONETIC-LAST-NAME").get(0);
assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName());
assertEquals("Dow", f.getValue());
f = vcard.getExtendedType("X-ABDATE").get(0);
assertEquals("X-ABDATE", f.getTypeName());
assertEquals("1975-03-01", f.getValue());
assertEquals("item1", f.getGroup());
f = vcard.getExtendedType("X-ABLABEL").get(0);
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("_$!<Anniversary>!$_", f.getValue());
assertEquals("item1", f.getGroup());
f = vcard.getExtendedType("X-ABLABEL").get(1);
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("_$!<Spouse>!$_", f.getValue());
assertEquals("item2", f.getGroup());
f = vcard.getExtendedType("X-ABRELATEDNAMES").get(0);
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("Jenny", f.getValue());
assertEquals("item2", f.getGroup());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public T get(V value) {
return find(value, true, true);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public T get(V value) {
T found = find(value);
if (found != null) {
return found;
}
synchronized (runtimeDefined) {
for (T obj : runtimeDefined) {
if (matches(obj, value)) {
return obj;
}
}
T created = create(value);
runtimeDefined.add(created);
return created;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void labels() throws Exception {
VCard vcard = new VCard();
//address with label
AddressType adr = new AddressType();
adr.setStreetAddress("123 Main St.");
adr.setLocality("Austin");
adr.setRegion("TX");
adr.setPostalCode("12345");
adr.setLabel("123 Main St.\r\nAustin, TX 12345");
adr.addType(AddressTypeParameter.HOME);
vcard.addAddress(adr);
//address without label
adr = new AddressType();
adr.setStreetAddress("222 Broadway");
adr.setLocality("New York");
adr.setRegion("NY");
adr.setPostalCode("99999");
adr.addType(AddressTypeParameter.WORK);
vcard.addAddress(adr);
//orphaned label
LabelType label = new LabelType("22 Spruce Ln.\r\nChicago, IL 11111");
label.addType(AddressTypeParameter.PARCEL);
vcard.addOrphanedLabel(label);
//3.0
//LABEL types should be used
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V3_0, null);
vcw.setAddProdId(false);
vcw.write(vcard);
String actual = sw.toString();
StringBuilder sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:3.0\r\n");
sb.append("ADR;TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n");
sb.append("LABEL;TYPE=home:123 Main St.\\nAustin\\, TX 12345\r\n");
sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n");
sb.append("LABEL;TYPE=parcel:22 Spruce Ln.\\nChicago\\, IL 11111\r\n");
sb.append("END:VCARD\r\n");
String expected = sb.toString();
assertEquals(expected, actual);
//4.0
//LABEL parameters should be used
sw = new StringWriter();
vcw = new VCardWriter(sw, VCardVersion.V4_0, null);
vcw.setAddProdId(false);
vcw.write(vcard);
actual = sw.toString();
sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:4.0\r\n");
sb.append("ADR;LABEL=\"123 Main St.\\nAustin, TX 12345\";TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n");
sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n");
sb.append("END:VCARD\r\n");
expected = sb.toString();
assertEquals(expected, actual);
}
#location 34
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void labels() throws Exception {
VCard vcard = new VCard();
//address with label
AddressType adr = new AddressType();
adr.setStreetAddress("123 Main St.");
adr.setLocality("Austin");
adr.setRegion("TX");
adr.setPostalCode("12345");
adr.setLabel("123 Main St.\r\nAustin, TX 12345");
adr.addType(AddressTypeParameter.HOME);
vcard.addAddress(adr);
//address without label
adr = new AddressType();
adr.setStreetAddress("222 Broadway");
adr.setLocality("New York");
adr.setRegion("NY");
adr.setPostalCode("99999");
adr.addType(AddressTypeParameter.WORK);
vcard.addAddress(adr);
//orphaned label
LabelType label = new LabelType("22 Spruce Ln.\r\nChicago, IL 11111");
label.addType(AddressTypeParameter.PARCEL);
vcard.addOrphanedLabel(label);
//3.0
//LABEL types should be used
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V3_0, null, "\r\n");
vcw.setAddProdId(false);
vcw.write(vcard);
String actual = sw.toString();
StringBuilder sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:3.0\r\n");
sb.append("ADR;TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n");
sb.append("LABEL;TYPE=home:123 Main St.\\nAustin\\, TX 12345\r\n");
sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n");
sb.append("LABEL;TYPE=parcel:22 Spruce Ln.\\nChicago\\, IL 11111\r\n");
sb.append("END:VCARD\r\n");
String expected = sb.toString();
assertEquals(expected, actual);
//4.0
//LABEL parameters should be used
sw = new StringWriter();
vcw = new VCardWriter(sw, VCardVersion.V4_0, null, "\r\n");
vcw.setAddProdId(false);
vcw.write(vcard);
actual = sw.toString();
sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:4.0\r\n");
sb.append("ADR;LABEL=\"123 Main St.\\nAustin, TX 12345\";TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n");
sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n");
sb.append("END:VCARD\r\n");
expected = sb.toString();
assertEquals(expected, actual);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void subTypes() throws Exception {
VCard vcard = new VCard();
//one sub type
AddressType adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
vcard.addAddress(adr);
//two types
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
vcard.addAddress(adr);
//three types
//make sure it properly escapes sub type values that have special chars
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
adr.getSubTypes().put("TEXT", "123 \"Main\" St\r\nAustin, ;TX; 12345");
vcard.addAddress(adr);
//2.1
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1, null);
vcw.setAddProdId(false);
vcw.write(vcard);
String actual = sw.toString();
StringBuilder sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:2.1\r\n");
sb.append("ADR;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR;LANGUAGE=es;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR;LANGUAGE=es;TEXT=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\";X-DOORMAN=true:;;;;;;\r\n");
sb.append("END:VCARD\r\n");
String expected = sb.toString();
assertEquals(expected, actual);
//3.0
sw = new StringWriter();
vcw = new VCardWriter(sw, VCardVersion.V3_0, null);
vcw.setAddProdId(false);
vcw.write(vcard);
actual = sw.toString();
sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:3.0\r\n");
sb.append("ADR;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR,es;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR,es;TEXT=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\";X-DOORMAN=true:;;;;;;\r\n");
sb.append("END:VCARD\r\n");
expected = sb.toString();
assertEquals(expected, actual);
}
#location 30
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void subTypes() throws Exception {
VCard vcard = new VCard();
//one sub type
AddressType adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
vcard.addAddress(adr);
//two types
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
vcard.addAddress(adr);
//three types
//make sure it properly escapes sub type values that have special chars
adr = new AddressType();
adr.getSubTypes().put("X-DOORMAN", "true");
adr.getSubTypes().put("LANGUAGE", "FR");
adr.getSubTypes().put("LANGUAGE", "es");
adr.getSubTypes().put("TEXT", "123 \"Main\" St\r\nAustin, ;TX; 12345");
vcard.addAddress(adr);
//2.1
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1, null, "\r\n");
vcw.setAddProdId(false);
vcw.write(vcard);
String actual = sw.toString();
StringBuilder sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:2.1\r\n");
sb.append("ADR;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR;LANGUAGE=es;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR;LANGUAGE=es;TEXT=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\";X-DOORMAN=true:;;;;;;\r\n");
sb.append("END:VCARD\r\n");
String expected = sb.toString();
assertEquals(expected, actual);
//3.0
sw = new StringWriter();
vcw = new VCardWriter(sw, VCardVersion.V3_0, null, "\r\n");
vcw.setAddProdId(false);
vcw.write(vcard);
actual = sw.toString();
sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:3.0\r\n");
sb.append("ADR;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR,es;X-DOORMAN=true:;;;;;;\r\n");
sb.append("ADR;LANGUAGE=FR,es;TEXT=\"123 \\\"Main\\\" St\\nAustin, ;TX; 12345\";X-DOORMAN=true:;;;;;;\r\n");
sb.append("END:VCARD\r\n");
expected = sb.toString();
assertEquals(expected, actual);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void lotusNotesVCard() throws Exception {
VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("John_Doe_LOTUS_NOTES.vcf")));
reader.setCompatibilityMode(CompatibilityMode.MAC_ADDRESS_BOOK);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//PRODID
{
ProdIdType f = vcard.getProdId();
assertEquals("-//Apple Inc.//Address Book 6.1//EN", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Johny"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("I"), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. Doe John I Johny", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny,JayJay"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "SUN"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Generic Accountant", f.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("WORK")));
assertTrue(types.contains(EmailTypeParameter.PREF));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("WORK")));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("+1 (212) 204-34456", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertTrue(types.contains(TelephoneTypeParameter.PREF));
f = it.next();
assertEquals("00-1-212-555-7777", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals("item1", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("25334" + newline + "South cresent drive, Building 5, 3rd floo r", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("NYC887", f.getPostalCode());
assertEquals("U.S.A.", f.getCountry());
assertNull(f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PREF));
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" + newline + "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO , THE" + newline + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR P URPOSE" + newline + "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTOR S BE" + newline + "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" + newline + "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" + newline + " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS " + newline + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" + newline + " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)" + newline + "A RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" + newline + " POSSIBILITY OF SUCH DAMAGE.", f.getValue());
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("item2", f.getGroup());
assertEquals("http://www.sun.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MAY);
c.set(Calendar.DAY_OF_MONTH, 21);
assertEquals(c.getTime(), f.getDate());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(7957, f.getData().length);
assertFalse(it.hasNext());
}
//UID
{
UidType f = vcard.getUid();
assertEquals("0e7602cc-443e-4b82-b4b1-90f62f99a199", f.getValue());
}
//GEO
{
GeoType f = vcard.getGeo();
assertEquals(-2.6, f.getLatitude(), .01);
assertEquals(3.4, f.getLongitude(), .01);
}
//CLASS
{
ClassificationType f = vcard.getClassification();
assertEquals("Public", f.getValue());
}
//PROFILE
{
ProfileType f = vcard.getProfile();
assertEquals("VCard", f.getValue());
}
//TZ
{
TimezoneType f = vcard.getTimezone();
assertEquals(Integer.valueOf(1), f.getHourOffset());
assertEquals(Integer.valueOf(0), f.getMinuteOffset());
}
//LABEL
{
Iterator<LabelType> it = vcard.getOrphanedLabels().iterator();
LabelType f = it.next();
assertEquals("John Doe" + newline + "New York, NewYork," + newline + "South Crecent Drive," + newline + "Building 5, floor 3," + newline + "USA", f.getValue());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PARCEL));
assertTrue(types.contains(AddressTypeParameter.PREF));
assertFalse(it.hasNext());
}
//SORT-STRING
{
SortStringType f = vcard.getSortString();
assertEquals("JOHN", f.getValue());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("Counting Money", f.getValue());
assertFalse(it.hasNext());
}
//SOURCE
{
Iterator<SourceType> it = vcard.getSources().iterator();
SourceType f = it.next();
assertEquals("Whatever", f.getValue());
assertFalse(it.hasNext());
}
//MAILER
{
MailerType f = vcard.getMailer();
assertEquals("Mozilla Thunderbird", f.getValue());
}
//NAME
{
SourceDisplayTextType f = vcard.getSourceDisplayText();
assertEquals("VCard for John Doe", f.getValue());
}
//extended types
{
assertEquals(4, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-ABLABEL").get(0);
assertEquals("item2", f.getGroup());
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("_$!<HomePage>!$_", f.getValue());
f = vcard.getExtendedType("X-ABUID").get(0);
assertEquals("X-ABUID", f.getTypeName());
assertEquals("0E7602CC-443E-4B82-B4B1-90F62F99A199:ABPerson", f.getValue());
f = vcard.getExtendedType("X-GENERATOR").get(0);
assertEquals("X-GENERATOR", f.getTypeName());
assertEquals("Cardme Generator", f.getValue());
f = vcard.getExtendedType("X-LONG-STRING").get(0);
assertEquals("X-LONG-STRING", f.getTypeName());
assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", f.getValue());
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void lotusNotesVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_LOTUS_NOTES.vcf"));
reader.setCompatibilityMode(CompatibilityMode.MAC_ADDRESS_BOOK);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//PRODID
{
ProdIdType f = vcard.getProdId();
assertEquals("-//Apple Inc.//Address Book 6.1//EN", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Johny"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("I"), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. Doe John I Johny", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny,JayJay"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "SUN"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Generic Accountant", f.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("WORK")));
assertTrue(types.contains(EmailTypeParameter.PREF));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("WORK")));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("+1 (212) 204-34456", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertTrue(types.contains(TelephoneTypeParameter.PREF));
f = it.next();
assertEquals("00-1-212-555-7777", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals("item1", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("25334" + newline + "South cresent drive, Building 5, 3rd floo r", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("NYC887", f.getPostalCode());
assertEquals("U.S.A.", f.getCountry());
assertNull(f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PREF));
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"" + newline + "AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO , THE" + newline + "IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR P URPOSE" + newline + "ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTOR S BE" + newline + "LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR" + newline + "CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF" + newline + " SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS " + newline + "INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN" + newline + " CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)" + newline + "A RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE" + newline + " POSSIBILITY OF SUCH DAMAGE.", f.getValue());
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("item2", f.getGroup());
assertEquals("http://www.sun.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MAY);
c.set(Calendar.DAY_OF_MONTH, 21);
assertEquals(c.getTime(), f.getDate());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(7957, f.getData().length);
assertFalse(it.hasNext());
}
//UID
{
UidType f = vcard.getUid();
assertEquals("0e7602cc-443e-4b82-b4b1-90f62f99a199", f.getValue());
}
//GEO
{
GeoType f = vcard.getGeo();
assertEquals(-2.6, f.getLatitude(), .01);
assertEquals(3.4, f.getLongitude(), .01);
}
//CLASS
{
ClassificationType f = vcard.getClassification();
assertEquals("Public", f.getValue());
}
//PROFILE
{
ProfileType f = vcard.getProfile();
assertEquals("VCard", f.getValue());
}
//TZ
{
TimezoneType f = vcard.getTimezone();
assertEquals(Integer.valueOf(1), f.getHourOffset());
assertEquals(Integer.valueOf(0), f.getMinuteOffset());
}
//LABEL
{
Iterator<LabelType> it = vcard.getOrphanedLabels().iterator();
LabelType f = it.next();
assertEquals("John Doe" + newline + "New York, NewYork," + newline + "South Crecent Drive," + newline + "Building 5, floor 3," + newline + "USA", f.getValue());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PARCEL));
assertTrue(types.contains(AddressTypeParameter.PREF));
assertFalse(it.hasNext());
}
//SORT-STRING
{
SortStringType f = vcard.getSortString();
assertEquals("JOHN", f.getValue());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("Counting Money", f.getValue());
assertFalse(it.hasNext());
}
//SOURCE
{
Iterator<SourceType> it = vcard.getSources().iterator();
SourceType f = it.next();
assertEquals("Whatever", f.getValue());
assertFalse(it.hasNext());
}
//MAILER
{
MailerType f = vcard.getMailer();
assertEquals("Mozilla Thunderbird", f.getValue());
}
//NAME
{
SourceDisplayTextType f = vcard.getSourceDisplayText();
assertEquals("VCard for John Doe", f.getValue());
}
//extended types
{
assertEquals(4, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-ABLABEL").get(0);
assertEquals("item2", f.getGroup());
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("_$!<HomePage>!$_", f.getValue());
f = vcard.getExtendedType("X-ABUID").get(0);
assertEquals("X-ABUID", f.getTypeName());
assertEquals("0E7602CC-443E-4B82-B4B1-90F62F99A199:ABPerson", f.getValue());
f = vcard.getExtendedType("X-GENERATOR").get(0);
assertEquals("X-GENERATOR", f.getTypeName());
assertEquals("Cardme Generator", f.getValue());
f = vcard.getExtendedType("X-LONG-STRING").get(0);
assertEquals("X-LONG-STRING", f.getTypeName());
assertEquals("1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890", f.getValue());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
VCard vcard = new VCard();
StructuredNameType n = new StructuredNameType();
n.setFamily("Angstadt");
n.setGiven("Michael");
n.addPrefix("Mr");
vcard.setStructuredName(n);
vcard.setFormattedName(new FormattedNameType("Michael Angstadt"));
NicknameType nickname = new NicknameType();
nickname.addValue("Mike");
vcard.setNickname(nickname);
vcard.addTitle(new TitleType("Software Engineer"));
EmailType email = new EmailType("[email protected]");
vcard.addEmail(email);
UrlType url = new UrlType("http://mikeangstadt.name");
vcard.addUrl(url);
CategoriesType categories = new CategoriesType();
categories.addValue("Java software engineer");
categories.addValue("vCard expert");
categories.addValue("Nice guy!!");
vcard.setCategories(categories);
vcard.setGeo(new GeoType(39.95, -75.1667));
vcard.setTimezone(new TimezoneType(-5, 0, "America/New_York"));
byte portrait[] = getFileBytes("portrait.jpg");
PhotoType photo = new PhotoType(portrait, ImageTypeParameter.JPEG);
vcard.addPhoto(photo);
byte pronunciation[] = getFileBytes("pronunciation.ogg");
SoundType sound = new SoundType(pronunciation, SoundTypeParameter.OGG);
vcard.addSound(sound);
//vcard.setUid(UidType.random());
vcard.setUid(new UidType("urn:uuid:dd418720-c754-4631-a869-db89d02b831b"));
vcard.addSource(new SourceType("http://mikeangstadt.name/mike-angstadt.vcf"));
vcard.setRevision(new RevisionType(new Date()));
//write vCard to file
Writer writer = new FileWriter("mike-angstadt.vcf");
VCardWriter vcw = new VCardWriter(writer, VCardVersion.V3_0);
vcw.write(vcard);
List<String> warnings = vcw.getWarnings();
System.out.println("Completed with " + warnings.size() + " warnings.");
for (String warning : warnings) {
System.out.println("* " + warning);
}
writer.close();
}
#location 53
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception {
VCard vcard = new VCard();
StructuredNameType n = new StructuredNameType();
n.setFamily("Angstadt");
n.setGiven("Michael");
n.addPrefix("Mr");
vcard.setStructuredName(n);
vcard.setFormattedName(new FormattedNameType("Michael Angstadt"));
NicknameType nickname = new NicknameType();
nickname.addValue("Mike");
vcard.setNickname(nickname);
vcard.addTitle(new TitleType("Software Engineer"));
EmailType email = new EmailType("[email protected]");
vcard.addEmail(email);
UrlType url = new UrlType("http://mikeangstadt.name");
vcard.addUrl(url);
CategoriesType categories = new CategoriesType();
categories.addValue("Java software engineer");
categories.addValue("vCard expert");
categories.addValue("Nice guy!!");
vcard.setCategories(categories);
vcard.setGeo(new GeoType(39.95, -75.1667));
vcard.setTimezone(new TimezoneType(-5, 0, "America/New_York"));
byte portrait[] = getFileBytes("portrait.jpg");
PhotoType photo = new PhotoType(portrait, ImageTypeParameter.JPEG);
vcard.addPhoto(photo);
byte pronunciation[] = getFileBytes("pronunciation.ogg");
SoundType sound = new SoundType(pronunciation, SoundTypeParameter.OGG);
vcard.addSound(sound);
//vcard.setUid(UidType.random());
vcard.setUid(new UidType("urn:uuid:dd418720-c754-4631-a869-db89d02b831b"));
vcard.addSource(new SourceType("http://mikeangstadt.name/mike-angstadt.vcf"));
vcard.setRevision(new RevisionType(new Date()));
//write vCard to file
File file = new File("mike-angstadt.vcf");
System.out.println("Writing " + file.getName() + "...");
Writer writer = new FileWriter(file);
VCardWriter vcw = new VCardWriter(writer, VCardVersion.V3_0);
vcw.write(vcard);
List<String> warnings = vcw.getWarnings();
System.out.println("Completed with " + warnings.size() + " warnings.");
for (String warning : warnings) {
System.out.println("* " + warning);
}
writer.close();
System.out.println();
file = new File("mike-angstadt.xml");
System.out.println("Writing " + file.getName() + "...");
writer = new FileWriter(file);
XCardMarshaller xcm = new XCardMarshaller();
xcm.addVCard(vcard);
xcm.write(writer);
warnings = xcm.getWarnings();
System.out.println("Completed with " + warnings.size() + " warnings.");
for (String warning : warnings) {
System.out.println("* " + warning);
}
writer.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void evolutionVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_EVOLUTION.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType t = it.next();
assertEquals("http://www.ibm.com", t.getValue());
assertEquals("0abc9b8d-0845-47d0-9a91-3db5bb74620d", t.getSubTypes().first("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType t = it.next();
assertEquals("905-666-1234", t.getText());
Set<TelephoneTypeParameter> types = t.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertEquals("c2fa1caa-2926-4087-8971-609cfc7354ce", t.getSubTypes().first("X-COUCHDB-UUID"));
t = it.next();
assertEquals("905-555-1234", t.getText());
types = t.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertEquals("fbfb2722-4fd8-4dbf-9abd-eeb24072fd8e", t.getSubTypes().first("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
}
//UID
{
UidType t = vcard.getUid();
assertEquals("477343c8e6bf375a9bac1f96a5000837", t.getValue());
}
//N
{
StructuredNameType t = vcard.getStructuredName();
assertEquals("Doe", t.getFamily());
assertEquals("John", t.getGiven());
List<String> list = t.getAdditional();
assertEquals(Arrays.asList("Richter, James"), list);
list = t.getPrefixes();
assertEquals(Arrays.asList("Mr."), list);
list = t.getSuffixes();
assertEquals(Arrays.asList("Sr."), list);
}
//FN
{
FormattedNameType t = vcard.getFormattedName();
assertEquals("Mr. John Richter, James Doe Sr.", t.getValue());
}
//NICKNAME
{
NicknameType t = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), t.getValues());
}
//ORG
{
OrganizationType t = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting", "Dungeon"), t.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType t = it.next();
assertEquals("Money Counter", t.getValue());
assertFalse(it.hasNext());
}
//CATEGORIES
{
CategoriesType t = vcard.getCategories();
assertEquals(Arrays.asList("VIP"), t.getValues());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType t = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", t.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType t = it.next();
assertEquals("[email protected]", t.getValue());
Set<EmailTypeParameter> types = t.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(new EmailTypeParameter("work"))); //non-standard type
assertEquals("83a75a5d-2777-45aa-bab5-76a4bd972490", t.getSubTypes().first("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType t = it.next();
assertEquals("ASB-123", t.getPoBox());
assertEquals(null, t.getExtendedAddress());
assertEquals("15 Crescent moon drive", t.getStreetAddress());
assertEquals("Albaney", t.getLocality());
assertEquals("New York", t.getRegion());
assertEquals("12345", t.getPostalCode());
//the space between "United" and "States" is lost because it was included with the folding character and ignored (see .vcf file)
assertEquals("UnitedStates of America", t.getCountry());
Set<AddressTypeParameter> types = t.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType t = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 22);
Date expected = c.getTime();
assertEquals(expected, t.getDate());
}
//REV
{
RevisionType t = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 5);
c.set(Calendar.HOUR_OF_DAY, 13);
c.set(Calendar.MINUTE, 32);
c.set(Calendar.SECOND, 54);
assertEquals(c.getTime(), t.getTimestamp());
}
//extended types
{
assertEquals(7, countExtTypes(vcard));
Iterator<RawType> it = vcard.getExtendedProperties("X-COUCHDB-APPLICATION-ANNOTATIONS").iterator();
RawType t = it.next();
assertEquals("X-COUCHDB-APPLICATION-ANNOTATIONS", t.getTypeName());
assertEquals("{\"Evolution\":{\"revision\":\"2012-03-05T13:32:54Z\"}}", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedProperties("X-AIM").iterator();
t = it.next();
assertEquals("X-AIM", t.getTypeName());
assertEquals("[email protected]", t.getValue());
assertEquals("HOME", t.getSubTypes().getType());
assertEquals("cb9e11fc-bb97-4222-9cd8-99820c1de454", t.getSubTypes().first("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
it = vcard.getExtendedProperties("X-EVOLUTION-FILE-AS").iterator();
t = it.next();
assertEquals("X-EVOLUTION-FILE-AS", t.getTypeName());
assertEquals("Doe\\, John", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedProperties("X-EVOLUTION-SPOUSE").iterator();
t = it.next();
assertEquals("X-EVOLUTION-SPOUSE", t.getTypeName());
assertEquals("Maria", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedProperties("X-EVOLUTION-MANAGER").iterator();
t = it.next();
assertEquals("X-EVOLUTION-MANAGER", t.getTypeName());
assertEquals("Big Blue", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedProperties("X-EVOLUTION-ASSISTANT").iterator();
t = it.next();
assertEquals("X-EVOLUTION-ASSISTANT", t.getTypeName());
assertEquals("Little Red", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedProperties("X-EVOLUTION-ANNIVERSARY").iterator();
t = it.next();
assertEquals("X-EVOLUTION-ANNIVERSARY", t.getTypeName());
assertEquals("1980-03-22", t.getValue());
assertFalse(it.hasNext());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void evolutionVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_EVOLUTION.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType t = it.next();
assertEquals("http://www.ibm.com", t.getValue());
assertEquals("0abc9b8d-0845-47d0-9a91-3db5bb74620d", t.getSubTypes().first("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType t = it.next();
assertEquals("905-666-1234", t.getText());
Set<TelephoneTypeParameter> types = t.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertEquals("c2fa1caa-2926-4087-8971-609cfc7354ce", t.getSubTypes().first("X-COUCHDB-UUID"));
t = it.next();
assertEquals("905-555-1234", t.getText());
types = t.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertEquals("fbfb2722-4fd8-4dbf-9abd-eeb24072fd8e", t.getSubTypes().first("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
}
//UID
{
UidType t = vcard.getUid();
assertEquals("477343c8e6bf375a9bac1f96a5000837", t.getValue());
}
//N
{
StructuredNameType t = vcard.getStructuredName();
assertEquals("Doe", t.getFamily());
assertEquals("John", t.getGiven());
List<String> list = t.getAdditional();
assertEquals(Arrays.asList("Richter, James"), list);
list = t.getPrefixes();
assertEquals(Arrays.asList("Mr."), list);
list = t.getSuffixes();
assertEquals(Arrays.asList("Sr."), list);
}
//FN
{
FormattedNameType t = vcard.getFormattedName();
assertEquals("Mr. John Richter, James Doe Sr.", t.getValue());
}
//NICKNAME
{
NicknameType t = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), t.getValues());
}
//ORG
{
OrganizationType t = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting", "Dungeon"), t.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType t = it.next();
assertEquals("Money Counter", t.getValue());
assertFalse(it.hasNext());
}
//CATEGORIES
{
CategoriesType t = vcard.getCategories();
assertEquals(Arrays.asList("VIP"), t.getValues());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType t = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", t.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType t = it.next();
assertEquals("[email protected]", t.getValue());
Set<EmailTypeParameter> types = t.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(new EmailTypeParameter("work"))); //non-standard type
assertEquals("83a75a5d-2777-45aa-bab5-76a4bd972490", t.getSubTypes().first("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType t = it.next();
assertEquals("ASB-123", t.getPoBox());
assertEquals(null, t.getExtendedAddress());
assertEquals("15 Crescent moon drive", t.getStreetAddress());
assertEquals("Albaney", t.getLocality());
assertEquals("New York", t.getRegion());
assertEquals("12345", t.getPostalCode());
//the space between "United" and "States" is lost because it was included with the folding character and ignored (see .vcf file)
assertEquals("UnitedStates of America", t.getCountry());
Set<AddressTypeParameter> types = t.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType t = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 22);
Date expected = c.getTime();
assertEquals(expected, t.getDate());
}
//REV
{
RevisionType t = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 5);
c.set(Calendar.HOUR_OF_DAY, 13);
c.set(Calendar.MINUTE, 32);
c.set(Calendar.SECOND, 54);
assertEquals(c.getTime(), t.getTimestamp());
}
//extended types
{
assertEquals(7, countExtTypes(vcard));
Iterator<RawType> it = vcard.getExtendedProperties("X-COUCHDB-APPLICATION-ANNOTATIONS").iterator();
RawType t = it.next();
assertEquals("X-COUCHDB-APPLICATION-ANNOTATIONS", t.getTypeName());
assertEquals("{\"Evolution\":{\"revision\":\"2012-03-05T13:32:54Z\"}}", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedProperties("X-AIM").iterator();
t = it.next();
assertEquals("X-AIM", t.getTypeName());
assertEquals("[email protected]", t.getValue());
assertEquals("HOME", t.getSubTypes().getType());
assertEquals("cb9e11fc-bb97-4222-9cd8-99820c1de454", t.getSubTypes().first("X-COUCHDB-UUID"));
assertFalse(it.hasNext());
it = vcard.getExtendedProperties("X-EVOLUTION-FILE-AS").iterator();
t = it.next();
assertEquals("X-EVOLUTION-FILE-AS", t.getTypeName());
assertEquals("Doe\\, John", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedProperties("X-EVOLUTION-SPOUSE").iterator();
t = it.next();
assertEquals("X-EVOLUTION-SPOUSE", t.getTypeName());
assertEquals("Maria", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedProperties("X-EVOLUTION-MANAGER").iterator();
t = it.next();
assertEquals("X-EVOLUTION-MANAGER", t.getTypeName());
assertEquals("Big Blue", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedProperties("X-EVOLUTION-ASSISTANT").iterator();
t = it.next();
assertEquals("X-EVOLUTION-ASSISTANT", t.getTypeName());
assertEquals("Little Red", t.getValue());
assertFalse(it.hasNext());
it = vcard.getExtendedProperties("X-EVOLUTION-ANNIVERSARY").iterator();
t = it.next();
assertEquals("X-EVOLUTION-ANNIVERSARY", t.getTypeName());
assertEquals("1980-03-22", t.getValue());
assertFalse(it.hasNext());
}
assertWarnings(0, reader.getWarnings());
assertNull(reader.readNext());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void thunderbird() throws Exception {
VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("thunderbird-MoreFunctionsForAddressBook-extension.vcf")));
reader.setCompatibilityMode(CompatibilityMode.MAC_ADDRESS_BOOK);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertTrue(f.getPrefixes().isEmpty());
assertTrue(f.getSuffixes().isEmpty());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("John Doe", f.getValue());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("TheOrganization", "TheDepartment"), f.getValues());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johnny"), f.getValues());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("222 Broadway", f.getExtendedAddress());
assertEquals("Suite 100", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("NY", f.getRegion());
assertEquals("98765", f.getPostalCode());
assertEquals("USA", f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertTrue(types.contains(AddressTypeParameter.POSTAL));
f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("123 Main St", f.getExtendedAddress());
assertEquals("Apt 10", f.getStreetAddress());
assertEquals("Austin", f.getLocality());
assertEquals("TX", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.POSTAL));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("555-555-1111", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("555-555-2222", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("555-555-5555", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("555-555-3333", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("555-555-4444", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.PAGER));
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(EmailTypeParameter.PREF));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://www.private-webpage.com", f.getValue());
assertEquals("HOME", f.getType());
f = it.next();
assertEquals("http://www.work-webpage.com", f.getValue());
assertEquals("WORK", f.getType());
assertFalse(it.hasNext());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("TheTitle", f.getValue());
assertFalse(it.hasNext());
}
//CATEGORIES
{
//commas are incorrectly escaped, so there is only 1 item
CategoriesType f = vcard.getCategories();
assertEquals(Arrays.asList("category1, category2, category3"), f.getValues());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1970);
c.set(Calendar.MONTH, Calendar.SEPTEMBER);
c.set(Calendar.DAY_OF_MONTH, 21);
assertEquals(c.getTime(), f.getDate());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is the notes field." + newline + "Second Line" + newline + newline + "Fourth Line" + newline + "You can put anything in the \"note\" field; even curse words.", f.getValue());
assertFalse(it.hasNext());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(8940, f.getData().length);
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(2, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-SPOUSE").get(0);
assertEquals("X-SPOUSE", f.getTypeName());
assertEquals("TheSpouse", f.getValue());
f = vcard.getExtendedType("X-ANNIVERSARY").get(0);
assertEquals("X-ANNIVERSARY", f.getTypeName());
assertEquals("1990-04-30", f.getValue());
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void thunderbird() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("thunderbird-MoreFunctionsForAddressBook-extension.vcf"));
reader.setCompatibilityMode(CompatibilityMode.MAC_ADDRESS_BOOK);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertTrue(f.getPrefixes().isEmpty());
assertTrue(f.getSuffixes().isEmpty());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("John Doe", f.getValue());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("TheOrganization", "TheDepartment"), f.getValues());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johnny"), f.getValues());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("222 Broadway", f.getExtendedAddress());
assertEquals("Suite 100", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("NY", f.getRegion());
assertEquals("98765", f.getPostalCode());
assertEquals("USA", f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertTrue(types.contains(AddressTypeParameter.POSTAL));
f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("123 Main St", f.getExtendedAddress());
assertEquals("Apt 10", f.getStreetAddress());
assertEquals("Austin", f.getLocality());
assertEquals("TX", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.POSTAL));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("555-555-1111", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("555-555-2222", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("555-555-5555", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("555-555-3333", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("555-555-4444", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.PAGER));
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(EmailTypeParameter.PREF));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://www.private-webpage.com", f.getValue());
assertEquals("HOME", f.getType());
f = it.next();
assertEquals("http://www.work-webpage.com", f.getValue());
assertEquals("WORK", f.getType());
assertFalse(it.hasNext());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("TheTitle", f.getValue());
assertFalse(it.hasNext());
}
//CATEGORIES
{
//commas are incorrectly escaped, so there is only 1 item
CategoriesType f = vcard.getCategories();
assertEquals(Arrays.asList("category1, category2, category3"), f.getValues());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1970);
c.set(Calendar.MONTH, Calendar.SEPTEMBER);
c.set(Calendar.DAY_OF_MONTH, 21);
assertEquals(c.getTime(), f.getDate());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is the notes field." + newline + "Second Line" + newline + newline + "Fourth Line" + newline + "You can put anything in the \"note\" field; even curse words.", f.getValue());
assertFalse(it.hasNext());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(8940, f.getData().length);
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(2, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-SPOUSE").get(0);
assertEquals("X-SPOUSE", f.getTypeName());
assertEquals("TheSpouse", f.getValue());
f = vcard.getExtendedType("X-ANNIVERSARY").get(0);
assertEquals("X-ANNIVERSARY", f.getTypeName());
assertEquals("1990-04-30", f.getValue());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void gmailSingle() throws Exception {
VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("gmail-single.vcf")));
reader.setCompatibilityMode(CompatibilityMode.GMAIL);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Greg Dartmouth", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Dartmouth", f.getFamily());
assertEquals("Greg", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertTrue(f.getPrefixes().isEmpty());
assertTrue(f.getSuffixes().isEmpty());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("555 555 1111", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
f = it.next();
assertEquals("item1", f.getGroup());
assertEquals("555 555 2222", f.getValue());
types = f.getTypes();
assertTrue(types.isEmpty());
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("123 Home St" + newline + "Home City, HM 12345", f.getStreetAddress());
assertEquals(null, f.getLocality());
assertEquals(null, f.getRegion());
assertEquals(null, f.getPostalCode());
assertEquals(null, f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
f = it.next();
assertEquals("item2", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("321 Custom St", f.getStreetAddress());
assertEquals("Custom City", f.getLocality());
assertEquals("TX", f.getRegion());
assertEquals("98765", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertTrue(types.isEmpty());
assertFalse(it.hasNext());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("TheCompany"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("TheJobTitle", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1960);
c.set(Calendar.MONTH, Calendar.SEPTEMBER);
c.set(Calendar.DAY_OF_MONTH, 10);
assertEquals(c.getTime(), f.getDate());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://TheProfile.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertTrue(types.isEmpty());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is GMail's note field." + newline + "It should be added as a NOTE type." + newline + "ACustomField: CustomField", f.getValue());
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(12, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-PHONETIC-FIRST-NAME").get(0);
assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName());
assertEquals("Grregg", f.getValue());
f = vcard.getExtendedType("X-PHONETIC-LAST-NAME").get(0);
assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName());
assertEquals("Dart-mowth", f.getValue());
f = vcard.getExtendedType("X-ICQ").get(0);
assertEquals("X-ICQ", f.getTypeName());
assertEquals("123456789", f.getValue());
Iterator<RawType> abLabelIt = vcard.getExtendedType("X-ABLABEL").iterator();
{
f = abLabelIt.next();
assertEquals("item1", f.getGroup());
assertEquals("GRAND_CENTRAL", f.getValue());
f = abLabelIt.next();
assertEquals("item2", f.getGroup());
assertEquals("CustomAdrType", f.getValue());
f = abLabelIt.next();
assertEquals("item3", f.getGroup());
assertEquals("PROFILE", f.getValue());
f = abLabelIt.next();
assertEquals("item4", f.getGroup());
assertEquals("_$!<Anniversary>!$_", f.getValue());
f = abLabelIt.next();
assertEquals("item5", f.getGroup());
assertEquals("_$!<Spouse>!$_", f.getValue());
f = abLabelIt.next();
assertEquals("item6", f.getGroup());
assertEquals("CustomRelationship", f.getValue());
assertFalse(abLabelIt.hasNext());
}
f = vcard.getExtendedType("X-ABDATE").get(0);
assertEquals("item4", f.getGroup());
assertEquals("X-ABDATE", f.getTypeName());
assertEquals("1970-06-02", f.getValue());
f = vcard.getExtendedType("X-ABRELATEDNAMES").get(0);
assertEquals("item5", f.getGroup());
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("MySpouse", f.getValue());
f = vcard.getExtendedType("X-ABRELATEDNAMES").get(1);
assertEquals("item6", f.getGroup());
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("MyCustom", f.getValue());
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void gmailSingle() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("gmail-single.vcf"));
reader.setCompatibilityMode(CompatibilityMode.GMAIL);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Greg Dartmouth", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Dartmouth", f.getFamily());
assertEquals("Greg", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertTrue(f.getPrefixes().isEmpty());
assertTrue(f.getSuffixes().isEmpty());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("555 555 1111", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
f = it.next();
assertEquals("item1", f.getGroup());
assertEquals("555 555 2222", f.getValue());
types = f.getTypes();
assertTrue(types.isEmpty());
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("123 Home St" + newline + "Home City, HM 12345", f.getStreetAddress());
assertEquals(null, f.getLocality());
assertEquals(null, f.getRegion());
assertEquals(null, f.getPostalCode());
assertEquals(null, f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
f = it.next();
assertEquals("item2", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("321 Custom St", f.getStreetAddress());
assertEquals("Custom City", f.getLocality());
assertEquals("TX", f.getRegion());
assertEquals("98765", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertTrue(types.isEmpty());
assertFalse(it.hasNext());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("TheCompany"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("TheJobTitle", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1960);
c.set(Calendar.MONTH, Calendar.SEPTEMBER);
c.set(Calendar.DAY_OF_MONTH, 10);
assertEquals(c.getTime(), f.getDate());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://TheProfile.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertTrue(types.isEmpty());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is GMail's note field." + newline + "It should be added as a NOTE type." + newline + "ACustomField: CustomField", f.getValue());
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(12, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-PHONETIC-FIRST-NAME").get(0);
assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName());
assertEquals("Grregg", f.getValue());
f = vcard.getExtendedType("X-PHONETIC-LAST-NAME").get(0);
assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName());
assertEquals("Dart-mowth", f.getValue());
f = vcard.getExtendedType("X-ICQ").get(0);
assertEquals("X-ICQ", f.getTypeName());
assertEquals("123456789", f.getValue());
Iterator<RawType> abLabelIt = vcard.getExtendedType("X-ABLABEL").iterator();
{
f = abLabelIt.next();
assertEquals("item1", f.getGroup());
assertEquals("GRAND_CENTRAL", f.getValue());
f = abLabelIt.next();
assertEquals("item2", f.getGroup());
assertEquals("CustomAdrType", f.getValue());
f = abLabelIt.next();
assertEquals("item3", f.getGroup());
assertEquals("PROFILE", f.getValue());
f = abLabelIt.next();
assertEquals("item4", f.getGroup());
assertEquals("_$!<Anniversary>!$_", f.getValue());
f = abLabelIt.next();
assertEquals("item5", f.getGroup());
assertEquals("_$!<Spouse>!$_", f.getValue());
f = abLabelIt.next();
assertEquals("item6", f.getGroup());
assertEquals("CustomRelationship", f.getValue());
assertFalse(abLabelIt.hasNext());
}
f = vcard.getExtendedType("X-ABDATE").get(0);
assertEquals("item4", f.getGroup());
assertEquals("X-ABDATE", f.getTypeName());
assertEquals("1970-06-02", f.getValue());
f = vcard.getExtendedType("X-ABRELATEDNAMES").get(0);
assertEquals("item5", f.getGroup());
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("MySpouse", f.getValue());
f = vcard.getExtendedType("X-ABRELATEDNAMES").get(1);
assertEquals("item6", f.getGroup());
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("MyCustom", f.getValue());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void gmailSingle() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("gmail-single.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Greg Dartmouth", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Dartmouth", f.getFamily());
assertEquals("Greg", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertTrue(f.getPrefixes().isEmpty());
assertTrue(f.getSuffixes().isEmpty());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("555 555 1111", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
f = it.next();
assertEquals("item1", f.getGroup());
assertEquals("555 555 2222", f.getText());
types = f.getTypes();
assertTrue(types.isEmpty());
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("123 Home St" + NEWLINE + "Home City, HM 12345", f.getStreetAddress());
assertEquals(null, f.getLocality());
assertEquals(null, f.getRegion());
assertEquals(null, f.getPostalCode());
assertEquals(null, f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
f = it.next();
assertEquals("item2", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("321 Custom St", f.getStreetAddress());
assertEquals("Custom City", f.getLocality());
assertEquals("TX", f.getRegion());
assertEquals("98765", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertTrue(types.isEmpty());
assertFalse(it.hasNext());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("TheCompany"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("TheJobTitle", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1960);
c.set(Calendar.MONTH, Calendar.SEPTEMBER);
c.set(Calendar.DAY_OF_MONTH, 10);
assertEquals(c.getTime(), f.getDate());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://TheProfile.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertTrue(types.isEmpty());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is GMail's note field." + NEWLINE + "It should be added as a NOTE type." + NEWLINE + "ACustomField: CustomField", f.getValue());
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(12, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0);
assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName());
assertEquals("Grregg", f.getValue());
f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0);
assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName());
assertEquals("Dart-mowth", f.getValue());
f = vcard.getExtendedProperties("X-ICQ").get(0);
assertEquals("X-ICQ", f.getTypeName());
assertEquals("123456789", f.getValue());
Iterator<RawType> abLabelIt = vcard.getExtendedProperties("X-ABLABEL").iterator();
{
f = abLabelIt.next();
assertEquals("item1", f.getGroup());
assertEquals("GRAND_CENTRAL", f.getValue());
f = abLabelIt.next();
assertEquals("item2", f.getGroup());
assertEquals("CustomAdrType", f.getValue());
f = abLabelIt.next();
assertEquals("item3", f.getGroup());
assertEquals("PROFILE", f.getValue());
f = abLabelIt.next();
assertEquals("item4", f.getGroup());
assertEquals("_$!<Anniversary>!$_", f.getValue());
f = abLabelIt.next();
assertEquals("item5", f.getGroup());
assertEquals("_$!<Spouse>!$_", f.getValue());
f = abLabelIt.next();
assertEquals("item6", f.getGroup());
assertEquals("CustomRelationship", f.getValue());
assertFalse(abLabelIt.hasNext());
}
f = vcard.getExtendedProperties("X-ABDATE").get(0);
assertEquals("item4", f.getGroup());
assertEquals("X-ABDATE", f.getTypeName());
assertEquals("1970-06-02", f.getValue());
f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0);
assertEquals("item5", f.getGroup());
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("MySpouse", f.getValue());
f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(1);
assertEquals("item6", f.getGroup());
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("MyCustom", f.getValue());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void gmailSingle() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("gmail-single.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Greg Dartmouth", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Dartmouth", f.getFamily());
assertEquals("Greg", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertTrue(f.getPrefixes().isEmpty());
assertTrue(f.getSuffixes().isEmpty());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("555 555 1111", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
f = it.next();
assertEquals("item1", f.getGroup());
assertEquals("555 555 2222", f.getText());
types = f.getTypes();
assertTrue(types.isEmpty());
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("123 Home St" + NEWLINE + "Home City, HM 12345", f.getStreetAddress());
assertEquals(null, f.getLocality());
assertEquals(null, f.getRegion());
assertEquals(null, f.getPostalCode());
assertEquals(null, f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
f = it.next();
assertEquals("item2", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("321 Custom St", f.getStreetAddress());
assertEquals("Custom City", f.getLocality());
assertEquals("TX", f.getRegion());
assertEquals("98765", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertTrue(types.isEmpty());
assertFalse(it.hasNext());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("TheCompany"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("TheJobTitle", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1960);
c.set(Calendar.MONTH, Calendar.SEPTEMBER);
c.set(Calendar.DAY_OF_MONTH, 10);
assertEquals(c.getTime(), f.getDate());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://TheProfile.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertTrue(types.isEmpty());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is GMail's note field." + NEWLINE + "It should be added as a NOTE type." + NEWLINE + "ACustomField: CustomField", f.getValue());
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(12, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0);
assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName());
assertEquals("Grregg", f.getValue());
f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0);
assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName());
assertEquals("Dart-mowth", f.getValue());
f = vcard.getExtendedProperties("X-ICQ").get(0);
assertEquals("X-ICQ", f.getTypeName());
assertEquals("123456789", f.getValue());
Iterator<RawType> abLabelIt = vcard.getExtendedProperties("X-ABLABEL").iterator();
{
f = abLabelIt.next();
assertEquals("item1", f.getGroup());
assertEquals("GRAND_CENTRAL", f.getValue());
f = abLabelIt.next();
assertEquals("item2", f.getGroup());
assertEquals("CustomAdrType", f.getValue());
f = abLabelIt.next();
assertEquals("item3", f.getGroup());
assertEquals("PROFILE", f.getValue());
f = abLabelIt.next();
assertEquals("item4", f.getGroup());
assertEquals("_$!<Anniversary>!$_", f.getValue());
f = abLabelIt.next();
assertEquals("item5", f.getGroup());
assertEquals("_$!<Spouse>!$_", f.getValue());
f = abLabelIt.next();
assertEquals("item6", f.getGroup());
assertEquals("CustomRelationship", f.getValue());
assertFalse(abLabelIt.hasNext());
}
f = vcard.getExtendedProperties("X-ABDATE").get(0);
assertEquals("item4", f.getGroup());
assertEquals("X-ABDATE", f.getTypeName());
assertEquals("1970-06-02", f.getValue());
f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0);
assertEquals("item5", f.getGroup());
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("MySpouse", f.getValue());
f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(1);
assertEquals("item6", f.getGroup());
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("MyCustom", f.getValue());
}
assertWarnings(0, reader.getWarnings());
assertNull(reader.readNext());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void msOutlookVCard() throws Exception {
VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("John_Doe_MS_OUTLOOK.vcf")));
reader.setCompatibilityMode(CompatibilityMode.MS_OUTLOOK);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V2_1, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("en-us", f.getSubTypes().getLanguage());
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter", "James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter James Doe Sr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY GEORGE EL-HADDAD ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GEORGE EL-HADDAD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", f.getValue());
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("(905) 555-1234", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(905) 666-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Cresent moon drive", f.getStreetAddress());
assertEquals("Albaney", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
assertEquals("Cresent moon drive\r\nAlbaney, New York 12345", f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertTrue(types.contains(AddressTypeParameter.PREF));
f = it.next();
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Silicon Alley 5,", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
assertEquals("Silicon Alley 5,\r\nNew York, New York 12345", f.getLabel());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertFalse(it.hasNext());
}
//LABEL
{
assertTrue(vcard.getOrphanedLabels().isEmpty());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("Counting Money", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 22);
assertEquals(c.getTime(), f.getDate());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.PREF));
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(860, f.getData().length);
assertFalse(it.hasNext());
}
//REV
{
RevisionType f = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 5);
c.set(Calendar.HOUR_OF_DAY, 13);
c.set(Calendar.MINUTE, 19);
c.set(Calendar.SECOND, 33);
assertEquals(c.getTime(), f.getTimestamp());
}
//extended types
{
assertEquals(6, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0);
assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName());
assertEquals("2", f.getValue());
f = vcard.getExtendedType("X-MS-ANNIVERSARY").get(0);
assertEquals("X-MS-ANNIVERSARY", f.getTypeName());
assertEquals("20110113", f.getValue());
f = vcard.getExtendedType("X-MS-IMADDRESS").get(0);
assertEquals("X-MS-IMADDRESS", f.getTypeName());
assertEquals("[email protected]", f.getValue());
f = vcard.getExtendedType("X-MS-OL-DESIGN").get(0);
assertEquals("X-MS-OL-DESIGN", f.getTypeName());
assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue());
assertEquals("utf-8", f.getSubTypes().getCharset());
f = vcard.getExtendedType("X-MS-MANAGER").get(0);
assertEquals("X-MS-MANAGER", f.getTypeName());
assertEquals("Big Blue", f.getValue());
f = vcard.getExtendedType("X-MS-ASSISTANT").get(0);
assertEquals("X-MS-ASSISTANT", f.getTypeName());
assertEquals("Jenny", f.getValue());
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void msOutlookVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MS_OUTLOOK.vcf"));
reader.setCompatibilityMode(CompatibilityMode.MS_OUTLOOK);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V2_1, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("en-us", f.getSubTypes().getLanguage());
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter", "James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter James Doe Sr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY GEORGE EL-HADDAD ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GEORGE EL-HADDAD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.", f.getValue());
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("(905) 555-1234", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("(905) 666-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Cresent moon drive", f.getStreetAddress());
assertEquals("Albaney", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
assertEquals("Cresent moon drive\r\nAlbaney, New York 12345", f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertTrue(types.contains(AddressTypeParameter.PREF));
f = it.next();
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Silicon Alley 5,", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
assertEquals("Silicon Alley 5,\r\nNew York, New York 12345", f.getLabel());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertFalse(it.hasNext());
}
//LABEL
{
assertTrue(vcard.getOrphanedLabels().isEmpty());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("Counting Money", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 22);
assertEquals(c.getTime(), f.getDate());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.PREF));
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(860, f.getData().length);
assertFalse(it.hasNext());
}
//REV
{
RevisionType f = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 5);
c.set(Calendar.HOUR_OF_DAY, 13);
c.set(Calendar.MINUTE, 19);
c.set(Calendar.SECOND, 33);
assertEquals(c.getTime(), f.getTimestamp());
}
//extended types
{
assertEquals(6, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-MS-OL-DEFAULT-POSTAL-ADDRESS").get(0);
assertEquals("X-MS-OL-DEFAULT-POSTAL-ADDRESS", f.getTypeName());
assertEquals("2", f.getValue());
f = vcard.getExtendedType("X-MS-ANNIVERSARY").get(0);
assertEquals("X-MS-ANNIVERSARY", f.getTypeName());
assertEquals("20110113", f.getValue());
f = vcard.getExtendedType("X-MS-IMADDRESS").get(0);
assertEquals("X-MS-IMADDRESS", f.getTypeName());
assertEquals("[email protected]", f.getValue());
f = vcard.getExtendedType("X-MS-OL-DESIGN").get(0);
assertEquals("X-MS-OL-DESIGN", f.getTypeName());
assertEquals("<card xmlns=\"http://schemas.microsoft.com/office/outlook/12/electronicbusinesscards\" ver=\"1.0\" layout=\"left\" bgcolor=\"ffffff\"><img xmlns=\"\" align=\"tleft\" area=\"32\" use=\"photo\"/><fld xmlns=\"\" prop=\"name\" align=\"left\" dir=\"ltr\" style=\"b\" color=\"000000\" size=\"10\"/><fld xmlns=\"\" prop=\"org\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"title\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"dept\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"telwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Work</label></fld><fld xmlns=\"\" prop=\"telhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"><label align=\"right\" color=\"626262\">Home</label></fld><fld xmlns=\"\" prop=\"email\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"addrhome\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"webwork\" align=\"left\" dir=\"ltr\" color=\"000000\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/><fld xmlns=\"\" prop=\"blank\" size=\"8\"/></card>", f.getValue());
assertEquals("utf-8", f.getSubTypes().getCharset());
f = vcard.getExtendedType("X-MS-MANAGER").get(0);
assertEquals("X-MS-MANAGER", f.getTypeName());
assertEquals("Big Blue", f.getValue());
f = vcard.getExtendedType("X-MS-ASSISTANT").get(0);
assertEquals("X-MS-ASSISTANT", f.getTypeName());
assertEquals("Jenny", f.getValue());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void doMarshalValue(StringBuilder sb, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) {
//VCardWriter handles 2.1 AGENT types that have an embedded vCard.
//this method will not be called for these instances
if (url != null) {
sb.append(url);
} else {
StringWriter sw = new StringWriter();
VCardWriter writer = new VCardWriter(sw, version, null, "\n");
writer.setCompatibilityMode(compatibilityMode);
writer.setAddGenerator(false);
try {
writer.write(vcard);
} catch (IOException e) {
//never thrown because we're writing to a string
}
String str = sw.toString();
for (String w : writer.getWarnings()) {
warnings.add("AGENT marshal warning: " + w);
}
sb.append(VCardStringUtils.escapeText(str));
}
}
#location 20
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
protected void doMarshalValue(StringBuilder sb, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) {
if (url != null) {
sb.append(url);
} else if (vcard != null) {
throw new EmbeddedVCardException(vcard);
} else {
throw new SkipMeException("Property has neither a URL nor an embedded vCard.");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void iPhoneVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_IPHONE.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//PRODID
{
ProdIdType f = vcard.getProdId();
assertEquals("-//Apple Inc.//iOS 5.0.1//EN", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter", "James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter James Doe Sr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("item1", f.getGroup());
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(EmailTypeParameter.PREF));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("905-555-1234", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertTrue(types.contains(TelephoneTypeParameter.PREF));
f = it.next();
assertEquals("905-666-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("905-777-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("905-888-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-999-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-111-1234", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.PAGER));
f = it.next();
assertEquals("905-222-1234", f.getText());
assertEquals("item2", f.getGroup());
types = f.getTypes();
assertEquals(0, types.size());
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals("item3", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Silicon Alley 5,", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PREF));
f = it.next();
assertEquals("item4", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Street4" + NEWLINE + "Building 6" + NEWLINE + "Floor 8", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals(null, f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("item5", f.getGroup());
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.JUNE);
c.set(Calendar.DAY_OF_MONTH, 6);
assertEquals(c.getTime(), f.getDate());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(32531, f.getData().length);
}
//extended types
{
assertEquals(4, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-ABLABEL").get(0);
assertEquals("item2", f.getGroup());
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("_$!<AssistantPhone>!$_", f.getValue());
f = vcard.getExtendedProperties("X-ABADR").get(0);
assertEquals("item3", f.getGroup());
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Silicon Alley", f.getValue());
f = vcard.getExtendedProperties("X-ABADR").get(1);
assertEquals("item4", f.getGroup());
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Street 4, Building 6,\\n Floor 8\\nNew York\\nUSA", f.getValue());
f = vcard.getExtendedProperties("X-ABLABEL").get(1);
assertEquals("item5", f.getGroup());
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("_$!<HomePage>!$_", f.getValue());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void iPhoneVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_IPHONE.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//PRODID
{
ProdIdType f = vcard.getProdId();
assertEquals("-//Apple Inc.//iOS 5.0.1//EN", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter", "James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter James Doe Sr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("item1", f.getGroup());
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(EmailTypeParameter.PREF));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("905-555-1234", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertTrue(types.contains(TelephoneTypeParameter.PREF));
f = it.next();
assertEquals("905-666-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("905-777-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("905-888-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-999-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-111-1234", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.PAGER));
f = it.next();
assertEquals("905-222-1234", f.getText());
assertEquals("item2", f.getGroup());
types = f.getTypes();
assertEquals(0, types.size());
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals("item3", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Silicon Alley 5,", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PREF));
f = it.next();
assertEquals("item4", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Street4" + NEWLINE + "Building 6" + NEWLINE + "Floor 8", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals(null, f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("item5", f.getGroup());
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.JUNE);
c.set(Calendar.DAY_OF_MONTH, 6);
assertEquals(c.getTime(), f.getDate());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(32531, f.getData().length);
}
//extended types
{
assertEquals(4, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-ABLABEL").get(0);
assertEquals("item2", f.getGroup());
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("_$!<AssistantPhone>!$_", f.getValue());
f = vcard.getExtendedProperties("X-ABADR").get(0);
assertEquals("item3", f.getGroup());
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Silicon Alley", f.getValue());
f = vcard.getExtendedProperties("X-ABADR").get(1);
assertEquals("item4", f.getGroup());
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Street 4, Building 6,\\n Floor 8\\nNew York\\nUSA", f.getValue());
f = vcard.getExtendedProperties("X-ABLABEL").get(1);
assertEquals("item5", f.getGroup());
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("_$!<HomePage>!$_", f.getValue());
}
assertWarnings(0, reader.getWarnings());
assertNull(reader.readNext());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void labels() throws Exception {
VCard vcard = new VCard();
//address with label
AddressType adr = new AddressType();
adr.setStreetAddress("123 Main St.");
adr.setLocality("Austin");
adr.setRegion("TX");
adr.setPostalCode("12345");
adr.setLabel("123 Main St.\r\nAustin, TX 12345");
adr.addType(AddressTypeParameter.HOME);
vcard.addAddress(adr);
//address without label
adr = new AddressType();
adr.setStreetAddress("222 Broadway");
adr.setLocality("New York");
adr.setRegion("NY");
adr.setPostalCode("99999");
adr.addType(AddressTypeParameter.WORK);
vcard.addAddress(adr);
//orphaned label
LabelType label = new LabelType("22 Spruce Ln.\r\nChicago, IL 11111");
label.addType(AddressTypeParameter.PARCEL);
vcard.addOrphanedLabel(label);
//3.0
//LABEL types should be used
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V3_0, null);
vcw.setAddProdId(false);
vcw.write(vcard);
String actual = sw.toString();
StringBuilder sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:3.0\r\n");
sb.append("ADR;TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n");
sb.append("LABEL;TYPE=home:123 Main St.\\nAustin\\, TX 12345\r\n");
sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n");
sb.append("LABEL;TYPE=parcel:22 Spruce Ln.\\nChicago\\, IL 11111\r\n");
sb.append("END:VCARD\r\n");
String expected = sb.toString();
assertEquals(expected, actual);
//4.0
//LABEL parameters should be used
sw = new StringWriter();
vcw = new VCardWriter(sw, VCardVersion.V4_0, null);
vcw.setAddProdId(false);
vcw.write(vcard);
actual = sw.toString();
sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:4.0\r\n");
sb.append("ADR;LABEL=\"123 Main St.\\nAustin, TX 12345\";TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n");
sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n");
sb.append("END:VCARD\r\n");
expected = sb.toString();
assertEquals(expected, actual);
}
#location 34
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void labels() throws Exception {
VCard vcard = new VCard();
//address with label
AddressType adr = new AddressType();
adr.setStreetAddress("123 Main St.");
adr.setLocality("Austin");
adr.setRegion("TX");
adr.setPostalCode("12345");
adr.setLabel("123 Main St.\r\nAustin, TX 12345");
adr.addType(AddressTypeParameter.HOME);
vcard.addAddress(adr);
//address without label
adr = new AddressType();
adr.setStreetAddress("222 Broadway");
adr.setLocality("New York");
adr.setRegion("NY");
adr.setPostalCode("99999");
adr.addType(AddressTypeParameter.WORK);
vcard.addAddress(adr);
//orphaned label
LabelType label = new LabelType("22 Spruce Ln.\r\nChicago, IL 11111");
label.addType(AddressTypeParameter.PARCEL);
vcard.addOrphanedLabel(label);
//3.0
//LABEL types should be used
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V3_0, null, "\r\n");
vcw.setAddProdId(false);
vcw.write(vcard);
String actual = sw.toString();
StringBuilder sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:3.0\r\n");
sb.append("ADR;TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n");
sb.append("LABEL;TYPE=home:123 Main St.\\nAustin\\, TX 12345\r\n");
sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n");
sb.append("LABEL;TYPE=parcel:22 Spruce Ln.\\nChicago\\, IL 11111\r\n");
sb.append("END:VCARD\r\n");
String expected = sb.toString();
assertEquals(expected, actual);
//4.0
//LABEL parameters should be used
sw = new StringWriter();
vcw = new VCardWriter(sw, VCardVersion.V4_0, null, "\r\n");
vcw.setAddProdId(false);
vcw.write(vcard);
actual = sw.toString();
sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:4.0\r\n");
sb.append("ADR;LABEL=\"123 Main St.\\nAustin, TX 12345\";TYPE=home:;;123 Main St.;Austin;TX;12345;\r\n");
sb.append("ADR;TYPE=work:;;222 Broadway;New York;NY;99999;\r\n");
sb.append("END:VCARD\r\n");
expected = sb.toString();
assertEquals(expected, actual);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void thunderbird() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("thunderbird-MoreFunctionsForAddressBook-extension.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertTrue(f.getPrefixes().isEmpty());
assertTrue(f.getSuffixes().isEmpty());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("John Doe", f.getValue());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("TheOrganization", "TheDepartment"), f.getValues());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johnny"), f.getValues());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("222 Broadway", f.getExtendedAddress());
assertEquals("Suite 100", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("NY", f.getRegion());
assertEquals("98765", f.getPostalCode());
assertEquals("USA", f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertTrue(types.contains(AddressTypeParameter.POSTAL));
f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("123 Main St", f.getExtendedAddress());
assertEquals("Apt 10", f.getStreetAddress());
assertEquals("Austin", f.getLocality());
assertEquals("TX", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.POSTAL));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("555-555-1111", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("555-555-2222", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("555-555-5555", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("555-555-3333", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("555-555-4444", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.PAGER));
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(EmailTypeParameter.PREF));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://www.private-webpage.com", f.getValue());
assertEquals("HOME", f.getType());
f = it.next();
assertEquals("http://www.work-webpage.com", f.getValue());
assertEquals("WORK", f.getType());
assertFalse(it.hasNext());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("TheTitle", f.getValue());
assertFalse(it.hasNext());
}
//CATEGORIES
{
//commas are incorrectly escaped, so there is only 1 item
CategoriesType f = vcard.getCategories();
assertEquals(Arrays.asList("category1, category2, category3"), f.getValues());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1970);
c.set(Calendar.MONTH, Calendar.SEPTEMBER);
c.set(Calendar.DAY_OF_MONTH, 21);
assertEquals(c.getTime(), f.getDate());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is the notes field." + NEWLINE + "Second Line" + NEWLINE + NEWLINE + "Fourth Line" + NEWLINE + "You can put anything in the \"note\" field; even curse words.", f.getValue());
assertFalse(it.hasNext());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(8940, f.getData().length);
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(2, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-SPOUSE").get(0);
assertEquals("X-SPOUSE", f.getTypeName());
assertEquals("TheSpouse", f.getValue());
f = vcard.getExtendedProperties("X-ANNIVERSARY").get(0);
assertEquals("X-ANNIVERSARY", f.getTypeName());
assertEquals("1990-04-30", f.getValue());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void thunderbird() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("thunderbird-MoreFunctionsForAddressBook-extension.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertTrue(f.getPrefixes().isEmpty());
assertTrue(f.getSuffixes().isEmpty());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("John Doe", f.getValue());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("TheOrganization", "TheDepartment"), f.getValues());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johnny"), f.getValues());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("222 Broadway", f.getExtendedAddress());
assertEquals("Suite 100", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("NY", f.getRegion());
assertEquals("98765", f.getPostalCode());
assertEquals("USA", f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertTrue(types.contains(AddressTypeParameter.POSTAL));
f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("123 Main St", f.getExtendedAddress());
assertEquals("Apt 10", f.getStreetAddress());
assertEquals("Austin", f.getLocality());
assertEquals("TX", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.POSTAL));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("555-555-1111", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("555-555-2222", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("555-555-5555", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("555-555-3333", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("555-555-4444", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.PAGER));
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(EmailTypeParameter.PREF));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
f = it.next();
assertEquals("[email protected]", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://www.private-webpage.com", f.getValue());
assertEquals("HOME", f.getType());
f = it.next();
assertEquals("http://www.work-webpage.com", f.getValue());
assertEquals("WORK", f.getType());
assertFalse(it.hasNext());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("TheTitle", f.getValue());
assertFalse(it.hasNext());
}
//CATEGORIES
{
//commas are incorrectly escaped, so there is only 1 item
CategoriesType f = vcard.getCategories();
assertEquals(Arrays.asList("category1, category2, category3"), f.getValues());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1970);
c.set(Calendar.MONTH, Calendar.SEPTEMBER);
c.set(Calendar.DAY_OF_MONTH, 21);
assertEquals(c.getTime(), f.getDate());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is the notes field." + NEWLINE + "Second Line" + NEWLINE + NEWLINE + "Fourth Line" + NEWLINE + "You can put anything in the \"note\" field; even curse words.", f.getValue());
assertFalse(it.hasNext());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(8940, f.getData().length);
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(2, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-SPOUSE").get(0);
assertEquals("X-SPOUSE", f.getTypeName());
assertEquals("TheSpouse", f.getValue());
f = vcard.getExtendedProperties("X-ANNIVERSARY").get(0);
assertEquals("X-ANNIVERSARY", f.getTypeName());
assertEquals("1990-04-30", f.getValue());
}
assertWarnings(0, reader.getWarnings());
assertNull(reader.readNext());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void doUnmarshalValue(Element element, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) throws VCardException {
Element ele = XCardUtils.getFirstElement(element.getChildNodes());
value = ele.getTextContent();
if (value.matches("(?i)tel:.*")) {
//remove "tel:"
value = (value.length() > 4) ? value.substring(4) : "";
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected void doUnmarshalValue(Element element, VCardVersion version, List<String> warnings, CompatibilityMode compatibilityMode) throws VCardException {
String value = XCardUtils.getFirstChildText(element, "text", "uri");
if (value != null) {
parseValue(value);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void outlook2003VCard() throws Exception {
VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("outlook-2003.vcf")));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V2_1, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("III"), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("John Doe III", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Joey"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("Company, The", "TheDepartment"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("The Job Title", f.getValue());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is the note field!!\r\nSecond line\r\n\r\nThird line is empty\r\n", f.getValue());
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("BusinessPhone", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("HomePhone", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("MobilePhone", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("BusinessFaxPhone", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.FAX));
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("TheOffice", f.getExtendedAddress());
assertEquals("123 Main St", f.getStreetAddress());
assertEquals("Austin", f.getLocality());
assertEquals("TX", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
assertEquals("TheOffice\r\n123 Main St\r\nAustin, TX 12345\r\nUnited States of America", f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertFalse(it.hasNext());
}
//LABEL
{
assertTrue(vcard.getOrphanedLabels().isEmpty());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://web-page-address.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("TheProfession", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 21);
assertEquals(c.getTime(), f.getDate());
}
//KEY
{
Iterator<KeyType> it = vcard.getKeys().iterator();
KeyType f = it.next();
assertEquals(KeyTypeParameter.X509, f.getContentType());
assertEquals(805, f.getData().length);
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.PREF));
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//FBURL
{
Iterator<FbUrlType> it = vcard.getFbUrls().iterator();
//Outlook 2003 apparently doesn't output FBURL correctly:
//http://help.lockergnome.com/office/BUG-Outlook-2003-exports-FBURL-vCard-incorrectly--ftopict423660.html
FbUrlType f = it.next();
assertEquals("????????????????s????????????" + (char) 12, f.getValue());
assertFalse(it.hasNext());
}
//REV
{
RevisionType f = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.OCTOBER);
c.set(Calendar.DAY_OF_MONTH, 12);
c.set(Calendar.HOUR_OF_DAY, 21);
c.set(Calendar.MINUTE, 5);
c.set(Calendar.SECOND, 25);
assertEquals(c.getTime(), f.getTimestamp());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void outlook2003VCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2003.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V2_1, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("III"), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("John Doe III", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Joey"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("Company, The", "TheDepartment"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("The Job Title", f.getValue());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is the note field!!\r\nSecond line\r\n\r\nThird line is empty\r\n", f.getValue());
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("BusinessPhone", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("HomePhone", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("MobilePhone", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("BusinessFaxPhone", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.FAX));
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("TheOffice", f.getExtendedAddress());
assertEquals("123 Main St", f.getStreetAddress());
assertEquals("Austin", f.getLocality());
assertEquals("TX", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
assertEquals("TheOffice\r\n123 Main St\r\nAustin, TX 12345\r\nUnited States of America", f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertFalse(it.hasNext());
}
//LABEL
{
assertTrue(vcard.getOrphanedLabels().isEmpty());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://web-page-address.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("TheProfession", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 21);
assertEquals(c.getTime(), f.getDate());
}
//KEY
{
Iterator<KeyType> it = vcard.getKeys().iterator();
KeyType f = it.next();
assertEquals(KeyTypeParameter.X509, f.getContentType());
assertEquals(805, f.getData().length);
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.PREF));
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//FBURL
{
Iterator<FbUrlType> it = vcard.getFbUrls().iterator();
//Outlook 2003 apparently doesn't output FBURL correctly:
//http://help.lockergnome.com/office/BUG-Outlook-2003-exports-FBURL-vCard-incorrectly--ftopict423660.html
FbUrlType f = it.next();
assertEquals("????????????????s????????????" + (char) 12, f.getValue());
assertFalse(it.hasNext());
}
//REV
{
RevisionType f = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.OCTOBER);
c.set(Calendar.DAY_OF_MONTH, 12);
c.set(Calendar.HOUR_OF_DAY, 21);
c.set(Calendar.MINUTE, 5);
c.set(Calendar.SECOND, 25);
assertEquals(c.getTime(), f.getTimestamp());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void iPhoneVCard() throws Exception {
VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("John_Doe_IPHONE.vcf")));
reader.setCompatibilityMode(CompatibilityMode.I_PHONE);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//PRODID
{
ProdIdType f = vcard.getProdId();
assertEquals("-//Apple Inc.//iOS 5.0.1//EN", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter", "James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter James Doe Sr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("item1", f.getGroup());
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(EmailTypeParameter.PREF));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("905-555-1234", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertTrue(types.contains(TelephoneTypeParameter.PREF));
f = it.next();
assertEquals("905-666-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("905-777-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("905-888-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-999-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-111-1234", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.PAGER));
f = it.next();
assertEquals("905-222-1234", f.getValue());
assertEquals("item2", f.getGroup());
types = f.getTypes();
assertEquals(0, types.size());
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals("item3", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Silicon Alley 5,", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PREF));
f = it.next();
assertEquals("item4", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Street4" + newline + "Building 6" + newline + "Floor 8", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals(null, f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("item5", f.getGroup());
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.JUNE);
c.set(Calendar.DAY_OF_MONTH, 6);
assertEquals(c.getTime(), f.getDate());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(32531, f.getData().length);
}
//extended types
{
assertEquals(4, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-ABLABEL").get(0);
assertEquals("item2", f.getGroup());
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("_$!<AssistantPhone>!$_", f.getValue());
f = vcard.getExtendedType("X-ABADR").get(0);
assertEquals("item3", f.getGroup());
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Silicon Alley", f.getValue());
f = vcard.getExtendedType("X-ABADR").get(1);
assertEquals("item4", f.getGroup());
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Street 4, Building 6,\\n Floor 8\\nNew York\\nUSA", f.getValue());
f = vcard.getExtendedType("X-ABLABEL").get(1);
assertEquals("item5", f.getGroup());
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("_$!<HomePage>!$_", f.getValue());
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void iPhoneVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_IPHONE.vcf"));
reader.setCompatibilityMode(CompatibilityMode.I_PHONE);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//PRODID
{
ProdIdType f = vcard.getProdId();
assertEquals("-//Apple Inc.//iOS 5.0.1//EN", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter", "James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter James Doe Sr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("item1", f.getGroup());
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(EmailTypeParameter.PREF));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("905-555-1234", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
assertTrue(types.contains(TelephoneTypeParameter.PREF));
f = it.next();
assertEquals("905-666-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("905-777-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("905-888-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-999-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-111-1234", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.PAGER));
f = it.next();
assertEquals("905-222-1234", f.getValue());
assertEquals("item2", f.getGroup());
types = f.getTypes();
assertEquals(0, types.size());
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals("item3", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Silicon Alley 5,", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PREF));
f = it.next();
assertEquals("item4", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Street4" + newline + "Building 6" + newline + "Floor 8", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals(null, f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("item5", f.getGroup());
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.JUNE);
c.set(Calendar.DAY_OF_MONTH, 6);
assertEquals(c.getTime(), f.getDate());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(ImageTypeParameter.JPEG, f.getContentType());
assertEquals(32531, f.getData().length);
}
//extended types
{
assertEquals(4, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-ABLABEL").get(0);
assertEquals("item2", f.getGroup());
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("_$!<AssistantPhone>!$_", f.getValue());
f = vcard.getExtendedType("X-ABADR").get(0);
assertEquals("item3", f.getGroup());
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Silicon Alley", f.getValue());
f = vcard.getExtendedType("X-ABADR").get(1);
assertEquals("item4", f.getGroup());
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Street 4, Building 6,\\n Floor 8\\nNew York\\nUSA", f.getValue());
f = vcard.getExtendedType("X-ABLABEL").get(1);
assertEquals("item5", f.getGroup());
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("_$!<HomePage>!$_", f.getValue());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
VCard vcard = new VCard();
StructuredNameType n = new StructuredNameType();
n.setFamily("Angstadt");
n.setGiven("Michael");
n.addPrefix("Mr");
vcard.setStructuredName(n);
vcard.setFormattedName(new FormattedNameType("Michael Angstadt"));
NicknameType nickname = new NicknameType();
nickname.addValue("Mike");
vcard.setNickname(nickname);
vcard.addTitle(new TitleType("Software Engineer"));
EmailType email = new EmailType("[email protected]");
vcard.addEmail(email);
UrlType url = new UrlType("http://mikeangstadt.name");
vcard.addUrl(url);
CategoriesType categories = new CategoriesType();
categories.addValue("Java software engineer");
categories.addValue("vCard expert");
categories.addValue("Nice guy!!");
vcard.setCategories(categories);
vcard.setGeo(new GeoType(39.95, -75.1667));
vcard.setTimezone(new TimezoneType(-5, 0, "America/New_York"));
byte portrait[] = getFileBytes("portrait.jpg");
PhotoType photo = new PhotoType(portrait, ImageTypeParameter.JPEG);
vcard.addPhoto(photo);
byte pronunciation[] = getFileBytes("pronunciation.ogg");
SoundType sound = new SoundType(pronunciation, SoundTypeParameter.OGG);
vcard.addSound(sound);
//vcard.setUid(UidType.random());
vcard.setUid(new UidType("urn:uuid:dd418720-c754-4631-a869-db89d02b831b"));
vcard.addSource(new SourceType("http://mikeangstadt.name/mike-angstadt.vcf"));
vcard.setRevision(new RevisionType(new Date()));
//write vCard to file
Writer writer = new FileWriter("mike-angstadt.vcf");
VCardWriter vcw = new VCardWriter(writer, VCardVersion.V3_0);
vcw.write(vcard);
List<String> warnings = vcw.getWarnings();
System.out.println("Completed with " + warnings.size() + " warnings.");
for (String warning : warnings) {
System.out.println("* " + warning);
}
writer.close();
}
#location 57
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception {
VCard vcard = new VCard();
StructuredNameType n = new StructuredNameType();
n.setFamily("Angstadt");
n.setGiven("Michael");
n.addPrefix("Mr");
vcard.setStructuredName(n);
vcard.setFormattedName(new FormattedNameType("Michael Angstadt"));
NicknameType nickname = new NicknameType();
nickname.addValue("Mike");
vcard.setNickname(nickname);
vcard.addTitle(new TitleType("Software Engineer"));
EmailType email = new EmailType("[email protected]");
vcard.addEmail(email);
UrlType url = new UrlType("http://mikeangstadt.name");
vcard.addUrl(url);
CategoriesType categories = new CategoriesType();
categories.addValue("Java software engineer");
categories.addValue("vCard expert");
categories.addValue("Nice guy!!");
vcard.setCategories(categories);
vcard.setGeo(new GeoType(39.95, -75.1667));
vcard.setTimezone(new TimezoneType(-5, 0, "America/New_York"));
byte portrait[] = getFileBytes("portrait.jpg");
PhotoType photo = new PhotoType(portrait, ImageTypeParameter.JPEG);
vcard.addPhoto(photo);
byte pronunciation[] = getFileBytes("pronunciation.ogg");
SoundType sound = new SoundType(pronunciation, SoundTypeParameter.OGG);
vcard.addSound(sound);
//vcard.setUid(UidType.random());
vcard.setUid(new UidType("urn:uuid:dd418720-c754-4631-a869-db89d02b831b"));
vcard.addSource(new SourceType("http://mikeangstadt.name/mike-angstadt.vcf"));
vcard.setRevision(new RevisionType(new Date()));
//write vCard to file
File file = new File("mike-angstadt.vcf");
System.out.println("Writing " + file.getName() + "...");
Writer writer = new FileWriter(file);
VCardWriter vcw = new VCardWriter(writer, VCardVersion.V3_0);
vcw.write(vcard);
List<String> warnings = vcw.getWarnings();
System.out.println("Completed with " + warnings.size() + " warnings.");
for (String warning : warnings) {
System.out.println("* " + warning);
}
writer.close();
System.out.println();
file = new File("mike-angstadt.xml");
System.out.println("Writing " + file.getName() + "...");
writer = new FileWriter(file);
XCardMarshaller xcm = new XCardMarshaller();
xcm.addVCard(vcard);
xcm.write(writer);
warnings = xcm.getWarnings();
System.out.println("Completed with " + warnings.size() + " warnings.");
for (String warning : warnings) {
System.out.println("* " + warning);
}
writer.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void macAddressBookVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MAC_ADDRESS_BOOK.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter,James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter,James Doe Sr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("work")));
assertTrue(types.contains(EmailTypeParameter.PREF));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("905-777-1234", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.PREF));
f = it.next();
assertEquals("905-666-1234", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
f = it.next();
assertEquals("905-555-1234", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
f = it.next();
assertEquals("905-888-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-999-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-111-1234", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.PAGER));
f = it.next();
assertEquals("905-222-1234", f.getText());
assertEquals("item1", f.getGroup());
types = f.getTypes();
assertEquals(0, types.size());
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals("item2", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Silicon Alley 5,", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PREF));
f = it.next();
assertEquals("item3", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Street4" + NEWLINE + "Building 6" + NEWLINE + "Floor 8", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals(null, f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + NEWLINE + "Favotire Color: Blue", f.getValue());
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("item4", f.getGroup());
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.JUNE);
c.set(Calendar.DAY_OF_MONTH, 6);
assertEquals(c.getTime(), f.getDate());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(null, f.getContentType());
assertEquals(18242, f.getData().length);
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(9, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0);
assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName());
assertEquals("Jon", f.getValue());
f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0);
assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName());
assertEquals("Dow", f.getValue());
f = vcard.getExtendedProperties("X-ABLABEL").get(0);
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("AssistantPhone", f.getValue());
assertEquals("item1", f.getGroup());
f = vcard.getExtendedProperties("X-ABADR").get(0);
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Silicon Alley", f.getValue());
assertEquals("item2", f.getGroup());
f = vcard.getExtendedProperties("X-ABADR").get(1);
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Street 4, Building 6,\\nFloor 8\\nNew York\\nUSA", f.getValue());
assertEquals("item3", f.getGroup());
f = vcard.getExtendedProperties("X-ABLABEL").get(1);
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("_$!<HomePage>!$_", f.getValue());
assertEquals("item4", f.getGroup());
f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0);
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("Jenny", f.getValue());
assertEquals("item5", f.getGroup());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
f = vcard.getExtendedProperties("X-ABLABEL").get(2);
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("Spouse", f.getValue());
assertEquals("item5", f.getGroup());
f = vcard.getExtendedProperties("X-ABUID").get(0);
assertEquals("X-ABUID", f.getTypeName());
assertEquals("6B29A774-D124-4822-B8D0-2780EC117F60\\:ABPerson", f.getValue());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void macAddressBookVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MAC_ADDRESS_BOOK.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter,James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter,James Doe Sr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("work")));
assertTrue(types.contains(EmailTypeParameter.PREF));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("905-777-1234", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.PREF));
f = it.next();
assertEquals("905-666-1234", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
f = it.next();
assertEquals("905-555-1234", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
f = it.next();
assertEquals("905-888-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-999-1234", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-111-1234", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.PAGER));
f = it.next();
assertEquals("905-222-1234", f.getText());
assertEquals("item1", f.getGroup());
types = f.getTypes();
assertEquals(0, types.size());
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals("item2", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Silicon Alley 5,", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PREF));
f = it.next();
assertEquals("item3", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Street4" + NEWLINE + "Building 6" + NEWLINE + "Floor 8", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals(null, f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + NEWLINE + "Favotire Color: Blue", f.getValue());
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("item4", f.getGroup());
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.JUNE);
c.set(Calendar.DAY_OF_MONTH, 6);
assertEquals(c.getTime(), f.getDate());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(null, f.getContentType());
assertEquals(18242, f.getData().length);
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(9, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0);
assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName());
assertEquals("Jon", f.getValue());
f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0);
assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName());
assertEquals("Dow", f.getValue());
f = vcard.getExtendedProperties("X-ABLABEL").get(0);
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("AssistantPhone", f.getValue());
assertEquals("item1", f.getGroup());
f = vcard.getExtendedProperties("X-ABADR").get(0);
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Silicon Alley", f.getValue());
assertEquals("item2", f.getGroup());
f = vcard.getExtendedProperties("X-ABADR").get(1);
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Street 4, Building 6,\\nFloor 8\\nNew York\\nUSA", f.getValue());
assertEquals("item3", f.getGroup());
f = vcard.getExtendedProperties("X-ABLABEL").get(1);
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("_$!<HomePage>!$_", f.getValue());
assertEquals("item4", f.getGroup());
f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0);
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("Jenny", f.getValue());
assertEquals("item5", f.getGroup());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
f = vcard.getExtendedProperties("X-ABLABEL").get(2);
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("Spouse", f.getValue());
assertEquals("item5", f.getGroup());
f = vcard.getExtendedProperties("X-ABUID").get(0);
assertEquals("X-ABUID", f.getTypeName());
assertEquals("6B29A774-D124-4822-B8D0-2780EC117F60\\:ABPerson", f.getValue());
}
assertWarnings(0, reader.getWarnings());
assertNull(reader.readNext());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void macAddressBookVCard() throws Exception {
VCardReader reader = new VCardReader(new InputStreamReader(getClass().getResourceAsStream("John_Doe_MAC_ADDRESS_BOOK.vcf")));
reader.setCompatibilityMode(CompatibilityMode.MAC_ADDRESS_BOOK);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter,James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter,James Doe Sr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("work")));
assertTrue(types.contains(EmailTypeParameter.PREF));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("905-777-1234", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.PREF));
f = it.next();
assertEquals("905-666-1234", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
f = it.next();
assertEquals("905-555-1234", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
f = it.next();
assertEquals("905-888-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-999-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-111-1234", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.PAGER));
f = it.next();
assertEquals("905-222-1234", f.getValue());
assertEquals("item1", f.getGroup());
types = f.getTypes();
assertEquals(0, types.size());
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals("item2", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Silicon Alley 5,", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PREF));
f = it.next();
assertEquals("item3", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Street4" + newline + "Building 6" + newline + "Floor 8", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals(null, f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + newline + "Favotire Color: Blue", f.getValue());
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("item4", f.getGroup());
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.JUNE);
c.set(Calendar.DAY_OF_MONTH, 6);
assertEquals(c.getTime(), f.getDate());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(null, f.getContentType());
assertEquals(18242, f.getData().length);
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(9, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-PHONETIC-FIRST-NAME").get(0);
assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName());
assertEquals("Jon", f.getValue());
f = vcard.getExtendedType("X-PHONETIC-LAST-NAME").get(0);
assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName());
assertEquals("Dow", f.getValue());
f = vcard.getExtendedType("X-ABLABEL").get(0);
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("AssistantPhone", f.getValue());
assertEquals("item1", f.getGroup());
f = vcard.getExtendedType("X-ABADR").get(0);
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Silicon Alley", f.getValue());
assertEquals("item2", f.getGroup());
f = vcard.getExtendedType("X-ABADR").get(1);
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Street 4, Building 6,\\nFloor 8\\nNew York\\nUSA", f.getValue());
assertEquals("item3", f.getGroup());
f = vcard.getExtendedType("X-ABLABEL").get(1);
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("_$!<HomePage>!$_", f.getValue());
assertEquals("item4", f.getGroup());
f = vcard.getExtendedType("X-ABRELATEDNAMES").get(0);
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("Jenny", f.getValue());
assertEquals("item5", f.getGroup());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
f = vcard.getExtendedType("X-ABLABEL").get(2);
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("Spouse", f.getValue());
assertEquals("item5", f.getGroup());
f = vcard.getExtendedType("X-ABUID").get(0);
assertEquals("X-ABUID", f.getTypeName());
assertEquals("6B29A774-D124-4822-B8D0-2780EC117F60\\:ABPerson", f.getValue());
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void macAddressBookVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_MAC_ADDRESS_BOOK.vcf"));
reader.setCompatibilityMode(CompatibilityMode.MAC_ADDRESS_BOOK);
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter,James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter,James Doe Sr.", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Johny"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM", "Accounting"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(3, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("work")));
assertTrue(types.contains(EmailTypeParameter.PREF));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("905-777-1234", f.getValue());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.PREF));
f = it.next();
assertEquals("905-666-1234", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
f = it.next();
assertEquals("905-555-1234", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
f = it.next();
assertEquals("905-888-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-999-1234", f.getValue());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.FAX));
f = it.next();
assertEquals("905-111-1234", f.getValue());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.PAGER));
f = it.next();
assertEquals("905-222-1234", f.getValue());
assertEquals("item1", f.getGroup());
types = f.getTypes();
assertEquals(0, types.size());
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals("item2", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Silicon Alley 5,", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals("New York", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertTrue(types.contains(AddressTypeParameter.PREF));
f = it.next();
assertEquals("item3", f.getGroup());
assertEquals(null, f.getPoBox());
assertEquals(null, f.getExtendedAddress());
assertEquals("Street4" + newline + "Building 6" + newline + "Floor 8", f.getStreetAddress());
assertEquals("New York", f.getLocality());
assertEquals(null, f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("USA", f.getCountry());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + newline + "Favotire Color: Blue", f.getValue());
assertFalse(it.hasNext());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("item4", f.getGroup());
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.JUNE);
c.set(Calendar.DAY_OF_MONTH, 6);
assertEquals(c.getTime(), f.getDate());
}
//PHOTO
{
Iterator<PhotoType> it = vcard.getPhotos().iterator();
PhotoType f = it.next();
assertEquals(null, f.getContentType());
assertEquals(18242, f.getData().length);
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(9, countExtTypes(vcard));
RawType f = vcard.getExtendedType("X-PHONETIC-FIRST-NAME").get(0);
assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName());
assertEquals("Jon", f.getValue());
f = vcard.getExtendedType("X-PHONETIC-LAST-NAME").get(0);
assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName());
assertEquals("Dow", f.getValue());
f = vcard.getExtendedType("X-ABLABEL").get(0);
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("AssistantPhone", f.getValue());
assertEquals("item1", f.getGroup());
f = vcard.getExtendedType("X-ABADR").get(0);
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Silicon Alley", f.getValue());
assertEquals("item2", f.getGroup());
f = vcard.getExtendedType("X-ABADR").get(1);
assertEquals("X-ABADR", f.getTypeName());
assertEquals("Street 4, Building 6,\\nFloor 8\\nNew York\\nUSA", f.getValue());
assertEquals("item3", f.getGroup());
f = vcard.getExtendedType("X-ABLABEL").get(1);
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("_$!<HomePage>!$_", f.getValue());
assertEquals("item4", f.getGroup());
f = vcard.getExtendedType("X-ABRELATEDNAMES").get(0);
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("Jenny", f.getValue());
assertEquals("item5", f.getGroup());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("pref"));
f = vcard.getExtendedType("X-ABLABEL").get(2);
assertEquals("X-ABLABEL", f.getTypeName());
assertEquals("Spouse", f.getValue());
assertEquals("item5", f.getGroup());
f = vcard.getExtendedType("X-ABUID").get(0);
assertEquals("X-ABUID", f.getTypeName());
assertEquals("6B29A774-D124-4822-B8D0-2780EC117F60\\:ABPerson", f.getValue());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void embeddedVCard() throws Exception {
VCard vcard = new VCard();
FormattedNameType fn = new FormattedNameType("Michael Angstadt");
vcard.setFormattedName(fn);
VCard agentVcard = new VCard();
agentVcard.setFormattedName(new FormattedNameType("Agent 007"));
NoteType note = new NoteType("Bonne soir�e, 007.");
note.setLanguage("fr");
agentVcard.getNotes().add(note);
AgentType agent = new AgentType(agentVcard);
vcard.setAgent(agent);
//i herd u liek AGENTs...
VCard secondAgentVCard = new VCard();
secondAgentVCard.setFormattedName(new FormattedNameType("Agent 009"));
note = new NoteType("Good evening, 009.");
note.setLanguage("en");
secondAgentVCard.getNotes().add(note);
AgentType secondAgent = new AgentType(secondAgentVCard);
agentVcard.setAgent(secondAgent);
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V3_0, null);
vcw.setAddProdId(false);
vcw.write(vcard);
String actual = sw.toString();
//FIXME this test may fail on other machines because Class.getDeclaredFields() returns the fields in no particular order
//@formatter:off
StringBuilder sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:3.0\r\n");
sb.append("FN:Michael Angstadt\r\n");
sb.append("AGENT:"); //nested types should not have X-GENERATOR
sb.append("BEGIN:VCARD\\n");
sb.append("VERSION:3.0\\n");
sb.append("FN:Agent 007\\n");
sb.append("AGENT:");
sb.append("BEGIN:VCARD\\\\n");
sb.append("VERSION:3.0\\\\n");
sb.append("FN:Agent 009\\\\n");
sb.append("NOTE\\\\\\;LANGUAGE=en:Good evening\\\\\\\\\\\\\\, 009.\\\\n");
sb.append("END:VCARD\\\\n\\n");
sb.append("NOTE\\;LANGUAGE=fr:Bonne soir�e\\\\\\, 007.\\n");
sb.append("END:VCARD\\n\r\n");
sb.append("END:VCARD\r\n");
String expected = sb.toString();
//@formatter:on
assertEquals(expected, actual);
}
#location 28
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void embeddedVCard() throws Exception {
VCard vcard = new VCard();
FormattedNameType fn = new FormattedNameType("Michael Angstadt");
vcard.setFormattedName(fn);
VCard agentVcard = new VCard();
agentVcard.setFormattedName(new FormattedNameType("Agent 007"));
NoteType note = new NoteType("Bonne soir�e, 007.");
note.setLanguage("fr");
agentVcard.getNotes().add(note);
AgentType agent = new AgentType(agentVcard);
vcard.setAgent(agent);
//i herd u liek AGENTs...
VCard secondAgentVCard = new VCard();
secondAgentVCard.setFormattedName(new FormattedNameType("Agent 009"));
note = new NoteType("Good evening, 009.");
note.setLanguage("en");
secondAgentVCard.getNotes().add(note);
AgentType secondAgent = new AgentType(secondAgentVCard);
agentVcard.setAgent(secondAgent);
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V3_0, null, "\r\n");
vcw.setAddProdId(false);
vcw.write(vcard);
String actual = sw.toString();
//FIXME this test may fail on other machines because Class.getDeclaredFields() returns the fields in no particular order
//@formatter:off
StringBuilder sb = new StringBuilder();
sb.append("BEGIN:VCARD\r\n");
sb.append("VERSION:3.0\r\n");
sb.append("FN:Michael Angstadt\r\n");
sb.append("AGENT:"); //nested types should not have X-GENERATOR
sb.append("BEGIN:VCARD\\n");
sb.append("VERSION:3.0\\n");
sb.append("FN:Agent 007\\n");
sb.append("AGENT:");
sb.append("BEGIN:VCARD\\\\n");
sb.append("VERSION:3.0\\\\n");
sb.append("FN:Agent 009\\\\n");
sb.append("NOTE\\\\\\;LANGUAGE=en:Good evening\\\\\\\\\\\\\\, 009.\\\\n");
sb.append("END:VCARD\\\\n\\n");
sb.append("NOTE\\;LANGUAGE=fr:Bonne soir�e\\\\\\, 007.\\n");
sb.append("END:VCARD\\n\r\n");
sb.append("END:VCARD\r\n");
String expected = sb.toString();
//@formatter:on
assertEquals(expected, actual);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void test() throws Exception {
VCard vcard = new VCard();
StructuredNameType n = new StructuredNameType();
n.setGiven("Michael");
n.setFamily("Angstadt");
vcard.setStructuredName(n);
FormattedNameType fn = new FormattedNameType("Michael Angstadt");
vcard.setFormattedName(fn);
PhotoType photo = new PhotoType();
photo.setUrl("http://example.com/image.jpg");
vcard.getPhotos().add(photo);
VCardWriter vcw = new VCardWriter(new OutputStreamWriter(System.out));
vcw.write(vcard);
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void test() throws Exception {
VCard vcard = new VCard();
StructuredNameType n = new StructuredNameType();
n.setGiven("Michael");
n.setFamily("Angstadt");
vcard.setStructuredName(n);
FormattedNameType fn = new FormattedNameType("Michael Angstadt");
vcard.setFormattedName(fn);
PhotoType photo = new PhotoType();
photo.setUrl("http://example.com/image.jpg");
vcard.getPhotos().add(photo);
StringWriter sw = new StringWriter();
VCardWriter vcw = new VCardWriter(sw, VCardVersion.V2_1);
vcw.write(vcard);
System.out.println(sw.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void gmailVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_GMAIL.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter, James Doe Sr.", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter, James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("home")));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("905-555-1234", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
f = it.next();
assertEquals("905-666-1234", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("Crescent moon drive" + NEWLINE + "555-asd" + NEWLINE + "Nice Area, Albaney, New York12345" + NEWLINE + "United States of America", f.getExtendedAddress());
assertEquals(null, f.getStreetAddress());
assertEquals(null, f.getLocality());
assertEquals(null, f.getRegion());
assertEquals(null, f.getPostalCode());
assertEquals(null, f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertFalse(it.hasNext());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 22);
assertEquals(c.getTime(), f.getDate());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + NEWLINE + "Favotire Color: Blue", f.getValue());
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(6, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0);
assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName());
assertEquals("Jon", f.getValue());
f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0);
assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName());
assertEquals("Dow", f.getValue());
f = vcard.getExtendedProperties("X-ABDATE").get(0);
assertEquals("X-ABDATE", f.getTypeName());
assertEquals("1975-03-01", f.getValue());
assertEquals("item1", f.getGroup());
f = vcard.getExtendedProperties("X-ABLABEL").get(0);
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("_$!<Anniversary>!$_", f.getValue());
assertEquals("item1", f.getGroup());
f = vcard.getExtendedProperties("X-ABLABEL").get(1);
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("_$!<Spouse>!$_", f.getValue());
assertEquals("item2", f.getGroup());
f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0);
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("Jenny", f.getValue());
assertEquals("item2", f.getGroup());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void gmailVCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("John_Doe_GMAIL.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V3_0, vcard.getVersion());
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("Mr. John Richter, James Doe Sr.", f.getValue());
}
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertEquals(Arrays.asList("Richter, James"), f.getAdditional());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("Sr."), f.getSuffixes());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertTrue(types.contains(new EmailTypeParameter("home")));
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("905-555-1234", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
f = it.next();
assertEquals("905-666-1234", f.getText());
types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("Crescent moon drive" + NEWLINE + "555-asd" + NEWLINE + "Nice Area, Albaney, New York12345" + NEWLINE + "United States of America", f.getExtendedAddress());
assertEquals(null, f.getStreetAddress());
assertEquals(null, f.getLocality());
assertEquals(null, f.getRegion());
assertEquals(null, f.getPostalCode());
assertEquals(null, f.getCountry());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.HOME));
assertFalse(it.hasNext());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("IBM"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("Money Counter", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 22);
assertEquals(c.getTime(), f.getDate());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://www.ibm.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." + NEWLINE + "Favotire Color: Blue", f.getValue());
assertFalse(it.hasNext());
}
//extended types
{
assertEquals(6, countExtTypes(vcard));
RawType f = vcard.getExtendedProperties("X-PHONETIC-FIRST-NAME").get(0);
assertEquals("X-PHONETIC-FIRST-NAME", f.getTypeName());
assertEquals("Jon", f.getValue());
f = vcard.getExtendedProperties("X-PHONETIC-LAST-NAME").get(0);
assertEquals("X-PHONETIC-LAST-NAME", f.getTypeName());
assertEquals("Dow", f.getValue());
f = vcard.getExtendedProperties("X-ABDATE").get(0);
assertEquals("X-ABDATE", f.getTypeName());
assertEquals("1975-03-01", f.getValue());
assertEquals("item1", f.getGroup());
f = vcard.getExtendedProperties("X-ABLABEL").get(0);
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("_$!<Anniversary>!$_", f.getValue());
assertEquals("item1", f.getGroup());
f = vcard.getExtendedProperties("X-ABLABEL").get(1);
assertEquals("X-ABLabel", f.getTypeName());
assertEquals("_$!<Spouse>!$_", f.getValue());
assertEquals("item2", f.getGroup());
f = vcard.getExtendedProperties("X-ABRELATEDNAMES").get(0);
assertEquals("X-ABRELATEDNAMES", f.getTypeName());
assertEquals("Jenny", f.getValue());
assertEquals("item2", f.getGroup());
}
assertWarnings(0, reader.getWarnings());
assertNull(reader.readNext());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void outlook2003VCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2003.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V2_1, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("III"), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("John Doe III", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Joey"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("Company, The", "TheDepartment"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("The Job Title", f.getValue());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is the note field!!\r\nSecond line\r\n\r\nThird line is empty\r\n", f.getValue());
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("BusinessPhone", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("HomePhone", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("MobilePhone", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("BusinessFaxPhone", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.FAX));
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("TheOffice", f.getExtendedAddress());
assertEquals("123 Main St", f.getStreetAddress());
assertEquals("Austin", f.getLocality());
assertEquals("TX", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
assertEquals("TheOffice\r\n123 Main St\r\nAustin, TX 12345\r\nUnited States of America", f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertFalse(it.hasNext());
}
//LABEL
{
assertTrue(vcard.getOrphanedLabels().isEmpty());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://web-page-address.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("TheProfession", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 21);
assertEquals(c.getTime(), f.getDate());
}
//KEY
{
Iterator<KeyType> it = vcard.getKeys().iterator();
KeyType f = it.next();
assertEquals(KeyTypeParameter.X509, f.getContentType());
assertEquals(805, f.getData().length);
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.PREF));
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//FBURL
{
Iterator<FbUrlType> it = vcard.getFbUrls().iterator();
//Outlook 2003 apparently doesn't output FBURL correctly:
//http://help.lockergnome.com/office/BUG-Outlook-2003-exports-FBURL-vCard-incorrectly--ftopict423660.html
FbUrlType f = it.next();
assertEquals("????????????????s????????????" + (char) 12, f.getValue());
assertFalse(it.hasNext());
}
//REV
{
RevisionType f = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.OCTOBER);
c.set(Calendar.DAY_OF_MONTH, 12);
c.set(Calendar.HOUR_OF_DAY, 21);
c.set(Calendar.MINUTE, 5);
c.set(Calendar.SECOND, 25);
assertEquals(c.getTime(), f.getTimestamp());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void outlook2003VCard() throws Exception {
VCardReader reader = new VCardReader(getClass().getResourceAsStream("outlook-2003.vcf"));
VCard vcard = reader.readNext();
//VERSION
assertEquals(VCardVersion.V2_1, vcard.getVersion());
//N
{
StructuredNameType f = vcard.getStructuredName();
assertEquals("Doe", f.getFamily());
assertEquals("John", f.getGiven());
assertTrue(f.getAdditional().isEmpty());
assertEquals(Arrays.asList("Mr."), f.getPrefixes());
assertEquals(Arrays.asList("III"), f.getSuffixes());
}
//FN
{
FormattedNameType f = vcard.getFormattedName();
assertEquals("John Doe III", f.getValue());
}
//NICKNAME
{
NicknameType f = vcard.getNickname();
assertEquals(Arrays.asList("Joey"), f.getValues());
}
//ORG
{
OrganizationType f = vcard.getOrganization();
assertEquals(Arrays.asList("Company, The", "TheDepartment"), f.getValues());
}
//TITLE
{
Iterator<TitleType> it = vcard.getTitles().iterator();
TitleType f = it.next();
assertEquals("The Job Title", f.getValue());
assertFalse(it.hasNext());
}
//NOTE
{
Iterator<NoteType> it = vcard.getNotes().iterator();
NoteType f = it.next();
assertEquals("This is the note field!!\r\nSecond line\r\n\r\nThird line is empty\r\n", f.getValue());
assertFalse(it.hasNext());
}
//TEL
{
Iterator<TelephoneType> it = vcard.getTelephoneNumbers().iterator();
TelephoneType f = it.next();
assertEquals("BusinessPhone", f.getText());
Set<TelephoneTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("HomePhone", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.HOME));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("MobilePhone", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.CELL));
assertTrue(types.contains(TelephoneTypeParameter.VOICE));
f = it.next();
assertEquals("BusinessFaxPhone", f.getText());
types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(TelephoneTypeParameter.FAX));
assertTrue(types.contains(TelephoneTypeParameter.WORK));
assertFalse(it.hasNext());
}
//ADR
{
Iterator<AddressType> it = vcard.getAddresses().iterator();
AddressType f = it.next();
assertEquals(null, f.getPoBox());
assertEquals("TheOffice", f.getExtendedAddress());
assertEquals("123 Main St", f.getStreetAddress());
assertEquals("Austin", f.getLocality());
assertEquals("TX", f.getRegion());
assertEquals("12345", f.getPostalCode());
assertEquals("United States of America", f.getCountry());
assertEquals("TheOffice\r\n123 Main St\r\nAustin, TX 12345\r\nUnited States of America", f.getLabel());
Set<AddressTypeParameter> types = f.getTypes();
assertEquals(1, types.size());
assertTrue(types.contains(AddressTypeParameter.WORK));
assertFalse(it.hasNext());
}
//LABEL
{
assertTrue(vcard.getOrphanedLabels().isEmpty());
}
//URL
{
Iterator<UrlType> it = vcard.getUrls().iterator();
UrlType f = it.next();
assertEquals("http://web-page-address.com", f.getValue());
Set<String> types = f.getSubTypes().getTypes();
assertEquals(1, types.size());
assertTrue(types.contains("WORK"));
assertFalse(it.hasNext());
}
//ROLE
{
Iterator<RoleType> it = vcard.getRoles().iterator();
RoleType f = it.next();
assertEquals("TheProfession", f.getValue());
assertFalse(it.hasNext());
}
//BDAY
{
BirthdayType f = vcard.getBirthday();
Calendar c = Calendar.getInstance();
c.clear();
c.set(Calendar.YEAR, 1980);
c.set(Calendar.MONTH, Calendar.MARCH);
c.set(Calendar.DAY_OF_MONTH, 21);
assertEquals(c.getTime(), f.getDate());
}
//KEY
{
Iterator<KeyType> it = vcard.getKeys().iterator();
KeyType f = it.next();
assertEquals(KeyTypeParameter.X509, f.getContentType());
assertEquals(805, f.getData().length);
assertFalse(it.hasNext());
}
//EMAIL
{
Iterator<EmailType> it = vcard.getEmails().iterator();
EmailType f = it.next();
assertEquals("[email protected]", f.getValue());
Set<EmailTypeParameter> types = f.getTypes();
assertEquals(2, types.size());
assertTrue(types.contains(EmailTypeParameter.PREF));
assertTrue(types.contains(EmailTypeParameter.INTERNET));
assertFalse(it.hasNext());
}
//FBURL
{
Iterator<FbUrlType> it = vcard.getFbUrls().iterator();
//Outlook 2003 apparently doesn't output FBURL correctly:
//http://help.lockergnome.com/office/BUG-Outlook-2003-exports-FBURL-vCard-incorrectly--ftopict423660.html
FbUrlType f = it.next();
assertEquals("????????????????s????????????" + (char) 12, f.getValue());
assertFalse(it.hasNext());
}
//REV
{
RevisionType f = vcard.getRevision();
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
c.clear();
c.set(Calendar.YEAR, 2012);
c.set(Calendar.MONTH, Calendar.OCTOBER);
c.set(Calendar.DAY_OF_MONTH, 12);
c.set(Calendar.HOUR_OF_DAY, 21);
c.set(Calendar.MINUTE, 5);
c.set(Calendar.SECOND, 25);
assertEquals(c.getTime(), f.getTimestamp());
}
assertWarnings(0, reader.getWarnings());
assertNull(reader.readNext());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<String> execute(TsLintExecutorConfig config, List<String> files) {
if (config == null) {
throw new IllegalArgumentException("config");
}
if (files == null) {
throw new IllegalArgumentException("files");
}
// New up a command that's everything we need except the files to process
// We'll use this as our reference for chunking up files
File tslintOutputFile = this.tempFolder.newFile();
String tslintOutputFilePath = tslintOutputFile.getAbsolutePath();
LOG.debug("Using a temporary path for TsLint output: " + tslintOutputFilePath);
int baseCommandLength = getBaseCommand(config, tslintOutputFilePath).toCommandLine().length();
int availableForBatching = MAX_COMMAND_LENGTH - baseCommandLength;
List<List<String>> batches = new ArrayList<List<String>>();
List<String> currentBatch = new ArrayList<String>();
batches.add(currentBatch);
int currentBatchLength = 0;
for (int i = 0; i < files.size(); i++) {
String nextPath = this.preparePath(files.get(i).trim());
// +1 for the space we'll be adding between filenames
if (currentBatchLength + nextPath.length() + 1 > availableForBatching) {
// Too long to add to this batch, create new
currentBatch = new ArrayList<String>();
currentBatchLength = 0;
batches.add(currentBatch);
}
currentBatch.add(nextPath);
currentBatchLength += nextPath.length() + 1;
}
LOG.debug("Split " + files.size() + " files into " + batches.size() + " batches for processing");
StringStreamConsumer stdOutConsumer = new StringStreamConsumer();
StringStreamConsumer stdErrConsumer = new StringStreamConsumer();
List<String> toReturn = new ArrayList<String>();
for (int i = 0; i < batches.size(); i++) {
StringBuilder outputBuilder = new StringBuilder();
List<String> thisBatch = batches.get(i);
Command thisCommand = getBaseCommand(config, tslintOutputFilePath);
for (int fileIndex = 0; fileIndex < thisBatch.size(); fileIndex++) {
thisCommand.addArgument(thisBatch.get(fileIndex));
}
LOG.debug("Executing TsLint with command: " + thisCommand.toCommandLine());
// Timeout is specified per file, not per batch (which can vary a lot)
// so multiply it up
this.createExecutor().execute(thisCommand, stdOutConsumer, stdErrConsumer, config.getTimeoutMs() * thisBatch.size());
try {
BufferedReader reader = this.getBufferedReaderForFile(tslintOutputFile);
String str;
while ((str = reader.readLine()) != null) {
outputBuilder.append(str);
}
reader.close();
toReturn.add(outputBuilder.toString());
}
catch (IOException ex) {
LOG.error("Failed to re-read TsLint output from " + tslintOutputFilePath, ex);
}
}
return toReturn;
}
#location 76
#vulnerability type RESOURCE_LEAK | #fixed code
public List<String> execute(TsLintExecutorConfig config, List<String> files) {
if (config == null) {
throw new IllegalArgumentException("config");
}
else if (files == null) {
throw new IllegalArgumentException("files");
}
// New up a command that's everything we need except the files to process
// We'll use this as our reference for chunking up files, if we need to
File tslintOutputFile = this.tempFolder.newFile();
String tslintOutputFilePath = tslintOutputFile.getAbsolutePath();
Command baseCommand = getBaseCommand(config, tslintOutputFilePath);
LOG.debug("Using a temporary path for TsLint output: " + tslintOutputFilePath);
StringStreamConsumer stdOutConsumer = new StringStreamConsumer();
StringStreamConsumer stdErrConsumer = new StringStreamConsumer();
List<String> toReturn = new ArrayList<String>();
if (config.useTsConfigInsteadOfFileList()) {
LOG.debug("Running against a single project JSON file");
// If we're being asked to use a tsconfig.json file, it'll contain
// the file list to lint - so don't batch, and just run with it
toReturn.add(this.getCommandOutput(baseCommand, stdOutConsumer, stdErrConsumer, tslintOutputFile, config.getTimeoutMs()));
}
else {
int baseCommandLength = baseCommand.toCommandLine().length();
int availableForBatching = MAX_COMMAND_LENGTH - baseCommandLength;
List<List<String>> batches = new ArrayList<List<String>>();
List<String> currentBatch = new ArrayList<String>();
batches.add(currentBatch);
int currentBatchLength = 0;
for (int i = 0; i < files.size(); i++) {
String nextPath = this.preparePath(files.get(i).trim());
// +1 for the space we'll be adding between filenames
if (currentBatchLength + nextPath.length() + 1 > availableForBatching) {
// Too long to add to this batch, create new
currentBatch = new ArrayList<String>();
currentBatchLength = 0;
batches.add(currentBatch);
}
currentBatch.add(nextPath);
currentBatchLength += nextPath.length() + 1;
}
LOG.debug("Split " + files.size() + " files into " + batches.size() + " batches for processing");
for (int i = 0; i < batches.size(); i++) {
StringBuilder outputBuilder = new StringBuilder();
List<String> thisBatch = batches.get(i);
Command thisCommand = getBaseCommand(config, tslintOutputFilePath);
for (int fileIndex = 0; fileIndex < thisBatch.size(); fileIndex++) {
thisCommand.addArgument(thisBatch.get(fileIndex));
}
LOG.debug("Executing TsLint with command: " + thisCommand.toCommandLine());
// Timeout is specified per file, not per batch (which can vary a lot)
// so multiply it up
toReturn.add(this.getCommandOutput(thisCommand, stdOutConsumer, stdErrConsumer, tslintOutputFile, config.getTimeoutMs() * thisBatch.size()));
}
}
return toReturn;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String getCommandOutput(Command thisCommand, StreamConsumer stdOutConsumer, StreamConsumer stdErrConsumer, File tslintOutputFile, Integer timeoutMs) {
LOG.debug("Executing TsLint with command: " + thisCommand.toCommandLine());
// Timeout is specified per file, not per batch (which can vary a lot)
// so multiply it up
this.createExecutor().execute(thisCommand, stdOutConsumer, stdErrConsumer, timeoutMs);
StringBuilder outputBuilder = new StringBuilder();
try {
BufferedReader reader = this.getBufferedReaderForFile(tslintOutputFile);
String str;
while ((str = reader.readLine()) != null) {
outputBuilder.append(str);
}
reader.close();
return outputBuilder.toString();
}
catch (IOException ex) {
LOG.error("Failed to re-read TsLint output", ex);
}
return "";
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
private String getCommandOutput(Command thisCommand, StreamConsumer stdOutConsumer, StreamConsumer stdErrConsumer, File tslintOutputFile, Integer timeoutMs) {
LOG.debug("Executing TsLint with command: " + thisCommand.toCommandLine());
// Timeout is specified per file, not per batch (which can vary a lot)
// so multiply it up
this.createExecutor().execute(thisCommand, stdOutConsumer, stdErrConsumer, timeoutMs);
return getFileContent(tslintOutputFile);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
@RedisCache(flush = true)
public Comment comment(Comment comment) throws ZhydCommentException {
if (StringUtils.isEmpty(comment.getNickname())) {
throw new ZhydCommentException("必须输入昵称哦~~");
}
String content = comment.getContent();
if (StringUtils.isEmpty(content)) {
throw new ZhydCommentException("不说话可不行,必须说点什么哦~~");
}
if (!XssKillerUtil.isValid(content)) {
throw new ZhydCommentException("内容不合法,请不要使用特殊标签哦~~");
}
content = XssKillerUtil.clean(content.trim());
if (content.endsWith("<p><br></p>")) {
comment.setContent(content.substring(0, content.length() - "<p><br></p>".length()));
}
comment.setNickname(HtmlUtil.html2Text(comment.getNickname()));
comment.setQq(HtmlUtil.html2Text(comment.getQq()));
comment.setAvatar(HtmlUtil.html2Text(comment.getAvatar()));
comment.setEmail(HtmlUtil.html2Text(comment.getEmail()));
comment.setUrl(HtmlUtil.html2Text(comment.getUrl()));
HttpServletRequest request = RequestHolder.getRequest();
String ua = request.getHeader("User-Agent");
UserAgent agent = UserAgent.parseUserAgentString(ua);
// 浏览器
Browser browser = agent.getBrowser();
String browserInfo = browser.getName();
// comment.setBrowserShortName(browser.getShortName());// 此处需开发者自己处理
// 浏览器版本
Version version = agent.getBrowserVersion();
if (version != null) {
browserInfo += " " + version.getVersion();
}
comment.setBrowser(browserInfo);
// 操作系统
OperatingSystem os = agent.getOperatingSystem();
comment.setOs(os.getName());
// comment.setOsShortName(os.getShortName());// 此处需开发者自己处理
comment.setIp(IpUtil.getRealIp(request));
String address = "定位失败";
Config config = configService.get();
try {
String locationJson = RestClientUtil.get(UrlBuildUtil.getLocationByIp(comment.getIp(), config.getBaiduApiAk()));
JSONObject localtionContent = JSONObject.parseObject(locationJson).getJSONObject("content");
// 地址详情
JSONObject addressDetail = localtionContent.getJSONObject("address_detail");
// 省
String province = addressDetail.getString("province");
// 市
String city = addressDetail.getString("city");
// 区
String district = addressDetail.getString("district");
// 街道
String street = addressDetail.getString("street");
// 街道编号
// String street_number = addressDetail.getString("street_number");
StringBuffer sb = new StringBuffer(province);
if (!StringUtils.isEmpty(city)) {
sb.append(city);
}
if (!StringUtils.isEmpty(district)) {
sb.append(district);
}
if (!StringUtils.isEmpty(street)) {
sb.append(street);
}
address = sb.toString();
// 经纬度
JSONObject point = localtionContent.getJSONObject("point");
// 纬度
String lat = point.getString("y");
// 经度
String lng = point.getString("x");
comment.setLat(lat);
comment.setLng(lng);
comment.setAddress(address);
} catch (Exception e) {
comment.setAddress("未知");
log.error("获取地址失败", e);
}
if (StringUtils.isEmpty(comment.getStatus())) {
comment.setStatus(CommentStatusEnum.VERIFYING.toString());
}
this.insert(comment);
this.sendEmail(comment);
return comment;
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
@RedisCache(flush = true)
public Comment comment(Comment comment) throws ZhydCommentException {
if (StringUtils.isEmpty(comment.getNickname())) {
throw new ZhydCommentException("必须输入昵称哦~~");
}
String content = comment.getContent();
if (!XssKillerUtil.isValid(content)) {
throw new ZhydCommentException("内容不合法,请不要使用特殊标签哦~~");
}
content = XssKillerUtil.clean(content.trim()).replaceAll("(<p><br></p>)|(<p></p>)", "");
if (StringUtils.isEmpty(content) || "\n".equals(content)) {
throw new ZhydCommentException("不说话可不行,必须说点什么哦~~");
}
// 过滤非法属性和无用的空标签
comment.setContent(content);
comment.setNickname(HtmlUtil.html2Text(comment.getNickname()));
comment.setQq(HtmlUtil.html2Text(comment.getQq()));
comment.setAvatar(HtmlUtil.html2Text(comment.getAvatar()));
comment.setEmail(HtmlUtil.html2Text(comment.getEmail()));
comment.setUrl(HtmlUtil.html2Text(comment.getUrl()));
HttpServletRequest request = RequestHolder.getRequest();
String ua = request.getHeader("User-Agent");
UserAgent agent = UserAgent.parseUserAgentString(ua);
// 浏览器
Browser browser = agent.getBrowser();
String browserInfo = browser.getName();
// comment.setBrowserShortName(browser.getShortName());// 此处需开发者自己处理
// 浏览器版本
Version version = agent.getBrowserVersion();
if (version != null) {
browserInfo += " " + version.getVersion();
}
comment.setBrowser(browserInfo);
// 操作系统
OperatingSystem os = agent.getOperatingSystem();
comment.setOs(os.getName());
// comment.setOsShortName(os.getShortName());// 此处需开发者自己处理
comment.setIp(IpUtil.getRealIp(request));
String address = "定位失败";
Config config = configService.get();
try {
String locationJson = RestClientUtil.get(UrlBuildUtil.getLocationByIp(comment.getIp(), config.getBaiduApiAk()));
JSONObject localtionContent = JSONObject.parseObject(locationJson).getJSONObject("content");
// 地址详情
JSONObject addressDetail = localtionContent.getJSONObject("address_detail");
// 省
String province = addressDetail.getString("province");
// 市
String city = addressDetail.getString("city");
// 区
String district = addressDetail.getString("district");
// 街道
String street = addressDetail.getString("street");
// 街道编号
// String street_number = addressDetail.getString("street_number");
StringBuffer sb = new StringBuffer(province);
if (!StringUtils.isEmpty(city)) {
sb.append(city);
}
if (!StringUtils.isEmpty(district)) {
sb.append(district);
}
if (!StringUtils.isEmpty(street)) {
sb.append(street);
}
address = sb.toString();
// 经纬度
JSONObject point = localtionContent.getJSONObject("point");
// 纬度
String lat = point.getString("y");
// 经度
String lng = point.getString("x");
comment.setLat(lat);
comment.setLng(lng);
comment.setAddress(address);
} catch (Exception e) {
comment.setAddress("未知");
log.error("获取地址失败", e);
}
if (StringUtils.isEmpty(comment.getStatus())) {
comment.setStatus(CommentStatusEnum.VERIFYING.toString());
}
this.insert(comment);
this.sendEmail(comment);
return comment;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String template2String(String templateContent, Map<String, Object> map,
boolean isNeedFilter) {
if (StringUtils.isEmpty(templateContent)) {
return null;
}
if (map == null) {
map = new HashMap<>();
}
Map<String, Object> newMap = new HashMap<>(1);
Set<String> keySet = map.keySet();
if (keySet.size() > 0) {
for (String key : keySet) {
Object o = map.get(key);
if (o != null) {
if (o instanceof String) {
String value = o.toString();
if (value != null) {
value = value.trim();
}
if (isNeedFilter) {
value = filterXmlString(value);
}
newMap.put(key, value);
} else {
newMap.put(key, o);
}
}
}
}
Template t = null;
try {
t = new Template("", new StringReader(templateContent), new Configuration());
StringWriter writer = new StringWriter();
t.process(newMap, writer);
return writer.toString();
} catch (IOException e) {
log.error("TemplateUtil -> template2String IOException.", e);
} catch (TemplateException e) {
log.error("TemplateUtil -> template2String TemplateException.", e);
} finally {
if (newMap != null) {
newMap.clear();
newMap = null;
}
}
return null;
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String template2String(String templateContent, Map<String, Object> map,
boolean isNeedFilter) {
if (StringUtils.isEmpty(templateContent)) {
return null;
}
if (map == null) {
map = new HashMap<>();
}
Map<String, Object> newMap = new HashMap<>(1);
Set<String> keySet = map.keySet();
if (keySet.size() > 0) {
for (String key : keySet) {
Object o = map.get(key);
if (o != null) {
if (o instanceof String) {
String value = o.toString();
value = value.trim();
if (isNeedFilter) {
value = filterXmlString(value);
}
newMap.put(key, value);
} else {
newMap.put(key, o);
}
}
}
}
Template t = null;
try {
t = new Template("", new StringReader(templateContent), new Configuration());
StringWriter writer = new StringWriter();
t.process(newMap, writer);
return writer.toString();
} catch (IOException e) {
log.error("TemplateUtil -> template2String IOException.", e);
} catch (TemplateException e) {
log.error("TemplateUtil -> template2String TemplateException.", e);
} finally {
newMap.clear();
newMap = null;
}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void sendEmails(Set<String> emailTargets, String body) throws IOException {
File temporaryEmailBody = File.createTempFile("_tmp_" + getClass().getSimpleName(), null);
BufferedWriter writer = new BufferedWriter(new FileWriter(temporaryEmailBody, false));
writer.write(body);
LOG.info("Sending Monitor email to " + emailTargets.size() + " targets: " + emailTargets + " Email body: " + body);
for (String emailTarget : emailTargets) {
Runtime.getRuntime().exec("cat " + temporaryEmailBody.getAbsolutePath()
+ " | mail -s 'Hank Notification' " + emailTarget);
}
if (!temporaryEmailBody.delete()) {
throw new IOException("Could not delete " + temporaryEmailBody.getAbsolutePath());
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException {
LOG.info("Sending Monitor email to " + emailTargets.size() + " targets: " + emailTargets + " Email body: " + body);
for (String emailTarget : emailTargets) {
String[] command = {"/bin/mail", "-s", "Hank-Notification", emailTarget};
Process process = Runtime.getRuntime().exec(command);
OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream());
writer.write(body);
writer.close();
process.getOutputStream().close();
process.waitFor();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException {
LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " starting.");
boolean claimedDataDeployer = false;
try {
ringGroupConfig = coord.getRingGroup(ringGroupName);
// attempt to claim the data deployer title
if (ringGroupConfig.claimDataDeployer()) {
claimedDataDeployer = true;
// we are now *the* data deployer for this ring group.
domainGroup = ringGroupConfig.getDomainGroup();
// set a watch on the ring group
ringGroupConfig.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
goingDown = false;
try {
while (!goingDown) {
// take a snapshot of the current ring/domain group configs, since
// they might get changed while we're processing the current update.
RingGroup snapshotRingGroupConfig;
DomainGroup snapshotDomainGroup;
synchronized (lock) {
snapshotRingGroupConfig = ringGroupConfig;
snapshotDomainGroup = domainGroup;
}
processUpdates(snapshotRingGroupConfig, snapshotDomainGroup);
Thread.sleep(config.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim data deployer status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
if (claimedDataDeployer) {
ringGroupConfig.releaseDataDeployer();
}
}
LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " shutting down.");
}
#location 29
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() throws IOException {
LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " starting.");
boolean claimedDataDeployer = false;
try {
ringGroup = coord.getRingGroup(ringGroupName);
// attempt to claim the data deployer title
if (ringGroup.claimDataDeployer()) {
claimedDataDeployer = true;
// we are now *the* data deployer for this ring group.
domainGroup = ringGroup.getDomainGroup();
// set a watch on the ring group
ringGroup.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
goingDown = false;
try {
while (!goingDown) {
// take a snapshot of the current ring/domain group configs, since
// they might get changed while we're processing the current update.
RingGroup snapshotRingGroup;
DomainGroup snapshotDomainGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
snapshotDomainGroup = domainGroup;
}
processUpdates(snapshotRingGroup, snapshotDomainGroup);
Thread.sleep(config.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim data deployer status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
if (claimedDataDeployer) {
ringGroup.releaseDataDeployer();
}
}
LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " shutting down.");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException {
Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath));
File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName());
LOG.info("Copying remote file " + source + " to local file " + destination);
InputStream inputStream = getInputStream(remoteSourceRelativePath);
// Use copyLarge (over 2GB)
try {
IOUtils.copyLarge(inputStream,
new BufferedOutputStream(new FileOutputStream(destination)));
} finally {
inputStream.close();
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public void copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException {
Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath));
File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName());
LOG.info("Copying remote file " + source + " to local file " + destination);
InputStream inputStream = getInputStream(remoteSourceRelativePath);
FileOutputStream fileOutputStream = new FileOutputStream(destination);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
// Use copyLarge (over 2GB)
try {
IOUtils.copyLarge(inputStream, bufferedOutputStream);
bufferedOutputStream.flush();
fileOutputStream.flush();
} finally {
inputStream.close();
bufferedOutputStream.close();
fileOutputStream.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public int decompress(byte[] src, int srcOffset, int srcLength, byte[] dst, int dstOff) {
if (srcLength - srcOffset == 0) {
return 0;
}
try {
ByteArrayInputStream bytesIn = new ByteArrayInputStream(src, srcOffset, srcLength);
GZIPInputStream gzip = new GZIPInputStream(bytesIn);
int curOff = dstOff;
while (true) {
int amtRead = gzip.read(dst, curOff, dst.length - curOff);
if (amtRead == -1) {
break;
}
curOff += amtRead;
}
return curOff;
} catch (IOException e) {
throw new RuntimeException("Unexpected IOException while decompressing!", e);
}
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public int decompress(byte[] src, int srcOffset, int srcLength, byte[] dst, int dstOff) {
if (srcLength - srcOffset == 0) {
return 0;
}
try {
ByteArrayInputStream bytesIn = new ByteArrayInputStream(src, srcOffset, srcLength);
GZIPInputStream gzip = new GZIPInputStream(bytesIn);
int curOff = dstOff;
while (curOff < dst.length - dstOff) {
int amtRead = gzip.read(dst, curOff, dst.length - curOff);
if (amtRead == -1) {
break;
}
curOff += amtRead;
}
return curOff;
} catch (IOException e) {
throw new RuntimeException("Unexpected IOException while decompressing!", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void assign(RingGroup ringGroup, int ringNum, Domain domain) throws IOException {
ring = ringGroup.getRing(ringNum);
domainGroup = ringGroup.getDomainGroup();
domainId = domainGroup.getDomainId(domain.getName());
version = domainGroup.getLatestVersion().getVersionNumber();
random = new Random();
for (Integer partNum : ring.getUnassignedPartitions(domain)) {
HostDomain minHostDomain = getMinHostDomain();
minHostDomain.addPartition(partNum, version);
}
while (!isDone()) {
HostDomain maxHostDomain = getMaxHostDomain();
HostDomain minHostDomain = getMinHostDomain();
ArrayList<HostDomainPartition> partitions = new ArrayList<HostDomainPartition>();
partitions.addAll(maxHostDomain.getPartitions());
int partNum = partitions.get(random.nextInt(partitions.size())).getPartNum();
HostDomainPartition partition = maxHostDomain.getPartitionByNumber(partNum);
try {
if (partition.getCurrentDomainGroupVersion() == null)
partition.delete();
else
partition.setDeletable(true);
} catch (Exception e) {
partition.setDeletable(true);
}
minHostDomain.addPartition(partNum, version);
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void assign(RingGroup ringGroup, int ringNum, Domain domain) throws IOException {
ring = ringGroup.getRing(ringNum);
domainGroup = ringGroup.getDomainGroup();
domainId = domainGroup.getDomainId(domain.getName());
version = domainGroup.getLatestVersion().getVersionNumber();
random = new Random();
for (Integer partNum : ring.getUnassignedPartitions(domain)) {
getMinHostDomain().addPartition(partNum, version);
}
while (!isDone()) {
HostDomain maxHostDomain = getMaxHostDomain();
HostDomain minHostDomain = getMinHostDomain();
ArrayList<HostDomainPartition> partitions = new ArrayList<HostDomainPartition>();
partitions.addAll(maxHostDomain.getPartitions());
int partNum = partitions.get(random.nextInt(partitions.size())).getPartNum();
HostDomainPartition partition = maxHostDomain.getPartitionByNumber(partNum);
try {
if (partition.getCurrentDomainGroupVersion() == null)
partition.delete();
else
partition.setDeletable(true);
} catch (Exception e) {
partition.setDeletable(true);
}
minHostDomain.addPartition(partNum, version);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testBlockCompressionSnappy() throws Exception {
new File(TMP_TEST_CURLY_READER).mkdirs();
OutputStream s = new FileOutputStream(TMP_TEST_CURLY_READER + "/00000.base.curly");
s.write(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_SNAPPY);
s.flush();
s.close();
MapReader keyfileReader = new MapReader(0,
KEY1.array(), new byte[]{0, 0, 0, 0, 0},
KEY2.array(), new byte[]{0, 0, 0, 5, 0},
KEY3.array(), new byte[]{0, 0, 0, 10, 0}
);
CurlyReader reader = new CurlyReader(CurlyReader.getLatestBase(TMP_TEST_CURLY_READER), 1024, keyfileReader, -1,
BlockCompressionCodec.SNAPPY, 3, 2, true);
ReaderResult result = new ReaderResult();
reader.get(KEY1, result);
assertTrue(result.isFound());
assertEquals(VALUE1, result.getBuffer());
result.clear();
reader.get(KEY4, result);
assertFalse(result.isFound());
result.clear();
reader.get(KEY3, result);
assertTrue(result.isFound());
assertEquals(VALUE3, result.getBuffer());
result.clear();
reader.get(KEY2, result);
assertTrue(result.isFound());
assertEquals(VALUE2, result.getBuffer());
result.clear();
}
#location 37
#vulnerability type RESOURCE_LEAK | #fixed code
public void testBlockCompressionSnappy() throws Exception {
doTestBlockCompression(BlockCompressionCodec.SNAPPY, EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_SNAPPY);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws IOException {
String configPath = args[0];
String log4jprops = args[1];
PropertyConfigurator.configure(log4jprops);
new UpdateDaemon(null, HostUtils.getHostName()).run();
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void main(String[] args) throws IOException {
String configPath = args[0];
String log4jprops = args[1];
PropertyConfigurator.configure(log4jprops);
UpdateDaemonConfigurator conf = new YamlConfigurator(configPath);
new UpdateDaemon(conf, HostUtils.getHostName()).run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException {
LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " starting.");
boolean claimedDataDeployer = false;
try {
ringGroupConfig = coord.getRingGroup(ringGroupName);
// attempt to claim the data deployer title
if (ringGroupConfig.claimDataDeployer()) {
claimedDataDeployer = true;
// we are now *the* data deployer for this ring group.
domainGroup = ringGroupConfig.getDomainGroup();
// set a watch on the ring group
ringGroupConfig.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
goingDown = false;
try {
while (!goingDown) {
// take a snapshot of the current ring/domain group configs, since
// they might get changed while we're processing the current update.
RingGroup snapshotRingGroupConfig;
DomainGroup snapshotDomainGroup;
synchronized (lock) {
snapshotRingGroupConfig = ringGroupConfig;
snapshotDomainGroup = domainGroup;
}
processUpdates(snapshotRingGroupConfig, snapshotDomainGroup);
Thread.sleep(config.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim data deployer status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
if (claimedDataDeployer) {
ringGroupConfig.releaseDataDeployer();
}
}
LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " shutting down.");
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() throws IOException {
LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " starting.");
boolean claimedDataDeployer = false;
try {
ringGroup = coord.getRingGroup(ringGroupName);
// attempt to claim the data deployer title
if (ringGroup.claimDataDeployer()) {
claimedDataDeployer = true;
// we are now *the* data deployer for this ring group.
domainGroup = ringGroup.getDomainGroup();
// set a watch on the ring group
ringGroup.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
goingDown = false;
try {
while (!goingDown) {
// take a snapshot of the current ring/domain group configs, since
// they might get changed while we're processing the current update.
RingGroup snapshotRingGroup;
DomainGroup snapshotDomainGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
snapshotDomainGroup = domainGroup;
}
processUpdates(snapshotRingGroup, snapshotDomainGroup);
Thread.sleep(config.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim data deployer status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
if (claimedDataDeployer) {
ringGroup.releaseDataDeployer();
}
}
LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " shutting down.");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void getBulk(int domainId, List<ByteBuffer> keys, HostConnectionGetBulkCallback resultHandler) throws TException {
client.getBulk(domainId, keys, resultHandler);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void getBulk(int domainId, List<ByteBuffer> keys, HostConnectionGetBulkCallback resultHandler) {
try {
client.getBulk(domainId, keys, resultHandler);
} catch (TException e) {
resultHandler.onError(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private ByteBuffer decompressBlock(ByteBuffer block) throws IOException {
Buffers buffers = threadLocalBuffers.get();
buffers.reset();
// Decompress the block
InputStream blockInputStream =
new ByteArrayInputStream(block.array(), block.arrayOffset() + block.position(), block.remaining());
// Build an InputStream corresponding to the compression codec
InputStream decompressedBlockInputStream = getBlockCompressionInputStream(blockInputStream);
// Decompress into the specialized result buffer
IOStreamUtils.copy(decompressedBlockInputStream, buffers.getDecompressionOutputStream(), buffers.getCopyBuffer());
decompressedBlockInputStream.close();
return buffers.getDecompressionOutputStream().getByteBuffer();
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
private ByteBuffer decompressBlock(ByteBuffer block) throws IOException {
Local local = threadLocal.get();
local.reset();
local.getBlockDecompressor().decompress(
block.array(),
block.arrayOffset() + block.position(),
block.remaining(),
local.getDecompressionOutputStream());
return local.getDecompressionOutputStream().getByteBuffer();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void get(int domainId, ByteBuffer key, HostConnectionGetCallback resultHandler) throws TException {
client.get(domainId, key, resultHandler);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void get(int domainId, ByteBuffer key, HostConnectionGetCallback resultHandler) {
try {
client.get(domainId, key, resultHandler);
} catch (TException e) {
resultHandler.onError(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void aggregate(DoublePopulationStatisticsAggregator other) {
if (numValues == 0) {
// Copy deciles directly
System.arraycopy(other.deciles, 0, deciles, 0, 9);
} else if (other.numValues == 0) {
// Keep this deciles unchanged
} else {
// Aggregate both deciles
aggregateDeciles(this.deciles, this.numValues, this.getMaximum(),
other.deciles, other.numValues, other.getMaximum(),
this.deciles);
}
if (other.maximum > this.maximum) {
this.maximum = other.maximum;
}
if (other.minimum < this.minimum) {
this.minimum = other.minimum;
}
this.numValues += other.numValues;
this.total += other.total;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
public void aggregate(DoublePopulationStatisticsAggregator other) {
if (other.maximum > this.maximum) {
this.maximum = other.maximum;
}
if (other.minimum < this.minimum) {
this.minimum = other.minimum;
}
this.numValues += other.numValues;
this.total += other.total;
this.reservoirSample.sample(other.reservoirSample, random);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void addTask(GetTask task) {
synchronized (getTasks) {
task.startNanoTime = System.nanoTime();
getTasks.addLast(task);
}
dispatcherThread.interrupt();
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void addTask(GetTask task) {
try {
// TODO: remove trace
//LOG.trace("Adding task with state " + task.state);
if (task.startNanoTime == null) {
task.startNanoTime = System.nanoTime();
}
getTasks.put(task);
//LOG.trace("Get Task is now " + getTasks.size());
} catch (InterruptedException e) {
// Someone is trying to stop Dispatcher
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testBlockCompressionGzip() throws Exception {
new File(TMP_TEST_CURLY_READER).mkdirs();
OutputStream s = new FileOutputStream(TMP_TEST_CURLY_READER + "/00000.base.curly");
s.write(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP);
s.flush();
s.close();
MapReader keyfileReader = new MapReader(0,
KEY1.array(), new byte[]{0, 0, 0, 0, 0},
KEY2.array(), new byte[]{0, 0, 0, 5, 0},
KEY3.array(), new byte[]{0, 0, 0, 10, 0}
);
CurlyReader reader = new CurlyReader(CurlyReader.getLatestBase(TMP_TEST_CURLY_READER), 1024, keyfileReader, -1,
BlockCompressionCodec.GZIP, 3, 2, true);
ReaderResult result = new ReaderResult();
reader.get(KEY1, result);
assertTrue(result.isFound());
assertEquals(VALUE1, result.getBuffer());
result.clear();
reader.get(KEY4, result);
assertFalse(result.isFound());
result.clear();
reader.get(KEY3, result);
assertTrue(result.isFound());
assertEquals(VALUE3, result.getBuffer());
result.clear();
reader.get(KEY2, result);
assertTrue(result.isFound());
assertEquals(VALUE2, result.getBuffer());
result.clear();
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
public void testBlockCompressionGzip() throws Exception {
doTestBlockCompression(BlockCompressionCodec.GZIP, EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException {
hostConfig.setState(HostState.IDLE);
if (hostConfig.getCurrentCommand() != null) {
processCurrentCommand(hostConfig, hostConfig.getCurrentCommand());
}
while (!goingDown) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOG.debug("Interrupted in run loop. Exiting.");
break;
}
}
hostConfig.setState(HostState.OFFLINE);
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() throws IOException {
hostConfig.setState(HostState.IDLE);
processCommands();
while (!goingDown) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOG.debug("Interrupted in run loop. Exiting.");
break;
}
}
hostConfig.setState(HostState.OFFLINE);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void commitFiles(File sourceRoot, String destinationRoot) throws IOException {
for (File file : sourceRoot.listFiles()) {
// Skip non files
if (!file.isFile()) {
continue;
}
File targetFile = new File(destinationRoot + "/" + file.getName());
// If target file already exists, delete it
if (targetFile.exists()) {
if (!targetFile.delete()) {
throw new IOException("Failed to overwrite file in destination root: " + targetFile.getAbsolutePath());
}
}
// Move file to destination
if (!file.renameTo(targetFile)) {
LOG.info("Committing " + file.getAbsolutePath() + " to " + targetFile.getAbsolutePath());
throw new IOException("Failed to rename source file: " + file.getAbsolutePath()
+ " to destination file: " + targetFile.getAbsolutePath());
}
}
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
protected void commitFiles(File sourceRoot, String destinationRoot) throws IOException {
File[] files = sourceRoot.listFiles();
if (files == null) {
throw new IOException("Failed to commit files from " + sourceRoot + " to " + destinationRoot + " since source is not a valid directory.");
}
for (File file : files) {
// Skip non files
if (!file.isFile()) {
continue;
}
File targetFile = new File(destinationRoot + "/" + file.getName());
// If target file already exists, delete it
if (targetFile.exists()) {
if (!targetFile.delete()) {
throw new IOException("Failed to overwrite file in destination root: " + targetFile.getAbsolutePath());
}
}
// Move file to destination
if (!file.renameTo(targetFile)) {
LOG.info("Committing " + file.getAbsolutePath() + " to " + targetFile.getAbsolutePath());
throw new IOException("Failed to rename source file: " + file.getAbsolutePath()
+ " to destination file: " + targetFile.getAbsolutePath());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Ring addRing(int ringNum) throws IOException {
try {
Ring rc = ZkRing.create(zk, ringGroupPath, ringNum, this, isUpdating() ? getUpdatingToVersion() : getCurrentVersion());
ringsByNumber.put(rc.getRingNumber(), rc);
return rc;
} catch (Exception e) {
throw new IOException(e);
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Ring addRing(int ringNum) throws IOException {
try {
Ring rc = ZkRing.create(zk, ringGroupPath, ringNum, this,
isUpdating() ? getUpdatingToVersion() : getCurrentVersion());
ringsByNumber.put(rc.getRingNumber(), rc);
return rc;
} catch (Exception e) {
throw new IOException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static DomainGroupVersion createNewFastForwardVersion(DomainGroup domainGroup) throws IOException {
Map<Domain, Integer> domainNameToVersion = new HashMap<Domain, Integer>();
// find the latest domain group version
DomainGroupVersion dgv = DomainGroups.getLatestVersion(domainGroup);
// create map of new domains and versions
for (DomainGroupVersionDomainVersion dgvdv : dgv.getDomainVersions()) {
domainNameToVersion.put(dgvdv.getDomain(), Domains.getLatestVersionNotOpenNotDefunct(dgvdv.getDomain()).getVersionNumber());
}
// call regular version creation method
return domainGroup.createNewVersion(domainNameToVersion);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public static DomainGroupVersion createNewFastForwardVersion(DomainGroup domainGroup) throws IOException {
Map<Domain, Integer> domainNameToVersion = new HashMap<Domain, Integer>();
// find the latest domain group version
DomainGroupVersion dgv = DomainGroups.getLatestVersion(domainGroup);
if (dgv == null) {
throw new IllegalArgumentException(
"Supplied domain group must have at least one version, but it did not: " + domainGroup);
}
// create map of new domains and versions
for (DomainGroupVersionDomainVersion dgvdv : dgv.getDomainVersions()) {
domainNameToVersion.put(dgvdv.getDomain(), Domains.getLatestVersionNotOpenNotDefunct(dgvdv.getDomain()).getVersionNumber());
}
// call regular version creation method
return domainGroup.createNewVersion(domainNameToVersion);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void get(int domainId, ByteBuffer key, HostConnectionGetCallback resultHandler) throws TException {
client.get(domainId, key, resultHandler);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void get(int domainId, ByteBuffer key, HostConnectionGetCallback resultHandler) {
try {
client.get(domainId, key, resultHandler);
} catch (TException e) {
resultHandler.onError(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException, InterruptedException {
setState(HostState.IDLE); // In case of exception, server will stop and state will be coherent.
processCurrentCommand();
while (!stopping) {
try {
Thread.sleep(MAIN_THREAD_STEP_SLEEP_MS);
} catch (InterruptedException e) {
LOG.debug("Interrupted in run loop. Exiting.", e);
break;
}
}
// Shuting down
LOG.info("Partition server main thread is stopping.");
// Stop serving data
stopServingData();
// Stop updating if necessary
if (updateThread != null) {
LOG.info("Update thread is still running. Interrupting and waiting for it to finish...");
updateThread.interrupt();
updateThread.join(); // In case of interrupt exception, server will stop and state will be coherent.
}
setState(HostState.OFFLINE); // In case of exception, server will stop and state will be coherent.
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() throws IOException, InterruptedException {
setStateSynchronized(HostState.IDLE); // In case of exception, server will stop and state will be coherent.
processCommandOnStartup();
while (!stopping) {
try {
Thread.sleep(MAIN_THREAD_STEP_SLEEP_MS);
} catch (InterruptedException e) {
LOG.debug("Interrupted in run loop. Exiting.", e);
break;
}
}
// Shuting down
LOG.info("Partition server main thread is stopping.");
// Stop serving data
stopServingData();
// Stop updating if necessary
if (updateThread != null) {
LOG.info("Update thread is still running. Interrupting and waiting for it to finish...");
updateThread.interrupt();
updateThread.join(); // In case of interrupt exception, server will stop and state will be coherent.
}
setStateSynchronized(HostState.OFFLINE); // In case of exception, server will stop and state will be coherent.
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException {
// Add shutdown hook
addShutdownHook();
claimedRingGroupConductor = false;
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting.");
try {
ringGroup = coordinator.getRingGroup(ringGroupName);
// attempt to claim the ring group conductor title
if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) {
claimedRingGroupConductor = true;
// we are now *the* ring group conductor for this ring group.
domainGroup = ringGroup.getDomainGroup();
// set a watch on the ring group
ringGroup.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
stopping = false;
try {
while (!stopping) {
// take a snapshot of the current ring/domain group configs, since
// they might get changed while we're processing the current update.
RingGroup snapshotRingGroup;
DomainGroup snapshotDomainGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
snapshotDomainGroup = domainGroup;
}
// Only process updates if ring group conductor is configured to be active
if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE) {
processUpdates(snapshotRingGroup, snapshotDomainGroup);
}
Thread.sleep(configurator.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
if (claimedRingGroupConductor) {
ringGroup.releaseRingGroupConductor();
claimedRingGroupConductor = false;
}
}
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down.");
// Remove shutdown hook. We don't need it anymore
removeShutdownHook();
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() throws IOException {
// Add shutdown hook
addShutdownHook();
claimedRingGroupConductor = false;
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting.");
try {
ringGroup = coordinator.getRingGroup(ringGroupName);
// attempt to claim the ring group conductor title
if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) {
claimedRingGroupConductor = true;
// we are now *the* ring group conductor for this ring group.
domainGroup = ringGroup.getDomainGroup();
// set a watch on the ring group
ringGroup.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
stopping = false;
try {
while (!stopping) {
// take a snapshot of the current ring/domain group configs, since
// they might get changed while we're processing the current update.
RingGroup snapshotRingGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
}
// Only process updates if ring group conductor is configured to be active
if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE) {
processUpdates(snapshotRingGroup);
}
Thread.sleep(configurator.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
if (claimedRingGroupConductor) {
ringGroup.releaseRingGroupConductor();
claimedRingGroupConductor = false;
}
}
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down.");
// Remove shutdown hook. We don't need it anymore
removeShutdownHook();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException {
for (String emailTarget : emailTargets) {
String[] command = {"/bin/mail", "-s", "Hank: " + name, emailTarget};
Process process = Runtime.getRuntime().exec(command);
OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream());
writer.write(body);
writer.close();
process.getOutputStream().close();
process.waitFor();
}
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException {
Session session = Session.getDefaultInstance(emailSessionProperties);
Message message = new MimeMessage(session);
try {
message.setSubject("Hank: " + name);
for (String emailTarget : emailTargets) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTarget));
}
message.setText(body);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException("Failed to send notification email.", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void sendEmails(Set<String> emailTargets, String body) throws IOException {
File temporaryEmailBody = File.createTempFile("_tmp_" + getClass().getSimpleName(), null);
BufferedWriter writer = new BufferedWriter(new FileWriter(temporaryEmailBody, false));
writer.write(body);
LOG.info("Sending Monitor email to " + emailTargets.size() + " targets: " + emailTargets + " Email body: " + body);
for (String emailTarget : emailTargets) {
Runtime.getRuntime().exec("cat " + temporaryEmailBody.getAbsolutePath()
+ " | mail -s 'Hank Notification' " + emailTarget);
}
if (!temporaryEmailBody.delete()) {
throw new IOException("Could not delete " + temporaryEmailBody.getAbsolutePath());
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException {
LOG.info("Sending Monitor email to " + emailTargets.size() + " targets: " + emailTargets + " Email body: " + body);
for (String emailTarget : emailTargets) {
String[] command = {"/bin/mail", "-s", "Hank-Notification", emailTarget};
Process process = Runtime.getRuntime().exec(command);
OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream());
writer.write(body);
writer.close();
process.getOutputStream().close();
process.waitFor();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private ByteBuffer decompressBlock(ByteBuffer block) throws IOException {
Buffers buffers = threadLocalBuffers.get();
buffers.reset();
// Decompress the block
InputStream blockInputStream =
new ByteArrayInputStream(block.array(), block.arrayOffset() + block.position(), block.remaining());
// Build an InputStream corresponding to the compression codec
InputStream decompressedBlockInputStream = getBlockCompressionInputStream(blockInputStream);
// Decompress into the specialized result buffer
IOStreamUtils.copy(decompressedBlockInputStream, buffers.getDecompressionOutputStream(), buffers.getCopyBuffer());
decompressedBlockInputStream.close();
return buffers.getDecompressionOutputStream().getByteBuffer();
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
private ByteBuffer decompressBlock(ByteBuffer block) throws IOException {
Local local = threadLocal.get();
local.reset();
local.getBlockDecompressor().decompress(
block.array(),
block.arrayOffset() + block.position(),
block.remaining(),
local.getDecompressionOutputStream());
return local.getDecompressionOutputStream().getByteBuffer();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException {
Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath));
File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName());
LOG.info("Copying remote file " + source + " to local file " + destination);
InputStream inputStream = getInputStream(remoteSourceRelativePath);
FileOutputStream fileOutputStream = new FileOutputStream(destination);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
// Use copyLarge (over 2GB)
try {
IOUtils.copyLarge(inputStream, bufferedOutputStream);
bufferedOutputStream.flush();
fileOutputStream.flush();
} finally {
inputStream.close();
bufferedOutputStream.close();
fileOutputStream.close();
}
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public void copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException {
Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath));
File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName());
LOG.info("Copying remote file " + source + " to local file " + destination);
InputStream inputStream = getInputStream(remoteSourceRelativePath);
FileOutputStream fileOutputStream = new FileOutputStream(destination);
try {
IOStreamUtils.copy(inputStream, fileOutputStream);
fileOutputStream.flush();
} finally {
inputStream.close();
fileOutputStream.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void stop() {
goingDown = true;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void stop() {
stopping = true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void assign(RingGroup ringGroup, int ringNum, Domain domain) throws IOException {
ring = ringGroup.getRing(ringNum);
domainGroup = ringGroup.getDomainGroup();
domainId = domainGroup.getDomainId(domain.getName());
version = domainGroup.getLatestVersion().getVersionNumber();
random = new Random();
// make random assignments for any of the currently unassigned parts
for (Integer partNum : ring.getUnassignedPartitions(domain)) {
getMinHostDomain().addPartition(partNum, version);
}
while (!assignmentsBalanced()) {
HostDomain maxHostDomain = getMaxHostDomain();
HostDomain minHostDomain = getMinHostDomain();
// pick a random partition from the maxHost
ArrayList<HostDomainPartition> partitions = new ArrayList<HostDomainPartition>();
partitions.addAll(maxHostDomain.getPartitions());
final HostDomainPartition toMove = partitions.get(random.nextInt(partitions.size()));
// assign it to the min host. note that we assign it before we unassign it
// to ensure that if we fail at this point, we haven't left any parts
// unassigned.
minHostDomain.addPartition(toMove.getPartNum(), version);
// unassign it from the max host
unassign(toMove);
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void assign(RingGroup ringGroup, int ringNum, Domain domain) throws IOException {
ring = ringGroup.getRing(ringNum);
domainGroup = ringGroup.getDomainGroup();
domainId = domainGroup.getDomainId(domain.getName());
version = domainGroup.getLatestVersion().getVersionNumber();
random = new Random();
for (Host host : ring.getHosts()) {
if (host.getDomainById(domainId) == null)
host.addDomain(domainId);
}
// make random assignments for any of the currently unassigned parts
for (Integer partNum : ring.getUnassignedPartitions(domain)) {
getMinHostDomain().addPartition(partNum, version);
}
while (!assignmentsBalanced()) {
HostDomain maxHostDomain = getMaxHostDomain();
HostDomain minHostDomain = getMinHostDomain();
// pick a random partition from the maxHost
ArrayList<HostDomainPartition> partitions = new ArrayList<HostDomainPartition>();
partitions.addAll(maxHostDomain.getPartitions());
final HostDomainPartition toMove = partitions.get(random.nextInt(partitions.size()));
// assign it to the min host. note that we assign it before we unassign it
// to ensure that if we fail at this point, we haven't left any parts
// unassigned.
minHostDomain.addPartition(toMove.getPartNum(), version);
// unassign it from the max host
unassign(toMove);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
boolean isAvailable() {
return state != HostConnectionState.STANDBY;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Host getHost() {
return host;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testBlockCompressionSnappy() throws Exception {
new File(TMP_TEST_CURLY_READER).mkdirs();
OutputStream s = new FileOutputStream(TMP_TEST_CURLY_READER + "/00000.base.curly");
s.write(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_SNAPPY);
s.flush();
s.close();
MapReader keyfileReader = new MapReader(0,
KEY1.array(), new byte[]{0, 0, 0, 0, 0},
KEY2.array(), new byte[]{0, 0, 0, 5, 0},
KEY3.array(), new byte[]{0, 0, 0, 10, 0}
);
CurlyReader reader = new CurlyReader(CurlyReader.getLatestBase(TMP_TEST_CURLY_READER), 1024, keyfileReader, -1,
BlockCompressionCodec.SNAPPY, 3, 2, true);
ReaderResult result = new ReaderResult();
reader.get(KEY1, result);
assertTrue(result.isFound());
assertEquals(VALUE1, result.getBuffer());
result.clear();
reader.get(KEY4, result);
assertFalse(result.isFound());
result.clear();
reader.get(KEY3, result);
assertTrue(result.isFound());
assertEquals(VALUE3, result.getBuffer());
result.clear();
reader.get(KEY2, result);
assertTrue(result.isFound());
assertEquals(VALUE2, result.getBuffer());
result.clear();
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
public void testBlockCompressionSnappy() throws Exception {
doTestBlockCompression(BlockCompressionCodec.SNAPPY, EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_SNAPPY);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean isDeletable() throws IOException {
if (deletable != null) {
return deletable.get();
} else {
try {
return WatchedBoolean.get(zk, ZkPath.append(path, DELETABLE_PATH_SEGMENT));
} catch (Exception e) {
throw new IOException(e);
}
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public boolean isDeletable() throws IOException {
Boolean result;
if (deletable != null) {
result = deletable.get();
} else {
try {
result = WatchedBoolean.get(zk, ZkPath.append(path, DELETABLE_PATH_SEGMENT));
} catch (Exception e) {
throw new IOException(e);
}
}
if (result == null) {
return false;
} else {
return result;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
boolean isAvailable() {
return state != HostConnectionState.STANDBY;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
Host getHost() {
return host;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException, InterruptedException {
// Add shutdown hook
addShutdownHook();
// Initialize and process commands
setStateSynchronized(HostState.IDLE); // In case of exception, server will stop and state will be coherent.
// Wait for state to propagate
while (host.getState() != HostState.IDLE) {
LOG.info("Waiting for Host state " + HostState.IDLE + " to propagate.");
Thread.sleep(100);
}
processCommandOnStartup();
while (!stopping) {
try {
Thread.sleep(MAIN_THREAD_STEP_SLEEP_MS);
} catch (InterruptedException e) {
LOG.info("Interrupted in run loop. Exiting.", e);
break;
}
}
// Shuting down
LOG.info("Partition server main thread is stopping.");
// Stop serving data
stopServingData();
// Stop updating if necessary
if (updateThread != null) {
LOG.info("Update thread is still running. Interrupting and waiting for it to finish...");
updateThread.interrupt();
updateThread.join(); // In case of interrupt exception, server will stop and state will be coherent.
}
setStateSynchronized(HostState.OFFLINE); // In case of exception, server will stop and state will be coherent.
// Remove shutdown hook. We don't need it anymore as we just set the host state to OFFLINE
removeShutdownHook();
}
#location 28
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() throws IOException, InterruptedException {
// Add shutdown hook
addShutdownHook();
// Initialize and process commands
setStateSynchronized(HostState.IDLE); // In case of exception, server will stop and state will be coherent.
// Wait for state to propagate
while (host.getState() != HostState.IDLE) {
LOG.info("Waiting for Host state " + HostState.IDLE + " to propagate.");
Thread.sleep(100);
}
processCommandOnStartup();
while (!stopping) {
try {
HostCommand command = commandQueue.poll(MAIN_THREAD_STEP_SLEEP_MS, TimeUnit.MILLISECONDS);
if (command != null) {
try {
processCommand(command, host.getState());
} catch (IOException e) {
LOG.error("Failed to process command: " + command, e);
break;
}
}
} catch (InterruptedException e) {
LOG.info("Interrupted in main loop. Exiting.", e);
break;
}
}
// Shuting down
LOG.info("Partition server main thread is stopping.");
// Stop serving data
stopServingData();
// Stop updating if necessary
stopUpdating();
// Signal OFFLINE
setStateSynchronized(HostState.OFFLINE); // In case of exception, server will stop and state will be coherent.
// Remove shutdown hook. We don't need it anymore as we just set the host state to OFFLINE
removeShutdownHook();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException {
LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " starting.");
boolean claimedRingGroupConductor = false;
try {
ringGroup = coordinator.getRingGroup(ringGroupName);
// attempt to claim the ring group conductor title
if (ringGroup.claimRingGroupConductor()) {
claimedRingGroupConductor = true;
// we are now *the* ring group conductor for this ring group.
domainGroup = ringGroup.getDomainGroup();
// set a watch on the ring group
ringGroup.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
goingDown = false;
try {
while (!goingDown) {
// take a snapshot of the current ring/domain group configs, since
// they might get changed while we're processing the current update.
RingGroup snapshotRingGroup;
DomainGroup snapshotDomainGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
snapshotDomainGroup = domainGroup;
}
processUpdates(snapshotRingGroup, snapshotDomainGroup);
Thread.sleep(configurator.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
if (claimedRingGroupConductor) {
ringGroup.releaseRingGroupConductor();
}
}
LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " shutting down.");
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() throws IOException {
LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " starting.");
boolean claimedRingGroupConductor = false;
try {
ringGroup = coordinator.getRingGroup(ringGroupName);
// attempt to claim the ring group conductor title
if (ringGroup.claimRingGroupConductor()) {
claimedRingGroupConductor = true;
// we are now *the* ring group conductor for this ring group.
domainGroup = ringGroup.getDomainGroup();
// set a watch on the ring group
ringGroup.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
stopping = false;
try {
while (!stopping) {
// take a snapshot of the current ring/domain group configs, since
// they might get changed while we're processing the current update.
RingGroup snapshotRingGroup;
DomainGroup snapshotDomainGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
snapshotDomainGroup = domainGroup;
}
processUpdates(snapshotRingGroup, snapshotDomainGroup);
Thread.sleep(configurator.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
if (claimedRingGroupConductor) {
ringGroup.releaseRingGroupConductor();
}
}
LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " shutting down.");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void merge(final CueballFilePath base,
final List<CueballFilePath> deltas,
final String newBasePath,
final int keyHashSize,
final int valueSize,
ValueTransformer transformer,
int hashIndexBits,
CompressionCodec compressionCodec) throws IOException {
// Array of stream buffers for the base and all deltas in order
CueballStreamBuffer[] cueballStreamBuffers = new CueballStreamBuffer[deltas.size() + 1];
// Open the current base
CueballStreamBuffer cueballBaseStreamBuffer = new CueballStreamBuffer(base.getPath(), 0,
keyHashSize, valueSize, hashIndexBits, compressionCodec);
cueballStreamBuffers[0] = cueballBaseStreamBuffer;
// Open all the deltas
int i = 1;
for (CueballFilePath delta : deltas) {
CueballStreamBuffer cueballStreamBuffer =
new CueballStreamBuffer(delta.getPath(), i, keyHashSize, valueSize, hashIndexBits, compressionCodec);
cueballStreamBuffers[i++] = cueballStreamBuffer;
}
// Output stream for the new base to be written. intentionally unbuffered, the writer below will do that on its own.
OutputStream newCueballBaseOutputStream = new FileOutputStream(newBasePath);
// Note that we intentionally omit the hasher here, since it will *not* be used
CueballWriter newCueballBaseWriter =
new CueballWriter(newCueballBaseOutputStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits);
while (true) {
// Find the stream buffer with the next smallest key hash
CueballStreamBuffer cueballStreamBufferToUse = null;
for (i = 0; i < cueballStreamBuffers.length; i++) {
if (cueballStreamBuffers[i].anyRemaining()) {
if (cueballStreamBufferToUse == null) {
cueballStreamBufferToUse = cueballStreamBuffers[i];
} else {
int comparison = cueballStreamBufferToUse.compareTo(cueballStreamBuffers[i]);
if (comparison == 0) {
// If two equal key hashes are found, use the most recent value (i.e. the one from the lastest delta)
// and skip (consume) the older ones
cueballStreamBufferToUse.consume();
cueballStreamBufferToUse = cueballStreamBuffers[i];
} else if (comparison == 1) {
// Found a stream buffer with a smaller key hash
cueballStreamBufferToUse = cueballStreamBuffers[i];
}
}
}
}
if (cueballStreamBufferToUse == null) {
// Nothing more to write
break;
}
// Transform if necessary
if (transformer != null) {
transformer.transform(cueballStreamBufferToUse.getBuffer(),
cueballStreamBufferToUse.getCurrentOffset() + keyHashSize,
cueballStreamBufferToUse.getIndex());
}
// Get next key hash and value
final ByteBuffer keyHash = ByteBuffer.wrap(cueballStreamBufferToUse.getBuffer(),
cueballStreamBufferToUse.getCurrentOffset(), keyHashSize);
final ByteBuffer valueBytes = ByteBuffer.wrap(cueballStreamBufferToUse.getBuffer(),
cueballStreamBufferToUse.getCurrentOffset() + keyHashSize, valueSize);
// Write next key hash and value
newCueballBaseWriter.writeHash(keyHash, valueBytes);
cueballStreamBufferToUse.consume();
}
// Close all buffers and the base writer
for (CueballStreamBuffer cueballStreamBuffer : cueballStreamBuffers) {
cueballStreamBuffer.close();
}
newCueballBaseWriter.close();
}
#location 81
#vulnerability type RESOURCE_LEAK | #fixed code
public void merge(final CueballFilePath base,
final List<CueballFilePath> deltas,
final String newBasePath,
final int keyHashSize,
final int valueSize,
ValueTransformer transformer,
int hashIndexBits,
CompressionCodec compressionCodec) throws IOException {
CueballStreamBufferMergeSort cueballStreamBufferMergeSort = new CueballStreamBufferMergeSort(base,
deltas,
keyHashSize,
hashIndexBits,
valueSize,
compressionCodec,
transformer);
// Output stream for the new base to be written. intentionally unbuffered, the writer below will do that on its own.
OutputStream newCueballBaseOutputStream = new FileOutputStream(newBasePath);
// Note that we intentionally omit the hasher here, since it will *not* be used
CueballWriter newCueballBaseWriter =
new CueballWriter(newCueballBaseOutputStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits);
while (true) {
CueballStreamBufferMergeSort.KeyHashValuePair keyValuePair = cueballStreamBufferMergeSort.nextKeyValuePair();
if (keyValuePair == null) {
break;
}
// Write next key hash and value
newCueballBaseWriter.writeHash(keyValuePair.keyHash, keyValuePair.value);
}
// Close all buffers and the base writer
cueballStreamBufferMergeSort.close();
newCueballBaseWriter.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException {
// Add shutdown hook
addShutdownHook();
claimedRingGroupConductor = false;
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting.");
try {
ringGroup = coordinator.getRingGroup(ringGroupName);
// attempt to claim the ring group conductor title
if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) {
claimedRingGroupConductor = true;
// we are now *the* ring group conductor for this ring group.
domainGroup = ringGroup.getDomainGroup();
// set a watch on the ring group
ringGroup.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
stopping = false;
try {
while (!stopping) {
// take a snapshot of the current ring, since
// it might get changed while we're processing the current update.
RingGroup snapshotRingGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
}
// Only process updates if ring group conductor is configured to be active/proactive
if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE ||
snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) {
processUpdates(snapshotRingGroup);
}
Thread.sleep(configurator.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
if (claimedRingGroupConductor) {
ringGroup.releaseRingGroupConductor();
claimedRingGroupConductor = false;
}
}
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down.");
// Remove shutdown hook. We don't need it anymore
removeShutdownHook();
}
#location 49
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() throws IOException {
// Add shutdown hook
addShutdownHook();
claimedRingGroupConductor = false;
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting.");
try {
ringGroup = coordinator.getRingGroup(ringGroupName);
// attempt to claim the ring group conductor title
if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) {
claimedRingGroupConductor = true;
// we are now *the* ring group conductor for this ring group.
domainGroup = ringGroup.getDomainGroup();
// set a watch on the ring group
ringGroup.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
stopping = false;
try {
while (!stopping) {
// take a snapshot of the current ring, since it might get changed
// while we're processing the current update.
RingGroup snapshotRingGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
}
// Only process updates if ring group conductor is configured to be active/proactive
if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE ||
snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) {
processUpdates(snapshotRingGroup);
}
Thread.sleep(configurator.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
releaseIfClaimed();
}
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down.");
// Remove shutdown hook. We don't need it anymore
removeShutdownHook();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testGzipBlockCompression() throws Exception {
ByteArrayOutputStream s = new ByteArrayOutputStream();
MapWriter keyfileWriter = new MapWriter();
CurlyWriter writer = new CurlyWriter(s, keyfileWriter, 3, -1, BlockCompressionCodec.GZIP, 1024, 2);
writer.write(KEY1, VALUE1);
writer.write(KEY2, VALUE2);
writer.write(KEY3, VALUE3);
writer.close();
assertTrue(writer.getNumBytesWritten() > 0);
assertEquals(3, writer.getNumRecordsWritten());
// verify the keyfile looks as expected
assertTrue(keyfileWriter.entries.containsKey(KEY1));
System.out.println("k1=" + Bytes.bytesToHexString(keyfileWriter.entries.get(KEY1))); //TODO: remove
System.out.println("k2=" + Bytes.bytesToHexString(keyfileWriter.entries.get(KEY2))); //TODO: remove
System.out.println("k3=" + Bytes.bytesToHexString(keyfileWriter.entries.get(KEY3))); //TODO: remove
assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 0, 0}), keyfileWriter.entries.get(KEY1));
assertTrue(keyfileWriter.entries.containsKey(KEY2));
assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 5, 0}), keyfileWriter.entries.get(KEY2));
assertTrue(keyfileWriter.entries.containsKey(KEY3));
assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 10, 0}), keyfileWriter.entries.get(KEY3));
assertFalse(keyfileWriter.entries.containsKey(KEY4));
// verify that the record stream looks as expected
System.out.println(Bytes.bytesToHexString(ByteBuffer.wrap(s.toByteArray()))); //TODO: remove
assertEquals(ByteBuffer.wrap(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP), ByteBuffer.wrap(s.toByteArray()));
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
public void testGzipBlockCompression() throws Exception {
ByteArrayOutputStream s = new ByteArrayOutputStream();
MapWriter keyfileWriter = new MapWriter();
CurlyWriter writer = new CurlyWriter(s, keyfileWriter, 3, -1, BlockCompressionCodec.GZIP, 1024, 2);
writer.write(KEY1, VALUE1);
writer.write(KEY2, VALUE2);
writer.write(KEY3, VALUE3);
writer.close();
assertTrue(writer.getNumBytesWritten() > 0);
assertEquals(3, writer.getNumRecordsWritten());
// verify the keyfile looks as expected
assertTrue(keyfileWriter.entries.containsKey(KEY1));
assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 0, 0}), keyfileWriter.entries.get(KEY1));
assertTrue(keyfileWriter.entries.containsKey(KEY2));
assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 5, 0}), keyfileWriter.entries.get(KEY2));
assertTrue(keyfileWriter.entries.containsKey(KEY3));
assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 10, 0}), keyfileWriter.entries.get(KEY3));
assertFalse(keyfileWriter.entries.containsKey(KEY4));
// verify that the record stream looks as expected
assertEquals(ByteBuffer.wrap(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP), ByteBuffer.wrap(s.toByteArray()));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testBlockCompressionGzip() throws Exception {
new File(TMP_TEST_CURLY_READER).mkdirs();
OutputStream s = new FileOutputStream(TMP_TEST_CURLY_READER + "/00000.base.curly");
s.write(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP);
s.flush();
s.close();
MapReader keyfileReader = new MapReader(0,
KEY1.array(), new byte[]{0, 0, 0, 0, 0},
KEY2.array(), new byte[]{0, 0, 0, 5, 0},
KEY3.array(), new byte[]{0, 0, 0, 10, 0}
);
CurlyReader reader = new CurlyReader(CurlyReader.getLatestBase(TMP_TEST_CURLY_READER), 1024, keyfileReader, -1,
BlockCompressionCodec.GZIP, 3, 2, true);
ReaderResult result = new ReaderResult();
reader.get(KEY1, result);
assertTrue(result.isFound());
assertEquals(VALUE1, result.getBuffer());
result.clear();
reader.get(KEY4, result);
assertFalse(result.isFound());
result.clear();
reader.get(KEY3, result);
assertTrue(result.isFound());
assertEquals(VALUE3, result.getBuffer());
result.clear();
reader.get(KEY2, result);
assertTrue(result.isFound());
assertEquals(VALUE2, result.getBuffer());
result.clear();
}
#location 37
#vulnerability type RESOURCE_LEAK | #fixed code
public void testBlockCompressionGzip() throws Exception {
doTestBlockCompression(BlockCompressionCodec.GZIP, EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static ZkRingGroup create(ZooKeeperPlus zk, String path, ZkDomainGroup domainGroup, Coordinator coordinator) throws KeeperException, InterruptedException, IOException {
if (domainGroup.getVersions().isEmpty()) {
throw new IllegalStateException(
"You cannot create a ring group for a domain group that has no versions!");
}
zk.create(path, domainGroup.getName().getBytes());
zk.create(ZkPath.append(path, CURRENT_VERSION_PATH_SEGMENT), null);
zk.create(ZkPath.append(path, UPDATING_TO_VERSION_PATH_SEGMENT),
(Integer.toString(domainGroup.getLatestVersion().getVersionNumber())).getBytes());
return new ZkRingGroup(zk, path, domainGroup, coordinator);
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
public static ZkRingGroup create(ZooKeeperPlus zk, String path, ZkDomainGroup domainGroup, Coordinator coordinator) throws KeeperException, InterruptedException, IOException {
if (domainGroup.getVersions().isEmpty()) {
throw new IllegalStateException(
"You cannot create a ring group for a domain group that has no versions!");
}
zk.create(path, domainGroup.getName().getBytes());
zk.create(ZkPath.append(path, CURRENT_VERSION_PATH_SEGMENT), null);
zk.create(ZkPath.append(path, UPDATING_TO_VERSION_PATH_SEGMENT),
(Integer.toString(DomainGroupUtils.getLatestVersion(domainGroup).getVersionNumber())).getBytes());
return new ZkRingGroup(zk, path, domainGroup, coordinator);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void updateComplete() throws IOException {
try {
if (zk.exists(ringPath + CURRENT_VERSION_PATH_SEGMENT, false) != null) {
zk.setData(ringPath + CURRENT_VERSION_PATH_SEGMENT, getUpdatingToVersionNumber().toString().getBytes(), -1);
} else {
zk.create(ringPath + CURRENT_VERSION_PATH_SEGMENT, getUpdatingToVersionNumber().toString().getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.delete(ringPath + UPDATING_TO_VERSION_PATH_SEGMENT, -1);
} catch (Exception e) {
throw new IOException(e);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void updateComplete() throws IOException {
try {
currentVersionNumber.set(getUpdatingToVersionNumber());
updatingToVersionNumber.set(null);
} catch (Exception e) {
throw new IOException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void runUpdateCore(DomainVersion currentVersion,
DomainVersion updatingToVersion,
IncrementalUpdatePlan updatePlan,
String updateWorkRoot) throws IOException {
// Prepare Curly
// Determine files from versions
CurlyFilePath curlyBasePath = getCurlyFilePathForVersion(updatePlan.getBase(), currentVersion, true);
List<CurlyFilePath> curlyDeltas = new ArrayList<CurlyFilePath>();
for (DomainVersion curlyDeltaVersion : updatePlan.getDeltasOrdered()) {
// Only add to the delta list if the version is not empty
if (!isEmptyVersion(curlyDeltaVersion)) {
curlyDeltas.add(getCurlyFilePathForVersion(curlyDeltaVersion, currentVersion, false));
}
}
// Check that all required files are available
CueballPartitionUpdater.checkRequiredFileExists(curlyBasePath.getPath());
for (CurlyFilePath curlyDelta : curlyDeltas) {
CueballPartitionUpdater.checkRequiredFileExists(curlyDelta.getPath());
}
// Prepare Cueball
// Determine files from versions
CueballFilePath cueballBasePath = CueballPartitionUpdater.getCueballFilePathForVersion(updatePlan.getBase(),
currentVersion, localPartitionRoot, localPartitionRootCache, true);
List<CueballFilePath> cueballDeltas = new ArrayList<CueballFilePath>();
for (DomainVersion cueballDelta : updatePlan.getDeltasOrdered()) {
// Only add to the delta list if the version is not empty
if (!CueballPartitionUpdater.isEmptyVersion(cueballDelta, partitionRemoteFileOps)) {
cueballDeltas.add(CueballPartitionUpdater.getCueballFilePathForVersion(cueballDelta, currentVersion,
localPartitionRoot, localPartitionRootCache, false));
}
}
// Check that all required files are available
CueballPartitionUpdater.checkRequiredFileExists(cueballBasePath.getPath());
for (CueballFilePath cueballDelta : cueballDeltas) {
CueballPartitionUpdater.checkRequiredFileExists(cueballDelta.getPath());
}
// Determine new Curly base path
CurlyFilePath newCurlyBasePath =
new CurlyFilePath(updateWorkRoot + "/" + Curly.getName(updatingToVersion.getVersionNumber(), true));
// Determine new Cueball base path
CueballFilePath newCueballBasePath =
new CueballFilePath(updateWorkRoot + "/" + Cueball.getName(updatingToVersion.getVersionNumber(), true));
OutputStream newCurlyBaseOutputStream = new FileOutputStream(newCurlyBasePath.getPath());
OutputStream newCueballBaseOutputStream = new FileOutputStream(newCueballBasePath.getPath());
// Note: the Cueball writer used to perform the compaction must not hash the passed-in key because
// it will directly receive key hashes. This is because the actual key is unknown when compacting.
// TODO: Using an identity hasher and actually copying the bytes is unnecessary and inefficient.
// TODO: (continued) Adding the logic of writing directly a hash could be added to Cueball.
CueballWriter cueballWriter = new CueballWriter(newCueballBaseOutputStream, keyHashSize,
new IdentityHasher(), offsetSize, compressionCodec, hashIndexBits);
CurlyWriter curlyWriter = new CurlyWriter(newCurlyBaseOutputStream, cueballWriter, offsetSize);
merger.merge(curlyBasePath, curlyDeltas, cueballBasePath, cueballDeltas, curlyWriter);
}
#location 65
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
protected void runUpdateCore(DomainVersion currentVersion,
DomainVersion updatingToVersion,
IncrementalUpdatePlan updatePlan,
String updateWorkRoot) throws IOException {
// Prepare Curly
// Determine files from versions
CurlyFilePath curlyBasePath = getCurlyFilePathForVersion(updatePlan.getBase(), currentVersion, true);
List<CurlyFilePath> curlyDeltas = new ArrayList<CurlyFilePath>();
for (DomainVersion curlyDeltaVersion : updatePlan.getDeltasOrdered()) {
// Only add to the delta list if the version is not empty
if (!isEmptyVersion(curlyDeltaVersion)) {
curlyDeltas.add(getCurlyFilePathForVersion(curlyDeltaVersion, currentVersion, false));
}
}
// Check that all required files are available
CueballPartitionUpdater.checkRequiredFileExists(curlyBasePath.getPath());
for (CurlyFilePath curlyDelta : curlyDeltas) {
CueballPartitionUpdater.checkRequiredFileExists(curlyDelta.getPath());
}
// Prepare Cueball
// Determine files from versions
CueballFilePath cueballBasePath = CueballPartitionUpdater.getCueballFilePathForVersion(updatePlan.getBase(),
currentVersion, localPartitionRoot, localPartitionRootCache, true);
List<CueballFilePath> cueballDeltas = new ArrayList<CueballFilePath>();
for (DomainVersion cueballDelta : updatePlan.getDeltasOrdered()) {
// Only add to the delta list if the version is not empty
if (!CueballPartitionUpdater.isEmptyVersion(cueballDelta, partitionRemoteFileOps)) {
cueballDeltas.add(CueballPartitionUpdater.getCueballFilePathForVersion(cueballDelta, currentVersion,
localPartitionRoot, localPartitionRootCache, false));
}
}
// Check that all required files are available
CueballPartitionUpdater.checkRequiredFileExists(cueballBasePath.getPath());
for (CueballFilePath cueballDelta : cueballDeltas) {
CueballPartitionUpdater.checkRequiredFileExists(cueballDelta.getPath());
}
// Determine new Curly base path
CurlyFilePath newCurlyBasePath =
new CurlyFilePath(updateWorkRoot + "/" + Curly.getName(updatingToVersion.getVersionNumber(), true));
// Determine new Cueball base path
CueballFilePath newCueballBasePath =
new CueballFilePath(updateWorkRoot + "/" + Cueball.getName(updatingToVersion.getVersionNumber(), true));
OutputStream newCurlyBaseOutputStream = new FileOutputStream(newCurlyBasePath.getPath());
OutputStream newCueballBaseOutputStream = new FileOutputStream(newCueballBasePath.getPath());
// Note: the Curly writer used to perform the compaction must not hash the passed-in key because
// it will directly receive key hashes. This is because the actual key is unknown when compacting.
CurlyWriter curlyWriter = curlyWriterFactory.getCurlyWriter(newCueballBaseOutputStream, newCurlyBaseOutputStream);
IKeyFileStreamBufferMergeSort cueballStreamBufferMergeSort =
cueballStreamBufferMergeSortFactory.getInstance(cueballBasePath, cueballDeltas);
merger.merge(curlyBasePath, curlyDeltas, cueballStreamBufferMergeSort, curlyWriter);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException, InterruptedException {
// Add shutdown hook
addShutdownHook();
// Initialize and process commands
setStateSynchronized(HostState.IDLE); // In case of exception, server will stop and state will be coherent.
// Wait for state to propagate
while (host.getState() != HostState.IDLE) {
LOG.info("Waiting for Host state " + HostState.IDLE + " to propagate.");
Thread.sleep(100);
}
processCommandOnStartup();
while (!stopping) {
try {
Thread.sleep(MAIN_THREAD_STEP_SLEEP_MS);
} catch (InterruptedException e) {
LOG.info("Interrupted in run loop. Exiting.", e);
break;
}
}
// Shuting down
LOG.info("Partition server main thread is stopping.");
// Stop serving data
stopServingData();
// Stop updating if necessary
if (updateThread != null) {
LOG.info("Update thread is still running. Interrupting and waiting for it to finish...");
updateThread.interrupt();
updateThread.join(); // In case of interrupt exception, server will stop and state will be coherent.
}
setStateSynchronized(HostState.OFFLINE); // In case of exception, server will stop and state will be coherent.
// Remove shutdown hook. We don't need it anymore as we just set the host state to OFFLINE
removeShutdownHook();
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() throws IOException, InterruptedException {
// Add shutdown hook
addShutdownHook();
// Initialize and process commands
setStateSynchronized(HostState.IDLE); // In case of exception, server will stop and state will be coherent.
// Wait for state to propagate
while (host.getState() != HostState.IDLE) {
LOG.info("Waiting for Host state " + HostState.IDLE + " to propagate.");
Thread.sleep(100);
}
processCommandOnStartup();
while (!stopping) {
try {
HostCommand command = commandQueue.poll(MAIN_THREAD_STEP_SLEEP_MS, TimeUnit.MILLISECONDS);
if (command != null) {
try {
processCommand(command, host.getState());
} catch (IOException e) {
LOG.error("Failed to process command: " + command, e);
break;
}
}
} catch (InterruptedException e) {
LOG.info("Interrupted in main loop. Exiting.", e);
break;
}
}
// Shuting down
LOG.info("Partition server main thread is stopping.");
// Stop serving data
stopServingData();
// Stop updating if necessary
stopUpdating();
// Signal OFFLINE
setStateSynchronized(HostState.OFFLINE); // In case of exception, server will stop and state will be coherent.
// Remove shutdown hook. We don't need it anymore as we just set the host state to OFFLINE
removeShutdownHook();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException {
for (String emailTarget : emailTargets) {
String[] command = {"/bin/mail", "-s", "Hank: " + name, emailTarget};
Process process = Runtime.getRuntime().exec(command);
OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream());
writer.write(body);
writer.close();
process.getOutputStream().close();
process.waitFor();
}
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException {
Session session = Session.getDefaultInstance(emailSessionProperties);
Message message = new MimeMessage(session);
try {
message.setSubject("Hank: " + name);
for (String emailTarget : emailTargets) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTarget));
}
message.setText(body);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException("Failed to send notification email.", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void addCompleteTask(GetTask task) {
synchronized (getTasksComplete) {
getTasksComplete.addLast(task);
}
dispatcherThread.interrupt();
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void addCompleteTask(GetTask task) {
synchronized (getTasksComplete) {
getTasksComplete.addLast(task);
}
//dispatcherThread.interrupt();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private Flow build(Properties cascasdingProperties,
TapOrTapMap sources) throws IOException {
pipe = new DomainBuilderAssembly(properties.getDomainName(), pipe, keyFieldName, valueFieldName);
// Open new version and check for success
openNewVersion();
Flow flow = null;
try {
// Build flow
flow = getFlow(cascasdingProperties, sources);
// Set up job
DomainBuilderOutputCommitter.setupJob(properties.getDomainName(), flow.getJobConf());
// Complete flow
flow.complete();
// Commit job
DomainBuilderOutputCommitter.commitJob(properties.getDomainName(), flow.getJobConf());
} catch (Exception e) {
// In case of failure, cancel this new version
cancelNewVersion();
// Clean up job
if (flow != null) {
DomainBuilderOutputCommitter.cleanupJob(properties.getDomainName(), flow.getJobConf());
}
e.printStackTrace();
throw new IOException("Failed at building version " + domainVersion.getVersionNumber() +
" of domain " + properties.getDomainName() + ". Cancelling version.", e);
}
// Close the new version
closeNewVersion();
// Clean up job
DomainBuilderOutputCommitter.cleanupJob(properties.getDomainName(), flow.getJobConf());
return flow;
}
#location 32
#vulnerability type NULL_DEREFERENCE | #fixed code
private Flow build(Properties cascasdingProperties,
TapOrTapMap sources) throws IOException {
pipe = new DomainBuilderAssembly(properties.getDomainName(), pipe, keyFieldName, valueFieldName);
// Open new version and check for success
openNewVersion();
Flow flow = null;
try {
// Build flow
flow = getFlow(cascasdingProperties, sources);
// Set up job
DomainBuilderOutputCommitter.setupJob(properties.getDomainName(), flow.getJobConf());
// Complete flow
flow.complete();
// Commit job
DomainBuilderOutputCommitter.commitJob(properties.getDomainName(), flow.getJobConf());
} catch (Exception e) {
String exceptionMessage = "Failed at building version " + domainVersion.getVersionNumber() +
" of domain " + properties.getDomainName() + ". Cancelling version.";
// In case of failure, cancel this new version
cancelNewVersion();
// Clean up job
if (flow != null) {
DomainBuilderOutputCommitter.cleanupJob(properties.getDomainName(), flow.getJobConf());
}
e.printStackTrace();
throw new IOException(exceptionMessage, e);
}
// Close the new version
closeNewVersion();
// Clean up job
DomainBuilderOutputCommitter.cleanupJob(properties.getDomainName(), flow.getJobConf());
return flow;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void merge(final CueballFilePath base,
final List<CueballFilePath> deltas,
final String newBasePath,
final int keyHashSize,
final int valueSize,
ValueTransformer transformer,
int hashIndexBits,
CompressionCodec compressionCodec) throws IOException {
// Perform merging
StreamBuffer[] sbs = new StreamBuffer[deltas.size() + 1];
// open the current base
StreamBuffer baseBuffer = new StreamBuffer(base.getPath(), 0,
keyHashSize, valueSize, hashIndexBits, compressionCodec);
sbs[0] = baseBuffer;
// open all the deltas
int i = 1;
for (CueballFilePath delta : deltas) {
StreamBuffer db = new StreamBuffer(delta.getPath(), i,
keyHashSize, valueSize, hashIndexBits, compressionCodec);
sbs[i++] = db;
}
// output stream for the new base to be written. intentionally unbuffered -
// the writer below will do that on its own.
OutputStream newBaseStream = new FileOutputStream(newBasePath);
// note that we intentionally omit the hasher here, since it will *not* be
// used
CueballWriter writer = new CueballWriter(newBaseStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits);
while (true) {
StreamBuffer least = null;
for (i = 0; i < sbs.length; i++) {
boolean remaining = sbs[i].anyRemaining();
if (remaining) {
if (least == null) {
least = sbs[i];
} else {
int comparison = least.compareTo(sbs[i]);
if (comparison == 0) {
least.consume();
least = sbs[i];
} else if (comparison == 1) {
least = sbs[i];
}
}
}
}
if (least == null) {
break;
}
if (transformer != null) {
transformer.transform(least.getBuffer(), least.getCurrentOffset() + keyHashSize, least.getIndex());
}
final ByteBuffer keyHash = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset(), keyHashSize);
final ByteBuffer valueBytes = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset() + keyHashSize, valueSize);
writer.writeHash(keyHash, valueBytes);
least.consume();
}
for (StreamBuffer sb : sbs) {
sb.close();
}
writer.close();
}
#location 70
#vulnerability type RESOURCE_LEAK | #fixed code
public void merge(final CueballFilePath base,
final List<CueballFilePath> deltas,
final String newBasePath,
final int keyHashSize,
final int valueSize,
ValueTransformer transformer,
int hashIndexBits,
CompressionCodec compressionCodec) throws IOException {
// Perform merging
CueballStreamBuffer[] sbs = new CueballStreamBuffer[deltas.size() + 1];
// open the current base
CueballStreamBuffer baseBuffer = new CueballStreamBuffer(base.getPath(), 0,
keyHashSize, valueSize, hashIndexBits, compressionCodec);
sbs[0] = baseBuffer;
// open all the deltas
int i = 1;
for (CueballFilePath delta : deltas) {
CueballStreamBuffer db = new CueballStreamBuffer(delta.getPath(), i,
keyHashSize, valueSize, hashIndexBits, compressionCodec);
sbs[i++] = db;
}
// output stream for the new base to be written. intentionally unbuffered -
// the writer below will do that on its own.
OutputStream newBaseStream = new FileOutputStream(newBasePath);
// note that we intentionally omit the hasher here, since it will *not* be
// used
CueballWriter writer = new CueballWriter(newBaseStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits);
while (true) {
CueballStreamBuffer least = null;
for (i = 0; i < sbs.length; i++) {
boolean remaining = sbs[i].anyRemaining();
if (remaining) {
if (least == null) {
least = sbs[i];
} else {
int comparison = least.compareTo(sbs[i]);
if (comparison == 0) {
least.consume();
least = sbs[i];
} else if (comparison == 1) {
least = sbs[i];
}
}
}
}
if (least == null) {
break;
}
if (transformer != null) {
transformer.transform(least.getBuffer(), least.getCurrentOffset() + keyHashSize, least.getIndex());
}
final ByteBuffer keyHash = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset(), keyHashSize);
final ByteBuffer valueBytes = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset() + keyHashSize, valueSize);
writer.writeHash(keyHash, valueBytes);
least.consume();
}
for (CueballStreamBuffer sb : sbs) {
sb.close();
}
writer.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException {
LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " starting.");
boolean claimedRingGroupConductor = false;
try {
ringGroup = coordinator.getRingGroup(ringGroupName);
// attempt to claim the ring group conductor title
if (ringGroup.claimRingGroupConductor()) {
claimedRingGroupConductor = true;
// we are now *the* ring group conductor for this ring group.
domainGroup = ringGroup.getDomainGroup();
// set a watch on the ring group
ringGroup.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
goingDown = false;
try {
while (!goingDown) {
// take a snapshot of the current ring/domain group configs, since
// they might get changed while we're processing the current update.
RingGroup snapshotRingGroup;
DomainGroup snapshotDomainGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
snapshotDomainGroup = domainGroup;
}
processUpdates(snapshotRingGroup, snapshotDomainGroup);
Thread.sleep(configurator.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
if (claimedRingGroupConductor) {
ringGroup.releaseRingGroupConductor();
}
}
LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " shutting down.");
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() throws IOException {
LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " starting.");
boolean claimedRingGroupConductor = false;
try {
ringGroup = coordinator.getRingGroup(ringGroupName);
// attempt to claim the ring group conductor title
if (ringGroup.claimRingGroupConductor()) {
claimedRingGroupConductor = true;
// we are now *the* ring group conductor for this ring group.
domainGroup = ringGroup.getDomainGroup();
// set a watch on the ring group
ringGroup.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
stopping = false;
try {
while (!stopping) {
// take a snapshot of the current ring/domain group configs, since
// they might get changed while we're processing the current update.
RingGroup snapshotRingGroup;
DomainGroup snapshotDomainGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
snapshotDomainGroup = domainGroup;
}
processUpdates(snapshotRingGroup, snapshotDomainGroup);
Thread.sleep(configurator.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
if (claimedRingGroupConductor) {
ringGroup.releaseRingGroupConductor();
}
}
LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " shutting down.");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void updateComplete() throws IOException {
try {
if (zk.exists(ringPath + CURRENT_VERSION_PATH_SEGMENT, false) != null) {
zk.setData(ringPath + CURRENT_VERSION_PATH_SEGMENT, getUpdatingToVersionNumber().toString().getBytes(), -1);
} else {
zk.create(ringPath + CURRENT_VERSION_PATH_SEGMENT, getUpdatingToVersionNumber().toString().getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
zk.delete(ringPath + UPDATING_TO_VERSION_PATH_SEGMENT, -1);
} catch (Exception e) {
throw new IOException(e);
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void updateComplete() throws IOException {
try {
currentVersionNumber.set(getUpdatingToVersionNumber());
updatingToVersionNumber.set(null);
} catch (Exception e) {
throw new IOException(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.