input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
@Override
public Object readFrom(Class<Object> type, Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException {
if (entityStream.markSupported()) {
entityStream.mark(1);
if (entityStream.read() == -1) {
throw new NoContentException(LocalizationMessages.ERROR_JSONB_EMPTYSTREAM());
}
entityStream.reset();
} else {
final PushbackInputStream buffer = new PushbackInputStream(entityStream);
final int firstByte = buffer.read();
if (firstByte == -1) {
throw new NoContentException(LocalizationMessages.ERROR_JSONB_EMPTYSTREAM());
}
buffer.unread(firstByte);
entityStream = buffer;
}
Jsonb jsonb = getJsonb(type);
try {
return jsonb.fromJson(entityStream, genericType);
} catch (JsonbException e) {
throw new ProcessingException(LocalizationMessages.ERROR_JSONB_DESERIALIZATION(), e);
}
}
#location 28
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public Object readFrom(Class<Object> type, Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, String> httpHeaders,
InputStream entityStream) throws IOException, WebApplicationException {
final EntityInputStream entityInputStream = new EntityInputStream(entityStream);
entityStream = entityInputStream;
if (entityInputStream.isEmpty()) {
throw new NoContentException(LocalizationMessages.ERROR_JSONB_EMPTYSTREAM());
}
Jsonb jsonb = getJsonb(type);
try {
return jsonb.fromJson(entityStream, genericType);
} catch (JsonbException e) {
throw new ProcessingException(LocalizationMessages.ERROR_JSONB_DESERIALIZATION(), e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
RowBounds rowBounds = (RowBounds) args[2];
ResultHandler resultHandler = (ResultHandler) args[3];
Executor executor = (Executor) invocation.getTarget();
CacheKey cacheKey;
BoundSql boundSql;
//由于逻辑关系,只会进入一次
if(args.length == 4){
//4 个参数时
boundSql = ms.getBoundSql(parameter);
cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
} else {
//6 个参数时
cacheKey = (CacheKey) args[4];
boundSql = (BoundSql) args[5];
}
// Spring bean 方式配置时,如果没有配置属性就不会执行下面的 setProperties 方法,就不会初始化
// 因此这里会出现 null 的情况 fixed #26
if(dialect == null){
synchronized (default_dialect_class){
if(dialect == null){
setProperties(new Properties());
}
}
}
List resultList;
//调用方法判断是否需要进行分页,如果不需要,直接返回结果
if (!dialect.skip(ms, parameter, rowBounds)) {
//反射获取动态参数
String msId = ms.getId();
Configuration configuration = ms.getConfiguration();
Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql);
//判断是否需要进行 count 查询
if (dialect.beforeCount(ms, parameter, rowBounds)) {
String countMsId = msId + countSuffix;
Long count;
//先判断是否存在手写的 count 查询
MappedStatement countMs = getExistedMappedStatement(configuration, countMsId);
if(countMs != null){
count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler);
} else {
countMs = msCountMap.get(countMsId);
//自动创建
if (countMs == null) {
//根据当前的 ms 创建一个返回值为 Long 类型的 ms
countMs = MSUtils.newCountMappedStatement(ms, countMsId);
msCountMap.put(countMsId, countMs);
}
count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler);
}
//处理查询总数
//返回 true 时继续分页查询,false 时直接返回
if (!dialect.afterCount(count, parameter, rowBounds)) {
//当查询总数为 0 时,直接返回空的结果
return dialect.afterPage(new ArrayList(), parameter, rowBounds);
}
}
//判断是否需要进行分页查询
if (dialect.beforePage(ms, parameter, rowBounds)) {
//生成分页的缓存 key
CacheKey pageKey = cacheKey;
//处理参数对象
parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey);
//调用方言获取分页 sql
String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey);
BoundSql pageBoundSql = new BoundSql(configuration, pageSql, boundSql.getParameterMappings(), parameter);
//设置动态参数
for (String key : additionalParameters.keySet()) {
pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
}
//执行分页查询
resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql);
} else {
//不执行分页的情况下,也不执行内存分页
resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);
}
} else {
//rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页
resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
}
return dialect.afterPage(resultList, parameter, rowBounds);
} finally {
dialect.afterAll();
}
}
#location 38
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
RowBounds rowBounds = (RowBounds) args[2];
ResultHandler resultHandler = (ResultHandler) args[3];
Executor executor = (Executor) invocation.getTarget();
CacheKey cacheKey;
BoundSql boundSql;
//由于逻辑关系,只会进入一次
if (args.length == 4) {
//4 个参数时
boundSql = ms.getBoundSql(parameter);
cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
} else {
//6 个参数时
cacheKey = (CacheKey) args[4];
boundSql = (BoundSql) args[5];
}
checkDialectExists();
List resultList;
//调用方法判断是否需要进行分页,如果不需要,直接返回结果
if (!dialect.skip(ms, parameter, rowBounds)) {
//判断是否需要进行 count 查询
if (dialect.beforeCount(ms, parameter, rowBounds)) {
//查询总数
Long count = count(executor, ms, parameter, rowBounds, resultHandler, boundSql);
//处理查询总数,返回 true 时继续分页查询,false 时直接返回
if (!dialect.afterCount(count, parameter, rowBounds)) {
//当查询总数为 0 时,直接返回空的结果
return dialect.afterPage(new ArrayList(), parameter, rowBounds);
}
}
resultList = ExecutorUtil.pageQuery(dialect, executor,
ms, parameter, rowBounds, resultHandler, boundSql, cacheKey);
} else {
//rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页
resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
}
return dialect.afterPage(resultList, parameter, rowBounds);
} finally {
dialect.afterAll();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
RowBounds rowBounds = (RowBounds) args[2];
ResultHandler resultHandler = (ResultHandler) args[3];
Executor executor = (Executor) invocation.getTarget();
CacheKey cacheKey;
BoundSql boundSql;
//由于逻辑关系,只会进入一次
if(args.length == 4){
//4 个参数时
boundSql = ms.getBoundSql(parameter);
cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
} else {
//6 个参数时
cacheKey = (CacheKey) args[4];
boundSql = (BoundSql) args[5];
}
// Spring bean 方式配置时,如果没有配置属性就不会执行下面的 setProperties 方法,就不会初始化
// 因此这里会出现 null 的情况 fixed #26
if(dialect == null){
synchronized (default_dialect_class){
if(dialect == null){
setProperties(new Properties());
}
}
}
List resultList;
//调用方法判断是否需要进行分页,如果不需要,直接返回结果
if (!dialect.skip(ms, parameter, rowBounds)) {
//反射获取动态参数
String msId = ms.getId();
Configuration configuration = ms.getConfiguration();
Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql);
//判断是否需要进行 count 查询
if (dialect.beforeCount(ms, parameter, rowBounds)) {
String countMsId = msId + countSuffix;
Long count;
//先判断是否存在手写的 count 查询
MappedStatement countMs = getExistedMappedStatement(configuration, countMsId);
if(countMs != null){
count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler);
} else {
countMs = msCountMap.get(countMsId);
//自动创建
if (countMs == null) {
//根据当前的 ms 创建一个返回值为 Long 类型的 ms
countMs = MSUtils.newCountMappedStatement(ms, countMsId);
msCountMap.put(countMsId, countMs);
}
count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler);
}
//处理查询总数
//返回 true 时继续分页查询,false 时直接返回
if (!dialect.afterCount(count, parameter, rowBounds)) {
//当查询总数为 0 时,直接返回空的结果
return dialect.afterPage(new ArrayList(), parameter, rowBounds);
}
}
//判断是否需要进行分页查询
if (dialect.beforePage(ms, parameter, rowBounds)) {
//生成分页的缓存 key
CacheKey pageKey = cacheKey;
//处理参数对象
parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey);
//调用方言获取分页 sql
String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey);
BoundSql pageBoundSql = new BoundSql(configuration, pageSql, boundSql.getParameterMappings(), parameter);
//设置动态参数
for (String key : additionalParameters.keySet()) {
pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
}
//执行分页查询
resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql);
} else {
//不执行分页的情况下,也不执行内存分页
resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);
}
} else {
//rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页
resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
}
return dialect.afterPage(resultList, parameter, rowBounds);
} finally {
dialect.afterAll();
}
}
#location 53
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
RowBounds rowBounds = (RowBounds) args[2];
ResultHandler resultHandler = (ResultHandler) args[3];
Executor executor = (Executor) invocation.getTarget();
CacheKey cacheKey;
BoundSql boundSql;
//由于逻辑关系,只会进入一次
if (args.length == 4) {
//4 个参数时
boundSql = ms.getBoundSql(parameter);
cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
} else {
//6 个参数时
cacheKey = (CacheKey) args[4];
boundSql = (BoundSql) args[5];
}
checkDialectExists();
List resultList;
//调用方法判断是否需要进行分页,如果不需要,直接返回结果
if (!dialect.skip(ms, parameter, rowBounds)) {
//判断是否需要进行 count 查询
if (dialect.beforeCount(ms, parameter, rowBounds)) {
//查询总数
Long count = count(executor, ms, parameter, rowBounds, resultHandler, boundSql);
//处理查询总数,返回 true 时继续分页查询,false 时直接返回
if (!dialect.afterCount(count, parameter, rowBounds)) {
//当查询总数为 0 时,直接返回空的结果
return dialect.afterPage(new ArrayList(), parameter, rowBounds);
}
}
resultList = ExecutorUtil.pageQuery(dialect, executor,
ms, parameter, rowBounds, resultHandler, boundSql, cacheKey);
} else {
//rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页
resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
}
return dialect.afterPage(resultList, parameter, rowBounds);
} finally {
dialect.afterAll();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Object intercept(Invocation invocation) throws Throwable {
SqlUtil sqlUtil;
if (autoRuntimeDialect) {
sqlUtil = getSqlUtil(invocation);
} else {
if (autoDialect) {
initSqlUtil(invocation);
}
sqlUtil = this.sqlUtil;
}
return sqlUtil.processPage(invocation);
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public Object intercept(Invocation invocation) throws Throwable {
if (autoRuntimeDialect) {
SqlUtil sqlUtil = getSqlUtil(invocation);
return sqlUtil.processPage(invocation);
} else {
if (autoDialect) {
initSqlUtil(invocation);
}
return sqlUtil.processPage(invocation);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
RowBounds rowBounds = (RowBounds) args[2];
ResultHandler resultHandler = (ResultHandler) args[3];
Executor executor = (Executor) invocation.getTarget();
CacheKey cacheKey;
BoundSql boundSql;
//由于逻辑关系,只会进入一次
if(args.length == 4){
//4 个参数时
boundSql = ms.getBoundSql(parameter);
cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
} else {
//6 个参数时
cacheKey = (CacheKey) args[4];
boundSql = (BoundSql) args[5];
}
// Spring bean 方式配置时,如果没有配置属性就不会执行下面的 setProperties 方法,就不会初始化
// 因此这里会出现 null 的情况 fixed #26
if(dialect == null){
synchronized (default_dialect_class){
if(dialect == null){
setProperties(new Properties());
}
}
}
List resultList;
//调用方法判断是否需要进行分页,如果不需要,直接返回结果
if (!dialect.skip(ms, parameter, rowBounds)) {
//反射获取动态参数
String msId = ms.getId();
Configuration configuration = ms.getConfiguration();
Map<String, Object> additionalParameters = (Map<String, Object>) additionalParametersField.get(boundSql);
//判断是否需要进行 count 查询
if (dialect.beforeCount(ms, parameter, rowBounds)) {
String countMsId = msId + countSuffix;
Long count;
//先判断是否存在手写的 count 查询
MappedStatement countMs = getExistedMappedStatement(configuration, countMsId);
if(countMs != null){
count = executeManualCount(executor, countMs, parameter, boundSql, resultHandler);
} else {
countMs = msCountMap.get(countMsId);
//自动创建
if (countMs == null) {
//根据当前的 ms 创建一个返回值为 Long 类型的 ms
countMs = MSUtils.newCountMappedStatement(ms, countMsId);
msCountMap.put(countMsId, countMs);
}
count = executeAutoCount(executor, countMs, parameter, boundSql, rowBounds, resultHandler);
}
//处理查询总数
//返回 true 时继续分页查询,false 时直接返回
if (!dialect.afterCount(count, parameter, rowBounds)) {
//当查询总数为 0 时,直接返回空的结果
return dialect.afterPage(new ArrayList(), parameter, rowBounds);
}
}
//判断是否需要进行分页查询
if (dialect.beforePage(ms, parameter, rowBounds)) {
//生成分页的缓存 key
CacheKey pageKey = cacheKey;
//处理参数对象
parameter = dialect.processParameterObject(ms, parameter, boundSql, pageKey);
//调用方言获取分页 sql
String pageSql = dialect.getPageSql(ms, boundSql, parameter, rowBounds, pageKey);
BoundSql pageBoundSql = new BoundSql(configuration, pageSql, boundSql.getParameterMappings(), parameter);
//设置动态参数
for (String key : additionalParameters.keySet()) {
pageBoundSql.setAdditionalParameter(key, additionalParameters.get(key));
}
//执行分页查询
resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, pageKey, pageBoundSql);
} else {
//不执行分页的情况下,也不执行内存分页
resultList = executor.query(ms, parameter, RowBounds.DEFAULT, resultHandler, cacheKey, boundSql);
}
} else {
//rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页
resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
}
return dialect.afterPage(resultList, parameter, rowBounds);
} finally {
dialect.afterAll();
}
}
#location 41
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
RowBounds rowBounds = (RowBounds) args[2];
ResultHandler resultHandler = (ResultHandler) args[3];
Executor executor = (Executor) invocation.getTarget();
CacheKey cacheKey;
BoundSql boundSql;
//由于逻辑关系,只会进入一次
if (args.length == 4) {
//4 个参数时
boundSql = ms.getBoundSql(parameter);
cacheKey = executor.createCacheKey(ms, parameter, rowBounds, boundSql);
} else {
//6 个参数时
cacheKey = (CacheKey) args[4];
boundSql = (BoundSql) args[5];
}
checkDialectExists();
List resultList;
//调用方法判断是否需要进行分页,如果不需要,直接返回结果
if (!dialect.skip(ms, parameter, rowBounds)) {
//判断是否需要进行 count 查询
if (dialect.beforeCount(ms, parameter, rowBounds)) {
//查询总数
Long count = count(executor, ms, parameter, rowBounds, resultHandler, boundSql);
//处理查询总数,返回 true 时继续分页查询,false 时直接返回
if (!dialect.afterCount(count, parameter, rowBounds)) {
//当查询总数为 0 时,直接返回空的结果
return dialect.afterPage(new ArrayList(), parameter, rowBounds);
}
}
resultList = ExecutorUtil.pageQuery(dialect, executor,
ms, parameter, rowBounds, resultHandler, boundSql, cacheKey);
} else {
//rowBounds用参数值,不使用分页插件处理时,仍然支持默认的内存分页
resultList = executor.query(ms, parameter, rowBounds, resultHandler, cacheKey, boundSql);
}
return dialect.afterPage(resultList, parameter, rowBounds);
} finally {
dialect.afterAll();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void setProperties(Properties properties) {
//缓存 count ms
msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties);
String dialectClass = properties.getProperty("dialect");
if (StringUtil.isEmpty(dialectClass)) {
dialectClass = default_dialect_class;
}
try {
Class<?> aClass = Class.forName(dialectClass);
dialect = (Dialect) aClass.newInstance();
} catch (Exception e) {
throw new PageException(e);
}
dialect.setProperties(properties);
String countSuffix = properties.getProperty("countSuffix");
if (StringUtil.isNotEmpty(countSuffix)) {
this.countSuffix = countSuffix;
}
try {
//反射获取 BoundSql 中的 additionalParameters 属性
additionalParametersField = BoundSql.class.getDeclaredField("additionalParameters");
additionalParametersField.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new PageException(e);
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void setProperties(Properties properties) {
//缓存 count ms
msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties);
String dialectClass = properties.getProperty("dialect");
if (StringUtil.isEmpty(dialectClass)) {
dialectClass = default_dialect_class;
}
try {
Class<?> aClass = Class.forName(dialectClass);
dialect = (Dialect) aClass.newInstance();
} catch (Exception e) {
throw new PageException(e);
}
dialect.setProperties(properties);
String countSuffix = properties.getProperty("countSuffix");
if (StringUtil.isNotEmpty(countSuffix)) {
this.countSuffix = countSuffix;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void setProperties(Properties properties) {
//缓存 count ms
msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties);
String dialectClass = properties.getProperty("dialect");
if (StringUtil.isEmpty(dialectClass)) {
dialectClass = default_dialect_class;
}
try {
Class<?> aClass = Class.forName(dialectClass);
dialect = (Dialect) aClass.newInstance();
} catch (Exception e) {
throw new PageException(e);
}
dialect.setProperties(properties);
String countSuffix = properties.getProperty("countSuffix");
if (StringUtil.isNotEmpty(countSuffix)) {
this.countSuffix = countSuffix;
}
try {
//反射获取 BoundSql 中的 additionalParameters 属性
additionalParametersField = BoundSql.class.getDeclaredField("additionalParameters");
additionalParametersField.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new PageException(e);
}
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void setProperties(Properties properties) {
//缓存 count ms
msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties);
String dialectClass = properties.getProperty("dialect");
if (StringUtil.isEmpty(dialectClass)) {
dialectClass = default_dialect_class;
}
try {
Class<?> aClass = Class.forName(dialectClass);
dialect = (Dialect) aClass.newInstance();
} catch (Exception e) {
throw new PageException(e);
}
dialect.setProperties(properties);
String countSuffix = properties.getProperty("countSuffix");
if (StringUtil.isNotEmpty(countSuffix)) {
this.countSuffix = countSuffix;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void setProperties(Properties properties) {
//缓存 count ms
msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties);
String dialectClass = properties.getProperty("dialect");
if (StringUtil.isEmpty(dialectClass)) {
dialectClass = default_dialect_class;
}
try {
Class<?> aClass = Class.forName(dialectClass);
dialect = (Dialect) aClass.newInstance();
} catch (Exception e) {
throw new PageException(e);
}
dialect.setProperties(properties);
String countSuffix = properties.getProperty("countSuffix");
if (StringUtil.isNotEmpty(countSuffix)) {
this.countSuffix = countSuffix;
}
try {
//反射获取 BoundSql 中的 additionalParameters 属性
additionalParametersField = BoundSql.class.getDeclaredField("additionalParameters");
additionalParametersField.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new PageException(e);
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void setProperties(Properties properties) {
//缓存 count ms
msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties);
String dialectClass = properties.getProperty("dialect");
if (StringUtil.isEmpty(dialectClass)) {
dialectClass = default_dialect_class;
}
try {
Class<?> aClass = Class.forName(dialectClass);
dialect = (Dialect) aClass.newInstance();
} catch (Exception e) {
throw new PageException(e);
}
dialect.setProperties(properties);
String countSuffix = properties.getProperty("countSuffix");
if (StringUtil.isNotEmpty(countSuffix)) {
this.countSuffix = countSuffix;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void setProperties(Properties properties) {
//缓存 count ms
msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties);
String dialectClass = properties.getProperty("dialect");
if (StringUtil.isEmpty(dialectClass)) {
dialectClass = default_dialect_class;
}
try {
Class<?> aClass = Class.forName(dialectClass);
dialect = (Dialect) aClass.newInstance();
} catch (Exception e) {
throw new PageException(e);
}
dialect.setProperties(properties);
String countSuffix = properties.getProperty("countSuffix");
if (StringUtil.isNotEmpty(countSuffix)) {
this.countSuffix = countSuffix;
}
try {
//反射获取 BoundSql 中的 additionalParameters 属性
additionalParametersField = BoundSql.class.getDeclaredField("additionalParameters");
additionalParametersField.setAccessible(true);
} catch (NoSuchFieldException e) {
throw new PageException(e);
}
}
#location 24
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void setProperties(Properties properties) {
//缓存 count ms
msCountMap = CacheFactory.createCache(properties.getProperty("msCountCache"), "ms", properties);
String dialectClass = properties.getProperty("dialect");
if (StringUtil.isEmpty(dialectClass)) {
dialectClass = default_dialect_class;
}
try {
Class<?> aClass = Class.forName(dialectClass);
dialect = (Dialect) aClass.newInstance();
} catch (Exception e) {
throw new PageException(e);
}
dialect.setProperties(properties);
String countSuffix = properties.getProperty("countSuffix");
if (StringUtil.isNotEmpty(countSuffix)) {
this.countSuffix = countSuffix;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public String getUrl(DataSource dataSource){
Connection conn = null;
try {
conn = dataSource.getConnection();
return conn.getMetaData().getURL();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if(conn != null){
try {
if(sqlUtil.isCloseConn()){
conn.close();
}
} catch (SQLException e) {
//ignore
}
}
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public String getUrl(DataSource dataSource){
Connection conn = null;
try {
conn = dataSource.getConnection();
return conn.getMetaData().getURL();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if(conn != null){
try {
if(closeConn){
conn.close();
}
} catch (SQLException e) {
//ignore
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void verifyArchivedNotContainingItself(WorkflowRun run) throws IOException {
assertTrue("Build should have artifacts", run.getHasArtifacts());
Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0);
VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath);
ZipInputStream zip = new ZipInputStream(file.open());
for(ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
assertNotEquals("The zip output file shouldn't contain itself", entry.getName(), artifact.getFileName());
}
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
private void verifyArchivedNotContainingItself(WorkflowRun run) throws IOException {
assertTrue("Build should have artifacts", run.getHasArtifacts());
Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0);
VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath);
try (ZipInputStream zip = new ZipInputStream(file.open())) {
for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
assertNotEquals("The zip output file shouldn't contain itself", entry.getName(), artifact.getFileName());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void canArchiveFileWithSameName() throws Exception {
WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"node {\n" +
" dir ('src') {\n" +
" writeFile file: 'hello.txt', text: 'Hello world'\n" +
" writeFile file: 'output.zip', text: 'not really a zip'\n" +
" }\n" +
" dir ('out') {\n" +
" zip zipFile: 'output.zip', dir: '../src', glob: '', archive: true\n" +
" }\n" +
"}\n",
true));
WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
j.assertLogContains("Writing zip file", run);
assertTrue("Build should have artifacts", run.getHasArtifacts());
Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0);
assertEquals("output.zip", artifact.getFileName());
VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath);
ZipInputStream zip = new ZipInputStream(file.open());
ZipEntry entry = zip.getNextEntry();
while (entry != null && !entry.getName().equals("output.zip")) {
System.out.println("zip entry name is: " + entry.getName());
entry = zip.getNextEntry();
}
assertNotNull("output.zip should be included in the zip", entry);
// we should have the the zip - but double check
assertEquals("output.zip", entry.getName());
Scanner scanner = new Scanner(zip);
assertTrue(scanner.hasNextLine());
// the file that was not a zip should be included.
assertEquals("not really a zip", scanner.nextLine());
zip.close();
}
#location 28
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void canArchiveFileWithSameName() throws Exception {
WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
p.setDefinition(new CpsFlowDefinition(
"node {\n" +
" dir ('src') {\n" +
" writeFile file: 'hello.txt', text: 'Hello world'\n" +
" writeFile file: 'output.zip', text: 'not really a zip'\n" +
" }\n" +
" dir ('out') {\n" +
" zip zipFile: 'output.zip', dir: '../src', glob: '', archive: true\n" +
" }\n" +
"}\n",
true));
WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
j.assertLogContains("Writing zip file", run);
assertTrue("Build should have artifacts", run.getHasArtifacts());
Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0);
assertEquals("output.zip", artifact.getFileName());
VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath);
try (ZipInputStream zip = new ZipInputStream(file.open())) {
ZipEntry entry = zip.getNextEntry();
while (entry != null && !entry.getName().equals("output.zip")) {
System.out.println("zip entry name is: " + entry.getName());
entry = zip.getNextEntry();
}
assertNotNull("output.zip should be included in the zip", entry);
// we should have the the zip - but double check
assertEquals("output.zip", entry.getName());
Scanner scanner = new Scanner(zip);
assertTrue(scanner.hasNextLine());
// the file that was not a zip should be included.
assertEquals("not really a zip", scanner.nextLine());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void verifyArchivedHello(WorkflowRun run, String basePath) throws IOException {
assertTrue("Build should have artifacts", run.getHasArtifacts());
Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0);
assertEquals("hello.zip", artifact.getFileName());
VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath);
ZipInputStream zip = new ZipInputStream(file.open());
ZipEntry entry = zip.getNextEntry();
while (entry.isDirectory()) {
entry = zip.getNextEntry();
}
assertNotNull(entry);
assertEquals(basePath + "hello.txt", entry.getName());
try(Scanner scanner = new Scanner(zip)){
assertTrue(scanner.hasNextLine());
assertEquals("Hello World!", scanner.nextLine());
assertNull("There should be no more entries", zip.getNextEntry());
zip.close();
}
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
private void verifyArchivedHello(WorkflowRun run, String basePath) throws IOException {
assertTrue("Build should have artifacts", run.getHasArtifacts());
Run<WorkflowJob, WorkflowRun>.Artifact artifact = run.getArtifacts().get(0);
assertEquals("hello.zip", artifact.getFileName());
VirtualFile file = run.getArtifactManager().root().child(artifact.relativePath);
try (ZipInputStream zip = new ZipInputStream(file.open())) {
ZipEntry entry = zip.getNextEntry();
while (entry.isDirectory()) {
entry = zip.getNextEntry();
}
assertNotNull(entry);
assertEquals(basePath + "hello.txt", entry.getName());
try (Scanner scanner = new Scanner(zip)) {
assertTrue(scanner.hasNextLine());
assertEquals("Hello World!", scanner.nextLine());
assertNull("There should be no more entries", zip.getNextEntry());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String slurp(String fileName) throws IOException {
URL fileUrl = this.getClass().getResource(fileName);
File file = new File(URLDecoder.decode(fileUrl.getFile(), "UTF-8"));
FileReader in = new FileReader(file);
StringBuffer sb = new StringBuffer();
int ch;
while ((ch = in.read()) != -1) {
sb.append((char) ch);
}
return sb.toString();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
private String slurp(String fileName) throws IOException {
URL fileUrl = this.getClass().getResource(fileName);
File file = new File(URLDecoder.decode(fileUrl.getFile(), "UTF-8"));
BufferedReader in = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
sb.append(line).append("\n");
}
in.close();
return sb.toString();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String slurp(String fileName) throws IOException {
URL fileUrl = this.getClass().getResource(fileName);
File file = new File(URLDecoder.decode(fileUrl.getFile(), "UTF-8"));
FileReader in = new FileReader(file);
StringBuffer sb = new StringBuffer();
int ch;
while ((ch = in.read()) != -1) {
sb.append((char) ch);
}
return sb.toString();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
private String slurp(String fileName) throws IOException {
URL fileUrl = this.getClass().getResource(fileName);
File file = new File(URLDecoder.decode(fileUrl.getFile(), "UTF-8"));
BufferedReader in = new BufferedReader(new FileReader(file));
StringBuilder sb = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
sb.append(line).append("\n");
}
in.close();
return sb.toString();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void calcRemainingQuota(Long quota, Long refreshInterval,
Long requestTime, String key, Rate rate) {
if (quota != null) {
String quotaKey = key + QUOTA_SUFFIX;
handleExpiration(quotaKey, refreshInterval, rate);
long usage = requestTime != null ? requestTime : 0L;
Long current = 0L;
try {
current = this.redisTemplate.boundValueOps(quotaKey).increment(usage);
} catch (RuntimeException e) {
String msg = "Failed retrieving rate for " + quotaKey + ", will return quota limit";
rateLimiterErrorHandler.handleError(msg, e);
}
rate.setRemainingQuota(Math.max(-1, quota - current));
}
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected void calcRemainingQuota(Long quota, Long refreshInterval,
Long requestTime, String key, Rate rate) {
if (Objects.nonNull(quota)) {
String quotaKey = key + QUOTA_SUFFIX;
long usage = requestTime != null ? requestTime : 0L;
Long remaining = calcRemaining(quota, refreshInterval, usage, quotaKey, rate);
rate.setRemainingQuota(remaining);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private Long getRequestStartTime() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
return (Long) requestAttributes.getAttribute(REQUEST_START_TIME, SCOPE_REQUEST);
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
private Long getRequestStartTime() {
final RequestContext ctx = RequestContext.getCurrentContext();
final HttpServletRequest request = ctx.getRequest();
return (Long) request.getAttribute(REQUEST_START_TIME);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private Long calcRemaining(Long limit, Long refreshInterval, long usage,
String key, Rate rate) {
rate.setReset(SECONDS.toMillis(refreshInterval));
Long current = 0L;
try {
current = redisTemplate.opsForValue().increment(key, usage);
// Redis returns the value of key after the increment, check for the first increment, and the expiration time is set
if (current != null && current.equals(usage)) {
handleExpiration(key, refreshInterval);
}
} catch (RuntimeException e) {
String msg = "Failed retrieving rate for " + key + ", will return the current value";
rateLimiterErrorHandler.handleError(msg, e);
}
return Math.max(-1, limit - current);
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
private Long calcRemaining(Long limit, Long refreshInterval, long usage,
String key, Rate rate) {
rate.setReset(SECONDS.toMillis(refreshInterval));
Long current = 0L;
try {
current = redisTemplate.opsForValue().increment(key, usage);
// Redis returns the value of key after the increment, check for the first increment, and the expiration time is set
if (current != null && current.equals(usage)) {
handleExpiration(key, refreshInterval);
}
} catch (RuntimeException e) {
String msg = "Failed retrieving rate for " + key + ", will return the current value";
rateLimiterErrorHandler.handleError(msg, e);
}
return Math.max(-1, limit - (current != null ? current : 0L));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void calcRemainingLimit(Long limit, Long refreshInterval,
Long requestTime, String key, Rate rate) {
if (limit != null) {
long usage = requestTime == null ? 1L : 0L;
Long current = 0L;
try {
current = redisTemplate.opsForValue().increment(key, usage);
// Redis returns 1 when the key is incremented for the first time, and the expiration time is set
if (current != null && current.equals(1L)) {
this.redisTemplate.expire(key, refreshInterval, SECONDS);
}
} catch (RuntimeException e) {
String msg = "Failed retrieving rate for " + key + ", will return limit";
rateLimiterErrorHandler.handleError(msg, e);
}
rate.setRemaining(Math.max(-1, limit - current));
}
}
#location 17
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
protected void calcRemainingLimit(Long limit, Long refreshInterval,
Long requestTime, String key, Rate rate) {
if (Objects.nonNull(limit)) {
long usage = requestTime == null ? 1L : 0L;
Long remaining = calcRemaining(limit, refreshInterval, usage, key, rate);
rate.setRemaining(remaining);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void readCharacterProperty(String charDef) throws IOException {
try (InputStream input = (charDef == null) ? openFromJar("char.def") : new FileInputStream(charDef);
InputStreamReader isReader = new InputStreamReader(input, StandardCharsets.UTF_8);
LineNumberReader reader = new LineNumberReader(isReader)) {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
if (line.matches("\\s*") || line.startsWith("#")) {
continue;
}
String[] cols = line.split("\\s+");
if (cols.length < 2) {
throw new IllegalArgumentException("invalid format at line " + reader.getLineNumber());
}
if (cols[0].startsWith("0x")) {
continue;
}
CategoryType type = CategoryType.valueOf(cols[0]);
if (type == null) {
throw new IllegalArgumentException(cols[0] + " is invalid type at line " + reader.getLineNumber());
}
if (categories.containsKey(type)) {
throw new IllegalArgumentException(
cols[0] + " is already defined at line " + reader.getLineNumber());
}
CategoryInfo info = new CategoryInfo();
info.type = type;
info.isInvoke = (!cols[1].equals("0"));
info.isGroup = (!cols[2].equals("0"));
info.length = Integer.parseInt(cols[3]);
categories.put(type, info);
}
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
LatticeNode getOOVNode(String text, OOV oov, int length) {
LatticeNode node = createNode();
node.setParameter(oov.leftId, oov.rightId, oov.cost);
WordInfo info = new WordInfo(text, (short) length, oov.posId, text, text, "");
node.setWordInfo(info);
return node;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void buildLexicon(String filename, FileInputStream lexiconInput) throws IOException {
int lineno = -1;
try (InputStreamReader isr = new InputStreamReader(lexiconInput);
LineNumberReader reader = new LineNumberReader(isr)) {
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
lineno = reader.getLineNumber();
WordEntry entry = parseLine(line);
if (entry.headword != null) {
addToTrie(entry.headword, wordInfos.size());
}
params.add(entry.parameters);
wordInfos.add(entry.wordInfo);
}
} catch (Exception e) {
if (lineno > 0) {
System.err.println("Error: " + e.getMessage() + " at line " + lineno + " in " + filename);
}
throw e;
}
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
DictionaryBuilder() {
buffer = ByteBuffer.allocate(BUFFER_SIZE);
buffer.order(ByteOrder.LITTLE_ENDIAN);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws IOException {
FileInputStream lexiconInput = new FileInputStream(args[0]);
FileInputStream matrixInput = new FileInputStream(args[1]);
FileOutputStream output = new FileOutputStream(args[2]);
DictionaryBuilder builder = new DictionaryBuilder();
builder.build(lexiconInput, matrixInput, output);
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws IOException {
try (FileInputStream lexiconInput = new FileInputStream(args[0]);
FileInputStream matrixInput = new FileInputStream(args[1]);
FileOutputStream output = new FileOutputStream(args[2])) {
DictionaryBuilder builder = new DictionaryBuilder();
builder.build(lexiconInput, matrixInput, output);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void readOOV(String unkDef, Grammar grammar) throws IOException {
try (InputStream input = (unkDef == null) ? openFromJar("unk.def") : new FileInputStream(unkDef);
InputStreamReader isReader = new InputStreamReader(input, StandardCharsets.UTF_8);
LineNumberReader reader = new LineNumberReader(isReader)) {
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
String[] cols = line.split(",");
if (cols.length < 10) {
throw new IllegalArgumentException("invalid format at line " + reader.getLineNumber());
}
CategoryType type = CategoryType.valueOf(cols[0]);
if (type == null) {
throw new IllegalArgumentException(cols[0] + " is invalid type at line " + reader.getLineNumber());
}
if (!categories.containsKey(type)) {
throw new IllegalArgumentException(cols[0] + " is undefined at line " + reader.getLineNumber());
}
OOV oov = new OOV();
oov.leftId = Short.parseShort(cols[1]);
oov.rightId = Short.parseShort(cols[2]);
oov.cost = Short.parseShort(cols[3]);
List<String> pos = Arrays.asList(cols[4], cols[5], cols[6], cols[7], cols[8], cols[9]);
oov.posId = grammar.getPartOfSpeechId(pos);
if (!oovList.containsKey(type)) {
oovList.put(type, new ArrayList<OOV>());
}
oovList.get(type).add(oov);
}
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
LatticeNode getOOVNode(String text, OOV oov, int length) {
LatticeNode node = createNode();
node.setParameter(oov.leftId, oov.rightId, oov.cost);
WordInfo info = new WordInfo(text, (short) length, oov.posId, text, text, "");
node.setWordInfo(info);
return node;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws IOException {
FileInputStream lexiconInput = new FileInputStream(args[0]);
FileInputStream matrixInput = new FileInputStream(args[1]);
FileOutputStream output = new FileOutputStream(args[2]);
DictionaryBuilder builder = new DictionaryBuilder();
builder.build(lexiconInput, matrixInput, output);
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws IOException {
try (FileInputStream lexiconInput = new FileInputStream(args[0]);
FileInputStream matrixInput = new FileInputStream(args[1]);
FileOutputStream output = new FileOutputStream(args[2])) {
DictionaryBuilder builder = new DictionaryBuilder();
builder.build(lexiconInput, matrixInput, output);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 44
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
long bufferedDataAmount() {
return bufferQueueTotalAmount;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void handleRead() throws IOException {
if( !socketBuffer.hasRemaining() ) {
socketBuffer.rewind();
socketBuffer.limit( socketBuffer.capacity() );
if( sockchannel.read( socketBuffer ) == -1 ) {
if( draft == null ) {
closeConnection( CloseFrame.ABNROMAL_CLOSE, true );
} else if( draft.getCloseHandshakeType() == CloseHandshakeType.NONE ) {
closeConnection( CloseFrame.NORMAL, true );
} else if( draft.getCloseHandshakeType() == CloseHandshakeType.ONEWAY ) {
if( role == Role.SERVER )
closeConnection( CloseFrame.ABNROMAL_CLOSE, true );
else
closeConnection( CloseFrame.NORMAL, true );
} else {
closeConnection( CloseFrame.ABNROMAL_CLOSE, true );
}
}
socketBuffer.flip();
}
if( socketBuffer.hasRemaining() ) {
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( !handshakeComplete ) {
if( draft == null ) {
HandshakeState isflashedgecase = isFlashEdgeCase( socketBuffer );
if( isflashedgecase == HandshakeState.MATCHED ) {
channelWriteDirect( ByteBuffer.wrap( Charsetfunctions.utf8Bytes( wsl.getFlashPolicy( this ) ) ) );
closeDirect( CloseFrame.FLASHPOLICY, "" );
return;
} else if( isflashedgecase == HandshakeState.MATCHING ) {
return;
}
}
HandshakeState handshakestate = null;
socketBuffer.mark();
try {
if( role == Role.SERVER ) {
if( draft == null ) {
for( Draft d : known_drafts ) {
try {
d.setParseMode( role );
socketBuffer.reset();
Handshakedata tmphandshake = d.translateHandshake( socketBuffer );
if( tmphandshake instanceof ClientHandshake == false ) {
closeConnection( CloseFrame.PROTOCOL_ERROR, "wrong http function", false );
return;
}
ClientHandshake handshake = (ClientHandshake) tmphandshake;
handshakestate = d.acceptHandshakeAsServer( handshake );
if( handshakestate == HandshakeState.MATCHED ) {
ServerHandshakeBuilder response;
try {
response = wsl.onWebsocketHandshakeReceivedAsServer( this, d, handshake );
} catch ( InvalidDataException e ) {
closeConnection( e.getCloseCode(), e.getMessage(), false );
return;
}
writeDirect( d.createHandshake( d.postProcessHandshakeResponseAsServer( handshake, response ), role ) );
draft = d;
open( handshake );
handleRead();
return;
} else if( handshakestate == HandshakeState.MATCHING ) {
if( draft != null ) {
throw new InvalidHandshakeException( "multible drafts matching" );
}
draft = d;
}
} catch ( InvalidHandshakeException e ) {
// go on with an other draft
} catch ( IncompleteHandshakeException e ) {
if( socketBuffer.limit() == socketBuffer.capacity() ) {
close( CloseFrame.TOOBIG, "handshake is to big" );
}
// read more bytes for the handshake
socketBuffer.position( socketBuffer.limit() );
socketBuffer.limit( socketBuffer.capacity() );
return;
}
}
if( draft == null ) {
close( CloseFrame.PROTOCOL_ERROR, "no draft matches" );
}
return;
} else {
// special case for multiple step handshakes
Handshakedata tmphandshake = draft.translateHandshake( socketBuffer );
if( tmphandshake instanceof ClientHandshake == false ) {
closeConnection( CloseFrame.PROTOCOL_ERROR, "wrong http function", false );
return;
}
ClientHandshake handshake = (ClientHandshake) tmphandshake;
handshakestate = draft.acceptHandshakeAsServer( handshake );
if( handshakestate == HandshakeState.MATCHED ) {
open( handshake );
handleRead();
} else if( handshakestate != HandshakeState.MATCHING ) {
close( CloseFrame.PROTOCOL_ERROR, "the handshake did finaly not match" );
}
return;
}
} else if( role == Role.CLIENT ) {
draft.setParseMode( role );
Handshakedata tmphandshake = draft.translateHandshake( socketBuffer );
if( tmphandshake instanceof ServerHandshake == false ) {
closeConnection( CloseFrame.PROTOCOL_ERROR, "Wwrong http function", false );
return;
}
ServerHandshake handshake = (ServerHandshake) tmphandshake;
handshakestate = draft.acceptHandshakeAsClient( handshakerequest, handshake );
if( handshakestate == HandshakeState.MATCHED ) {
try {
wsl.onWebsocketHandshakeReceivedAsClient( this, handshakerequest, handshake );
} catch ( InvalidDataException e ) {
closeConnection( e.getCloseCode(), e.getMessage(), false );
return;
}
open( handshake );
handleRead();
} else if( handshakestate == HandshakeState.MATCHING ) {
return;
} else {
close( CloseFrame.PROTOCOL_ERROR, "draft " + draft + " refuses handshake" );
}
}
} catch ( InvalidHandshakeException e ) {
close( e );
}
} else {
// Receiving frames
List<Framedata> frames;
try {
frames = draft.translateFrame( socketBuffer );
for( Framedata f : frames ) {
if( DEBUG )
System.out.println( "matched frame: " + f );
Opcode curop = f.getOpcode();
if( curop == Opcode.CLOSING ) {
int code = CloseFrame.NOCODE;
String reason = "";
if( f instanceof CloseFrame ) {
CloseFrame cf = (CloseFrame) f;
code = cf.getCloseCode();
reason = cf.getMessage();
}
if( closeHandshakeSent ) {
// complete the close handshake by disconnecting
closeConnection( code, reason, true );
} else {
// echo close handshake
if( draft.getCloseHandshakeType() == CloseHandshakeType.TWOWAY )
close( code, reason );
closeConnection( code, reason, false );
}
continue;
} else if( curop == Opcode.PING ) {
wsl.onWebsocketPing( this, f );
continue;
} else if( curop == Opcode.PONG ) {
wsl.onWebsocketPong( this, f );
continue;
} else {
// process non control frames
if( currentframe == null ) {
if( f.getOpcode() == Opcode.CONTINIOUS ) {
throw new InvalidFrameException( "unexpected continious frame" );
} else if( f.isFin() ) {
// receive normal onframe message
deliverMessage( f );
} else {
// remember the frame whose payload is about to be continued
currentframe = f;
}
} else if( f.getOpcode() == Opcode.CONTINIOUS ) {
currentframe.append( f );
if( f.isFin() ) {
deliverMessage( currentframe );
currentframe = null;
}
} else {
throw new InvalidDataException( CloseFrame.PROTOCOL_ERROR, "non control or continious frame expected" );
}
}
}
} catch ( InvalidDataException e1 ) {
wsl.onWebsocketError( this, e1 );
close( e1 );
return;
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || flushandclosestate )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isFlushAndClose() || !socketBuffer.hasRemaining() );
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void decode( ByteBuffer socketBuffer ) {
if( !socketBuffer.hasRemaining() || flushandclosestate )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( readystate == READYSTATE.OPEN ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isFlushAndClose() || !socketBuffer.hasRemaining() );
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void stop() throws IOException {
synchronized ( connections ) {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
}
thread.interrupt();
this.server.close();
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void stop() throws IOException {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
thread.interrupt();
this.server.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 52
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void close() {
if( thread != null ) {
thread.interrupt();
closelock.lock();
try {
if( selector != null )
selector.wakeup();
} finally {
closelock.unlock();
}
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void close() {
if( thread != null ) {
conn.close( CloseFrame.NORMAL );
/*closelock.lock();
try {
if( selector != null )
selector.wakeup();
} finally {
closelock.unlock();
}*/
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
thread = null;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) {
oqueue.add( (WebSocketImpl) conn );// because the ostream will close the channel
selector.wakeup();
try {
synchronized ( connections ) {
if( this.connections.remove( conn ) ) {
onClose( conn, code, reason, remote );
}
}
} finally {
try {
releaseBuffers( conn );
} catch ( InterruptedException e ) {
Thread.currentThread().interrupt();
}
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) {
oqueue.add( (WebSocketImpl) conn );// because the ostream will close the channel
selector.wakeup();
try {
if( removeConnection( conn ) ) {
onClose( conn, code, reason, remote );
}
} finally {
try {
releaseBuffers( conn );
} catch ( InterruptedException e ) {
Thread.currentThread().interrupt();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void stop( int timeout ) throws IOException , InterruptedException {
if( !isclosed.compareAndSet( false, true ) ) { // this also makes sure that no further connections will be added to this.connections
return;
}
List<WebSocket> socketsToClose = null;
// copy the connections in a list (prevent callback deadlocks)
synchronized ( connections ) {
socketsToClose = new ArrayList<WebSocket>( connections );
}
for( WebSocket ws : socketsToClose ) {
ws.close( CloseFrame.GOING_AWAY );
}
synchronized ( this ) {
if( selectorthread != null ) {
if( Thread.currentThread() != selectorthread ) {
}
if( selectorthread != Thread.currentThread() ) {
selectorthread.interrupt();
selectorthread.join();
}
}
if( decoders != null ) {
for( WebSocketWorker w : decoders ) {
w.interrupt();
}
}
if( server != null ) {
server.close();
}
}
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void stop( int timeout ) throws InterruptedException {
if( !isclosed.compareAndSet( false, true ) ) { // this also makes sure that no further connections will be added to this.connections
return;
}
List<WebSocket> socketsToClose = null;
// copy the connections in a list (prevent callback deadlocks)
synchronized ( connections ) {
socketsToClose = new ArrayList<WebSocket>( connections );
}
for( WebSocket ws : socketsToClose ) {
ws.close( CloseFrame.GOING_AWAY );
}
synchronized ( this ) {
if( selectorthread != null ) {
if( Thread.currentThread() != selectorthread ) {
}
if( selectorthread != Thread.currentThread() ) {
if( socketsToClose.size() > 0 )
selectorthread.join( timeout );// isclosed will tell the selectorthread to go down after the last connection was closed
selectorthread.interrupt();// in case the selectorthread did not terminate in time we send the interrupt
selectorthread.join();
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 51
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void close() {
if( thread != null ) {
thread.interrupt();
closelock.lock();
try {
if( selector != null )
selector.wakeup();
} finally {
closelock.unlock();
}
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void close() {
if( thread != null ) {
conn.close( CloseFrame.NORMAL );
/*closelock.lock();
try {
if( selector != null )
selector.wakeup();
} finally {
closelock.unlock();
}*/
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void flush() throws IOException {
ByteBuffer buffer = this.bufferQueue.peek();
while ( buffer != null ) {
sockchannel.write( buffer );
if( buffer.remaining() > 0 ) {
continue;
} else {
synchronized ( bufferQueueTotalAmount ) {
// subtract this amount of data from the total queued (synchronized over this object)
bufferQueueTotalAmount -= buffer.limit();
}
this.bufferQueue.poll(); // Buffer finished. Remove it.
buffer = this.bufferQueue.peek();
}
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void flush() throws IOException {
ByteBuffer buffer = this.bufferQueue.peek();
while ( buffer != null ) {
sockchannel.write( buffer );
if( buffer.remaining() > 0 ) {
continue;
} else {
// subtract this amount of data from the total queued (synchronized over this object)
bufferQueueTotalAmount.addAndGet(-buffer.limit());
this.bufferQueue.poll(); // Buffer finished. Remove it.
buffer = this.bufferQueue.peek();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, client );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
conn.flush();
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && conn.read( buff ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isWritable() ) {
conn.flush();
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
conn.flush();
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
return;
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false );
return;
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
client.close();
} catch ( IOException e ) {
onError( e );
}
client = null;
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
SocketChannelIOHelper.batch( conn, channel );
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.eot( e );
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 52
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public int getConnectionLostTimeout() {
return connectionLostTimeout;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public int getConnectionLostTimeout() {
synchronized (syncConnectionLost) {
return connectionLostTimeout;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, client );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
conn.flush();
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && conn.read( buff ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isWritable() ) {
conn.flush();
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
conn.flush();
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
return;
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false );
return;
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
client.close();
} catch ( IOException e ) {
onError( e );
}
client = null;
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
SocketChannelIOHelper.batch( conn, channel );
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.eot( e );
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void stop() throws IOException , InterruptedException {
synchronized ( connections ) {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
}
selectorthread.interrupt();
selectorthread.join();
for( WebSocketWorker w : decoders ) {
w.interrupt();
}
this.server.close();
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void stop() throws IOException , InterruptedException {
stop( 0 );
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 34
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void start() {
if( thread != null )
throw new IllegalStateException( "Already started" );
new Thread( this ).start();
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void start() {
if( selectorthread != null )
throw new IllegalStateException( "Already started" );
new Thread( this ).start();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, client );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
conn.flush();
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && conn.read( buff ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isWritable() ) {
conn.flush();
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
conn.flush();
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
return;
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false );
return;
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
client.close();
} catch ( IOException e ) {
onError( e );
}
client = null;
}
#location 78
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
SocketChannelIOHelper.batch( conn, channel );
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.eot( e );
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 44
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isClosed() || !socketBuffer.hasRemaining() );
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || connectionClosed )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isClosed() || !socketBuffer.hasRemaining() );
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, client );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
conn.flush();
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && conn.read( buff ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isWritable() ) {
conn.flush();
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
conn.flush();
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
return;
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false );
return;
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
client.close();
} catch ( IOException e ) {
onError( e );
}
client = null;
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
SocketChannelIOHelper.batch( conn, channel );
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.eot( e );
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void stop() throws IOException {
synchronized ( connections ) {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
}
thread.interrupt();
this.server.close();
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void stop() throws IOException {
synchronized ( connections ) {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
}
selectorthread.interrupt();
this.server.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
} catch ( Throwable e ) {
System.out.println( e );
e.printStackTrace();
}
}
}
#location 34
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || connectionClosed )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isClosed() || !socketBuffer.hasRemaining() );
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || flushandclosestate )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isFlushAndClose() || !socketBuffer.hasRemaining() );
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || connectionClosed )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isClosed() || !socketBuffer.hasRemaining() );
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void decode( ByteBuffer socketBuffer ) throws IOException {
if( !socketBuffer.hasRemaining() || flushandclosestate )
return;
if( DEBUG )
System.out.println( "process(" + socketBuffer.remaining() + "): {" + ( socketBuffer.remaining() > 1000 ? "too big to display" : new String( socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining() ) ) + "}" );
if( handshakeComplete ) {
decodeFrames( socketBuffer );
} else {
if( decodeHandshake( socketBuffer ) ) {
decodeFrames( socketBuffer );
}
}
assert ( isClosing() || isFlushAndClose() || !socketBuffer.hasRemaining() );
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
synchronized ( this ) {
if( selectorthread != null )
throw new IllegalStateException( getClass().getName() + " can only be started once." );
selectorthread = Thread.currentThread();
if( isclosed.get() ) {
return;
}
}
selectorthread.setName( "WebsocketSelector" + selectorthread.getId() );
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
ServerSocket socket = server.socket();
socket.setReceiveBufferSize( WebSocket.RCVBUF );
socket.bind( address );
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocketImpl conn = null;
try {
selector.select();
registerWrite();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
if( !key.isValid() ) {
// Object o = key.attachment();
continue;
}
if( key.isAcceptable() ) {
if( !onConnect( key ) ) {
key.cancel();
continue;
}
SocketChannel channel = server.accept();
channel.configureBlocking( false );
WebSocketImpl w = wsf.createWebSocket( this, drafts, channel.socket() );
w.key = channel.register( selector, SelectionKey.OP_READ, w );
w.channel = wsf.wrapChannel( w.key );
i.remove();
allocateBuffers( w );
continue;
}
if( key.isReadable() ) {
conn = (WebSocketImpl) key.attachment();
ByteBuffer buf = takeBuffer();
try {
if( SocketChannelIOHelper.read( buf, conn, (ByteChannel) conn.channel ) ) {
conn.inQueue.put( buf );
queue( conn );
i.remove();
if( conn.channel instanceof WrappedByteChannel ) {
if( ( (WrappedByteChannel) conn.channel ).isNeedRead() ) {
iqueue.add( conn );
}
}
} else {
pushBuffer( buf );
}
} catch ( IOException e ) {
pushBuffer( buf );
throw e;
} catch ( RuntimeException e ) {
pushBuffer( buf );
throw e;
}
}
if( key.isWritable() ) {
conn = (WebSocketImpl) key.attachment();
if( SocketChannelIOHelper.batch( conn, (ByteChannel) conn.channel ) ) {
if( key.isValid() )
key.interestOps( SelectionKey.OP_READ );
}
}
}
while ( !iqueue.isEmpty() ) {
conn = iqueue.remove( 0 );
WrappedByteChannel c = ( (WrappedByteChannel) conn.channel );
ByteBuffer buf = takeBuffer();
if( SocketChannelIOHelper.readMore( buf, conn, c ) )
iqueue.add( conn );
conn.inQueue.put( buf );
queue( conn );
}
} catch ( CancelledKeyException e ) {
// an other thread may cancel the key
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
} catch ( InterruptedException e ) {
return;// FIXME controlled shutdown
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
handleFatal( null, e );
}
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
synchronized ( this ) {
if( selectorthread != null )
throw new IllegalStateException( getClass().getName() + " can only be started once." );
selectorthread = Thread.currentThread();
if( isclosed.get() ) {
return;
}
}
selectorthread.setName( "WebsocketSelector" + selectorthread.getId() );
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
ServerSocket socket = server.socket();
socket.setReceiveBufferSize( WebSocket.RCVBUF );
socket.bind( address );
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocketImpl conn = null;
try {
selector.select();
registerWrite();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
if( !key.isValid() ) {
// Object o = key.attachment();
continue;
}
if( key.isAcceptable() ) {
if( !onConnect( key ) ) {
key.cancel();
continue;
}
SocketChannel channel = server.accept();
channel.configureBlocking( false );
WebSocketImpl w = wsf.createWebSocket( this, drafts, channel.socket() );
w.key = channel.register( selector, SelectionKey.OP_READ, w );
w.channel = wsf.wrapChannel( w.key );
i.remove();
allocateBuffers( w );
continue;
}
if( key.isReadable() ) {
conn = (WebSocketImpl) key.attachment();
ByteBuffer buf = takeBuffer();
try {
if( SocketChannelIOHelper.read( buf, conn, (ByteChannel) conn.channel ) ) {
conn.inQueue.put( buf );
queue( conn );
i.remove();
if( conn.channel instanceof WrappedByteChannel ) {
if( ( (WrappedByteChannel) conn.channel ).isNeedRead() ) {
iqueue.add( conn );
}
}
} else {
pushBuffer( buf );
}
} catch ( IOException e ) {
pushBuffer( buf );
throw e;
} catch ( RuntimeException e ) {
pushBuffer( buf );
throw e;
}
}
if( key.isWritable() ) {
conn = (WebSocketImpl) key.attachment();
if( SocketChannelIOHelper.batch( conn, (ByteChannel) conn.channel ) ) {
if( key.isValid() )
key.interestOps( SelectionKey.OP_READ );
}
}
}
while ( !iqueue.isEmpty() ) {
conn = iqueue.remove( 0 );
WrappedByteChannel c = ( (WrappedByteChannel) conn.channel );
ByteBuffer buf = takeBuffer();
if( SocketChannelIOHelper.readMore( buf, conn, c ) )
iqueue.add( conn );
conn.inQueue.put( buf );
queue( conn );
}
} catch ( CancelledKeyException e ) {
// an other thread may cancel the key
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
} catch ( InterruptedException e ) {
return;// FIXME controlled shutdown
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
handleFatal( null, e );
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void stop() throws IOException , InterruptedException {
synchronized ( connections ) {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
}
selectorthread.interrupt();
selectorthread.join();
for( WebSocketWorker w : decoders ) {
w.interrupt();
}
this.server.close();
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void stop() throws IOException , InterruptedException {
stop( 0 );
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
thread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
while ( !thread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}
}
synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}
} catch ( IOException ex ) {
if( key != null )
key.cancel();
onWebsocketError( conn, ex );// conn may be null here
if( conn != null ) {
conn.close( CloseFrame.ABNROMAL_CLOSE );
}
}
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( selectorthread != null )
throw new IllegalStateException( "This instance of " + getClass().getSimpleName() + " can only be started once the same time." );
selectorthread = Thread.currentThread();
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
server.socket().bind( address );
// InetAddress.getLocalHost()
selector = Selector.open();
server.register( selector, server.validOps() );
} catch ( IOException ex ) {
onWebsocketError( null, ex );
return;
}
try {
while ( !selectorthread.isInterrupted() ) {
SelectionKey key = null;
WebSocket conn = null;
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
SocketChannel client = server.accept();
client.configureBlocking( false );
WebSocket c = new WebSocket( this, Collections.singletonList( draft ), client );
client.register( selector, SelectionKey.OP_READ, c );
}
// if isReadable == true
// then the server is ready to read
if( key.isReadable() ) {
conn = (WebSocket) key.attachment();
asyncQueueRead( conn );
// conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
/*if( key.isValid() && key.isWritable() ) {
conn = (WebSocket) key.attachment();
conn.flush();
key.channel().register( selector, SelectionKey.OP_READ, conn );
}*/
}
/*synchronized ( connections ) {
Iterator<WebSocket> it = this.connections.iterator();
while ( it.hasNext() ) {
// We have to do this check here, and not in the selectorthread that
// adds the buffered data to the WebSocket, because the
// Selector is not selectorthread-safe, and can only be accessed
// by this selectorthread.
conn = it.next();
if( conn.hasBufferedData() ) {
conn.flush();
// key.channel().register( selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn );
}
}
}*/
} catch ( IOException ex ) {
if( key != null )
key.cancel();
handleIOException( conn, ex );
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
onError( null, e );
try {
selector.close();
} catch ( IOException e1 ) {
onError( null, e1 );
}
decoders.shutdown();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public final void onWriteDemand( WebSocket conn ) {
selector.wakeup();
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public final void onWriteDemand( WebSocket conn ) {
try {
conn.flush();
} catch ( IOException e ) {
handleIOException( conn, e );
}
/*synchronized ( write_demands ) {
if( !write_demands.contains( conn ) ) {
write_demands.add( conn );
flusher.submit( new WebsocketWriteTask( conn ) );
}
}*/
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void stop() throws IOException {
synchronized ( connections ) {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
}
thread.interrupt();
this.server.close();
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void stop() throws IOException {
for( WebSocket ws : connections ) {
ws.close( CloseFrame.NORMAL );
}
thread.interrupt();
this.server.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, client );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
conn.flush();
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && conn.read( buff ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isWritable() ) {
conn.flush();
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
conn.flush();
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
return;
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.closeConnection( CloseFrame.BUGGYCLOSE, e.toString(), false );
return;
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
client.close();
} catch ( IOException e ) {
onError( e );
}
client = null;
}
#location 74
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected final void interruptableRun() {
try {
tryToConnect( new InetSocketAddress( uri.getHost(), getPort() ) );
} catch ( ClosedByInterruptException e ) {
onWebsocketError( null, e );
return;
} catch ( IOException e ) {//
onWebsocketError( conn, e );
return;
} catch ( SecurityException e ) {
onWebsocketError( conn, e );
return;
} catch ( UnresolvedAddressException e ) {
onWebsocketError( conn, e );
return;
}
conn = (WebSocketImpl) wf.createWebSocket( this, draft, channel.socket() );
ByteBuffer buff = ByteBuffer.allocate( WebSocket.RCVBUF );
try/*IO*/{
while ( !conn.isClosed() ) {
if( Thread.interrupted() ) {
conn.close( CloseFrame.NORMAL );
}
SelectionKey key = null;
SocketChannelIOHelper.batch( conn, channel );
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
i.remove();
if( key.isReadable() && SocketChannelIOHelper.read( buff, this.conn, channel ) ) {
conn.decode( buff );
}
if( !key.isValid() ) {
continue;
}
if( key.isConnectable() ) {
try {
finishConnect();
} catch ( InterruptedException e ) {
conn.close( CloseFrame.NEVERCONNECTED );// report error to only
break;
} catch ( InvalidHandshakeException e ) {
conn.close( e ); // http error
}
}
}
}
} catch ( IOException e ) {
onError( e );
conn.close( CloseFrame.ABNORMAL_CLOSE );
} catch ( RuntimeException e ) {
// this catch case covers internal errors only and indicates a bug in this websocket implementation
onError( e );
conn.eot( e );
}
try {
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
closelock.lock();
selector = null;
closelock.unlock();
try {
channel.close();
} catch ( IOException e ) {
onError( e );
}
channel = null;
thread = null;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() {
if( thread == null )
thread = Thread.currentThread();
interruptableRun();
assert ( !channel.isOpen() );
try {
if( selector != null ) // if the initialization in <code>tryToConnect</code> fails, it could be null
selector.close();
} catch ( IOException e ) {
onError( e );
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void roundTripWriteAndRead() throws TaskException, IOException {
String str = "ਹਰਜੋਤ ਸਿੰਘ ភាសាខ្មែរ latin ąćęłńóśźż ทดสอบ വീട मानक हिन्दी ് జ উ ☗⦄✸▃ ";
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
new PageTextWriter(doc).write(page, new Point(10, 10), str, getStandardType1Font(StandardType1Font.HELVETICA), 10.0d, Color.BLACK);
doc.addPage(page);
PDDocumentHandler handler = new PDDocumentHandler(doc);
File tmp = IOUtils.createTemporaryPdfBuffer();
handler.savePDDocument(tmp);
PDDocument doc2 = PDFParser.parse(SeekableSources.seekableSourceFrom(tmp));
String text = new PdfTextExtractorByArea().extractTextFromArea(doc2.getPage(0), new Rectangle(0,0, 1000, 1000));
assertEquals(noWhitespace(str), noWhitespace(text));
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void roundTripWriteAndRead() throws TaskException, IOException {
List<String> strings = Arrays.asList("ગુજરાતી ਪੰਜਾਬੀ தமிழ்",
"ਹਰਜੋਤ ਸਿੰਘ ភាសាខ្មែរ latin ąćęłńóśźż ทดสอบ വീട मानक हिन्दी ് జ উ ☗⦄✸▃ ");
for(String str: strings) {
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
new PageTextWriter(doc).write(page, new Point(10, 10), str, getStandardType1Font(StandardType1Font.HELVETICA), 10.0d, Color.BLACK);
doc.addPage(page);
PDDocumentHandler handler = new PDDocumentHandler(doc);
File tmp = IOUtils.createTemporaryPdfBuffer();
handler.savePDDocument(tmp);
PDDocument doc2 = PDFParser.parse(SeekableSources.seekableSourceFrom(tmp));
String text = new PdfTextExtractorByArea().extractTextFromArea(doc2.getPage(0), new Rectangle(0, 0, 1000, 1000));
assertEquals(noWhitespace(str), noWhitespace(text));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public TaskTestContext assertOutputSize(int size) {
requireMultipleOutputs();
assertEquals("An unexpected number of output files has been created", size, fileOutput.listFiles().length);
return this;
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
public TaskTestContext assertOutputSize(int size) {
requireMultipleOutputs();
String[] files = fileOutput.list();
assertEquals("An unexpected number of output files has been created: " + StringUtils.join(files, ","),
size, files.length);
return this;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void mergeNull() {
PDDocument destination = new PDDocument();
AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination);
assertNotNull(document.getDocumentCatalog().getAcroForm());
victim.mergeForm(null, annotationsLookup);
assertFalse(victim.hasForm());
assertNull(destination.getDocumentCatalog().getAcroForm());
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void mergeNull() {
PDDocument destination = new PDDocument();
AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination);
assertNotNull(document.getDocumentCatalog().getAcroForm());
victim.mergeForm(null, annotationsLookup);
assertTrue(victim.getForm().getFields().isEmpty());
assertNull(destination.getDocumentCatalog().getAcroForm());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBasics() throws TaskException, IOException {
parameters.setOutput(new DirectoryTaskOutput(outputFolder));
victim.execute(parameters);
long sizeInKb = outputFolder.listFiles()[0].length() / 1000;
assertThat(sizeInKb, is(lessThan(104L)));
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testBasics() throws TaskException, IOException {
withSource("pdf/unoptimized.pdf");
victim.execute(parameters);
assertThat(sizeOfResult(), is(lessThan(104L)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void canDisplayGeorgian() {
PDFont font = FontUtils.findFontFor(new PDDocument(), "ქართული ენა");
assertNotNull("No font available for Georgian", font);
assertThat(font.getName(), is("NotoSansGeorgian"));
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void canDisplayGeorgian() {
assertNotNull(findFontFor("ქართული ენა"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void extract(PDDocument document, File output) throws TaskException {
if (document == null) {
throw new TaskException("Unable to extract text from a null document.");
}
if (output == null || !output.isFile() || !output.canWrite()) {
throw new TaskException(String.format("Cannot write extracted text to a the given output file '%s'.",
output));
}
try {
outputWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output), encoding));
textStripper.writeText(document, outputWriter);
} catch (IOException e) {
throw new TaskExecutionException("An error occurred extracting text from a pdf source.", e);
}
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
public void extract(PDDocument document, File output) throws TaskException {
if (document == null) {
throw new TaskException("Unable to extract text from a null document.");
}
if (output == null || !output.isFile() || !output.canWrite()) {
throw new TaskException(String.format("Cannot write extracted text to a the given output file '%s'.",
output));
}
try {
outputWriter = Files.newBufferedWriter(output.toPath(), Charset.forName(encoding));
textStripper.writeText(document, outputWriter);
} catch (IOException e) {
throw new TaskExecutionException("An error occurred extracting text from a pdf source.", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void canDisplayGeorgian() {
PDFont font = FontUtils.findFontFor(new PDDocument(), "ქართული ენა");
assertNotNull("No font available for Georgian", font);
assertThat(font.getName(), is("NotoSansGeorgian"));
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void canDisplayGeorgian() {
assertNotNull(findFontFor("ქართული ენა"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static void copyToStreamZipped(Map<String, File> files, OutputStream out) throws IOException {
ZipOutputStream zipOut = new ZipOutputStream(out);
for (Entry<String, File> entry : files.entrySet()) {
FileInputStream input = null;
if (isBlank(entry.getKey())) {
throw new IOException(String.format("Unable to copy %s to the output stream, no output name specified.",
entry.getValue()));
}
try {
input = new FileInputStream(entry.getValue());
zipOut.putNextEntry(new ZipEntry(entry.getKey()));
LOG.debug("Copying {} to zip stream {}.", entry.getValue(), entry.getKey());
IOUtils.copy(input, zipOut);
} finally {
IOUtils.closeQuietly(input);
delete(entry.getValue());
}
}
IOUtils.closeQuietly(zipOut);
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
static void copyToStreamZipped(Map<String, File> files, OutputStream out) throws IOException {
try (ZipOutputStream zipOut = new ZipOutputStream(out)) {
for (Entry<String, File> entry : files.entrySet()) {
if (isBlank(entry.getKey())) {
throw new IOException(String.format(
"Unable to copy %s to the output stream, no output name specified.", entry.getValue()));
}
try (FileInputStream input = new FileInputStream(entry.getValue())) {
zipOut.putNextEntry(new ZipEntry(entry.getKey()));
LOG.debug("Copying {} to zip stream {}.", entry.getValue(), entry.getKey());
IOUtils.copy(input, zipOut);
} finally {
delete(entry.getValue());
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void resolveTextAndFontsWhenTextRepeats() throws TaskIOException {
PageTextWriter writer = new PageTextWriter(new PDDocument());
List<PageTextWriter.TextWithFont> textAndFonts = writer.resolveFonts("123α456α789", helvetica);
assertThat(textAndFonts.get(0).getFont().getName(), is("Helvetica"));
assertThat(textAndFonts.get(0).getText(), is("123"));
assertThat(textAndFonts.get(1).getFont().getName(), is(not("Helvetica")));
assertThat(textAndFonts.get(1).getText(), is("α"));
assertThat(textAndFonts.get(2).getFont().getName(), is("Helvetica"));
assertThat(textAndFonts.get(2).getText(), is("456"));
assertThat(textAndFonts.get(3).getFont().getName(), is(not("Helvetica")));
assertThat(textAndFonts.get(3).getText(), is("α"));
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void resolveTextAndFontsWhenTextRepeats() throws TaskIOException {
write("123α456α789");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void execute(JpegToPdfParameters parameters) throws TaskException {
int currentStep = 0;
documentHandler = new PDDocumentHandler();
documentHandler.setCreatorOnPDDocument();
PageImageWriter imageWriter = new PageImageWriter(documentHandler.getUnderlyingPDDocument());
for (Source<?> source : parameters.getSourceList()) {
executionContext().assertTaskNotCancelled();
currentStep++;
try {
PDImageXObject image = PageImageWriter.toPDXImageObject(source);
PDRectangle mediaBox = PDRectangle.A4;
if (image.getWidth() > image.getHeight() && image.getWidth() > mediaBox.getWidth()) {
mediaBox = new PDRectangle(mediaBox.getHeight(), mediaBox.getWidth());
}
PDPage page = documentHandler.addBlankPage(mediaBox);
// full page (scaled down only)
int width = image.getWidth();
int height = image.getHeight();
if (width > mediaBox.getWidth()) {
int targetWidth = (int) mediaBox.getWidth();
LOG.debug("Scaling image down to fit by width {} vs {}", width, targetWidth);
float ratio = (float) width / targetWidth;
width = targetWidth;
height = Math.round(height / ratio);
}
if (height > mediaBox.getHeight()) {
int targetHeight = (int) mediaBox.getHeight();
LOG.debug("Scaling image down to fit by height {} vs {}", height, targetHeight);
float ratio = (float) height / targetHeight;
height = targetHeight;
width = Math.round(width / ratio);
}
// centered on page
int x = ((int) mediaBox.getWidth() - width) / 2;
int y = ((int) mediaBox.getHeight() - height) / 2;
imageWriter.append(page, image, new Point(x, y), width, height, null, 0);
notifyEvent(executionContext().notifiableTaskMetadata()).stepsCompleted(currentStep).outOf(totalSteps);
} catch (TaskIOException e) {
executionContext().assertTaskIsLenient(e);
notifyEvent(executionContext().notifiableTaskMetadata()).taskWarning(
String.format("Image %s was skipped, could not be processed", source.getName()), e);
}
}
File tmpFile = createTemporaryBuffer(parameters.getOutput());
LOG.debug("Created output on temporary buffer {}", tmpFile);
documentHandler.setVersionOnPDDocument(parameters.getVersion());
documentHandler.setCompress(parameters.isCompress());
documentHandler.savePDDocument(tmpFile);
String outName = nameGenerator(parameters.getOutputPrefix()).generate(nameRequest());
outputWriter.addOutput(file(tmpFile).name(outName));
nullSafeCloseQuietly(documentHandler);
parameters.getOutput().accept(outputWriter);
LOG.debug("Input images written to {}", parameters.getOutput());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public void execute(JpegToPdfParameters parameters) throws TaskException {
final MutableInt currentStep = new MutableInt(0);
ImagesToPdfDocumentConverter converter = new ImagesToPdfDocumentConverter() {
@Override
public void beforeImage(Source<?> source) throws TaskException {
executionContext().assertTaskNotCancelled();
currentStep.increment();
}
@Override
public void afterImage(PDImageXObject image) {
notifyEvent(executionContext().notifiableTaskMetadata()).stepsCompleted(currentStep.getValue()).outOf(totalSteps);
}
@Override
public void failedImage(Source<?> source, TaskIOException e) throws TaskException{
executionContext().assertTaskIsLenient(e);
notifyEvent(executionContext().notifiableTaskMetadata()).taskWarning(
String.format("Image %s was skipped, could not be processed", source.getName()), e);
}
};
documentHandler = converter.convert(parameters.getSourceList());
File tmpFile = createTemporaryBuffer(parameters.getOutput());
LOG.debug("Created output on temporary buffer {}", tmpFile);
documentHandler.setVersionOnPDDocument(parameters.getVersion());
documentHandler.setCompress(parameters.isCompress());
documentHandler.savePDDocument(tmpFile);
String outName = nameGenerator(parameters.getOutputPrefix()).generate(nameRequest());
outputWriter.addOutput(file(tmpFile).name(outName));
nullSafeCloseQuietly(documentHandler);
parameters.getOutput().accept(outputWriter);
LOG.debug("Input images written to {}", parameters.getOutput());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testFindFontFor() {
assertEquals("NotoSansThai", findFontFor(new PDDocument(), "ทดสอบ").getName());
assertEquals("NotoSans", findFontFor(new PDDocument(), "αυτό είναι ένα τεστ").getName());
assertNull(findFontFor(new PDDocument(), "വീട്"));
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testFindFontFor() {
assertNotNull(findFontFor("ทดสอบ")); // thai
assertNotNull(findFontFor("αυτό είναι ένα τεστ")); // greek
assertNotNull(findFontFor("വീട്")); // malayalam
assertNotNull(findFontFor("मानक")); // hindi
assertNotNull(findFontFor("జ")); // telugu
assertNotNull(findFontFor("উ")); // bengali
assertNotNull(findFontFor("עברית")); // hebrew
assertNotNull(findFontFor("简化字")); // simplified chinese
assertNotNull(findFontFor("한국어/조선말")); // korean
assertNotNull(findFontFor("日本語")); // japanese
assertNotNull(findFontFor("latin ąćęłńóśźż")); // latin
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void resolvedSpaceSeparately() throws TaskIOException {
PageTextWriter writer = new PageTextWriter(new PDDocument());
List<PageTextWriter.TextWithFont> textAndFonts = writer.resolveFonts("ab cd", helvetica);
assertThat(textAndFonts.get(0).getFont().getName(), is("Helvetica"));
assertThat(textAndFonts.get(0).getText(), is("ab"));
assertThat(textAndFonts.get(1).getFont().getName(), is("Helvetica"));
assertThat(textAndFonts.get(1).getText(), is(" "));
assertThat(textAndFonts.get(2).getFont().getName(), is("Helvetica"));
assertThat(textAndFonts.get(2).getText(), is("cd"));
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void resolvedSpaceSeparately() throws TaskIOException {
write("ab cd");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static void copyToStreamZipped(Map<String, File> files, OutputStream out) throws IOException {
ZipOutputStream zipOut = new ZipOutputStream(out);
for (Entry<String, File> entry : files.entrySet()) {
FileInputStream input = null;
if (isBlank(entry.getKey())) {
throw new IOException(String.format("Unable to copy %s to the output stream, no output name specified.",
entry.getValue()));
}
try {
input = new FileInputStream(entry.getValue());
zipOut.putNextEntry(new ZipEntry(entry.getKey()));
LOG.debug("Copying {} to zip stream {}.", entry.getValue(), entry.getKey());
IOUtils.copy(input, zipOut);
} finally {
IOUtils.closeQuietly(input);
delete(entry.getValue());
}
}
IOUtils.closeQuietly(zipOut);
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
static void copyToStreamZipped(Map<String, File> files, OutputStream out) throws IOException {
try (ZipOutputStream zipOut = new ZipOutputStream(out)) {
for (Entry<String, File> entry : files.entrySet()) {
if (isBlank(entry.getKey())) {
throw new IOException(String.format(
"Unable to copy %s to the output stream, no output name specified.", entry.getValue()));
}
try (FileInputStream input = new FileInputStream(entry.getValue())) {
zipOut.putNextEntry(new ZipEntry(entry.getKey()));
LOG.debug("Copying {} to zip stream {}.", entry.getValue(), entry.getKey());
IOUtils.copy(input, zipOut);
} finally {
delete(entry.getValue());
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCanDisplayThai() {
PDFont noto = FontUtils.loadFont(new PDDocument(), UnicodeType0Font.NOTO_SANS_THAI_REGULAR);
assertThat(FontUtils.canDisplay("นี่คือการทดสอบ", noto), is(true));
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCanDisplayThai() {
assertThat(findFontFor("นี่คือการทดสอบ"), is(notNullValue()));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void mergeWithSignatureRemovesSignatureValue() throws IOException {
PDDocument destination = new PDDocument();
AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination);
assertNotNull(document.getDocumentCatalog().getAcroForm());
victim.mergeForm(document.getDocumentCatalog().getAcroForm(), annotationsLookup);
mapping.clear();
annotationsLookup.clear();
PDDocument anotherDoc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getClassLoader().getResourceAsStream("pdf/forms/simple_form_with_signature_signed.pdf")));
for (PDPage current : anotherDoc.getPages()) {
mapping.addLookupEntry(current, new PDPage());
annotationsLookup = new AnnotationsDistiller(anotherDoc).retainRelevantAnnotations(mapping);
}
victim.mergeForm(anotherDoc.getDocumentCatalog().getAcroForm(), annotationsLookup);
assertTrue(victim.hasForm());
PDAcroForm form = victim.getForm();
assertNotNull(form);
PDField signature = null;
for (PDField current : form.getFieldTree()) {
if (current.getFieldType() == COSName.SIG.getName()) {
signature = current;
}
}
assertNotNull(signature);
assertEquals("", signature.getValueAsString());
assertTrue(form.isSignaturesExist());
}
#location 28
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void mergeWithSignatureRemovesSignatureValue() throws IOException {
PDDocument destination = new PDDocument();
AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination);
assertNotNull(document.getDocumentCatalog().getAcroForm());
victim.mergeForm(document.getDocumentCatalog().getAcroForm(), annotationsLookup);
mapping.clear();
annotationsLookup.clear();
PDDocument anotherDoc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getClassLoader().getResourceAsStream("pdf/forms/simple_form_with_signature_signed.pdf")));
for (PDPage current : anotherDoc.getPages()) {
mapping.addLookupEntry(current, new PDPage());
annotationsLookup = new AnnotationsDistiller(anotherDoc).retainRelevantAnnotations(mapping);
}
victim.mergeForm(anotherDoc.getDocumentCatalog().getAcroForm(), annotationsLookup);
assertFalse(victim.getForm().getFields().isEmpty());
PDAcroForm form = victim.getForm();
assertNotNull(form);
PDField signature = null;
for (PDField current : form.getFieldTree()) {
if (current.getFieldType() == COSName.SIG.getName()) {
signature = current;
}
}
assertNotNull(signature);
assertEquals("", signature.getValueAsString());
assertTrue(form.isSignaturesExist());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public TaskTestContext assertEmptyMultipleOutput() {
assertNotNull(fileOutput);
assertTrue("Expected an output directory", fileOutput.isDirectory());
assertEquals("Found output files while expecting none", 0, fileOutput.listFiles().length);
return this;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
public TaskTestContext assertEmptyMultipleOutput() {
assertNotNull(fileOutput);
assertTrue("Expected an output directory", fileOutput.isDirectory());
assertEquals("Found output files while expecting none", 0,
fileOutput.listFiles((d, n) -> !n.endsWith(".tmp")).length);
return this;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testFindFontFor() {
assertEquals("NotoSansThai", findFontFor(new PDDocument(), "ทดสอบ").getName());
assertEquals("NotoSans", findFontFor(new PDDocument(), "αυτό είναι ένα τεστ").getName());
assertNull(findFontFor(new PDDocument(), "വീട്"));
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testFindFontFor() {
assertNotNull(findFontFor("ทดสอบ")); // thai
assertNotNull(findFontFor("αυτό είναι ένα τεστ")); // greek
assertNotNull(findFontFor("വീട്")); // malayalam
assertNotNull(findFontFor("मानक")); // hindi
assertNotNull(findFontFor("జ")); // telugu
assertNotNull(findFontFor("উ")); // bengali
assertNotNull(findFontFor("עברית")); // hebrew
assertNotNull(findFontFor("简化字")); // simplified chinese
assertNotNull(findFontFor("한국어/조선말")); // korean
assertNotNull(findFontFor("日本語")); // japanese
assertNotNull(findFontFor("latin ąćęłńóśźż")); // latin
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public String generate(NameGenerationRequest request) {
if (request == null) {
throw new IllegalArgumentException("Unable to generate a name for a null request.");
}
String result = toSafeFilename(
prefixTypesChain.process(prefix, ofNullable(request).orElseGet(() -> nameRequest())));
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("win") || osName.contains("mac")) {
// char based max length
result = shortenFilenameCharLength(result, 255);
} else {
// bytes based max length
result = shortenFilenameBytesLength(result, 254, StandardCharsets.UTF_8);
}
return result;
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public String generate(NameGenerationRequest request) {
if (request == null) {
throw new IllegalArgumentException("Unable to generate a name for a null request.");
}
return toSafeFilename(prefixTypesChain.process(prefix, ofNullable(request).orElseGet(() -> nameRequest())));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void before(AlternateMixParameters parameters, TaskExecutionContext executionContext) throws TaskException {
super.before(parameters, executionContext);
mixer = new PdfAlternateMixer(parameters.getFirstInput(), parameters.getSecondInput());
outputWriter = OutputWriters.newSingleOutputWriter(parameters.getExistingOutputPolicy(), executionContext);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public void before(AlternateMixParameters parameters, TaskExecutionContext executionContext) throws TaskException {
super.before(parameters, executionContext);
mixer = new PdfAlternateMixer();
outputWriter = OutputWriters.newSingleOutputWriter(parameters.getExistingOutputPolicy(), executionContext);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void writeToArchive(File[] sources, ArchiveOutputStream archive) throws IOException {
for (File source : sources) {
if (!source.exists()) {
throw new FileNotFoundException(source.getPath());
} else if (!source.canRead()) {
throw new FileNotFoundException(source.getPath() + " (Permission denied)");
}
if (source.isFile()) {
writeToArchive(source.getParentFile(), new File[]{ source }, archive);
} else {
writeToArchive(source, source.listFiles(), archive);
}
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
protected void writeToArchive(File[] sources, ArchiveOutputStream archive) throws IOException {
for (File source : sources) {
if (!source.exists()) {
throw new FileNotFoundException(source.getPath());
} else if (!source.canRead()) {
throw new FileNotFoundException(source.getPath() + " (Permission denied)");
}
writeToArchive(source.getParentFile(), new File[]{ source }, archive);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static ArchiveOutputStream createArchiveOutputStream(CommonsArchiver archiver, File archive) throws IOException,
ArchiveException {
return createArchiveOutputStream(archiver.getFileType(), new FileOutputStream(archive));
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
static ArchiveOutputStream createArchiveOutputStream(CommonsArchiver archiver, File archive) throws IOException,
ArchiveException {
return createArchiveOutputStream(archiver.getArchiveFormat(), archive);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static FileModeMapper create(ArchiveEntry entry) {
if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
// FIXME: this is really horrid, but with java 6 i need the system call to 'chmod'
// TODO: implement basic windows permission mapping (e.g. with File.setX or attrib)
return new FallbackFileModeMapper(entry);
}
// please don't use me on OS/2
return new UnixPermissionMapper(entry);
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public static FileModeMapper create(ArchiveEntry entry) {
if (IS_POSIX) {
return new PosixPermissionMapper(entry);
}
// TODO: implement basic windows permission mapping (e.g. with File.setX or attrib)
return new FallbackFileModeMapper(entry);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static CompressorOutputStream createCompressorOutputStream(CommonsCompressor compressor, File destination)
throws IOException, CompressorException {
return createCompressorOutputStream(compressor.getFileType(), new FileOutputStream(destination));
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
static CompressorOutputStream createCompressorOutputStream(CommonsCompressor compressor, File destination)
throws IOException, CompressorException {
return createCompressorOutputStream(compressor.getCompressionType(), destination);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void initialize() {
InputStream in = PinyinDic.class.getResourceAsStream(dicLocation);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
String line = null;
long startPoint = System.currentTimeMillis();
while (null != (line = reader.readLine())) {
if (StringUtils.isNotBlank(line)) {
dicSet.add(line);
}
}
long endPoint = System.currentTimeMillis();
Logger.logger.info(String.format("Load pinyin from pinyin.dic, sizeof dic=[%s], takes %s ms, size=%s",
MemoryUsage.humanSizeOf(dicSet), (endPoint - startPoint), dicSet.size()), this);
} catch (Exception ex) {
Logger.logger.error("read pinyin dic error.", ex);
throw new RuntimeException("read pinyin dic error.", ex);
}
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
private void initialize() {
InputStream in = PinyinDic.class.getResourceAsStream(dicLocation);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
String line = null;
long startPoint = System.currentTimeMillis();
while (null != (line = reader.readLine())) {
if (StringUtils.isNotBlank(line)) {
dicSet.add(line);
}
}
long endPoint = System.currentTimeMillis();
Logger.logger.info(String.format("Load pinyin from pinyin.dic, sizeof dic=[%s], takes %s ms, size=%s",
MemoryUsage.humanSizeOf(dicSet), (endPoint - startPoint), dicSet.size()), this);
} catch (Exception ex) {
Logger.logger.error("read pinyin dic error.", ex);
throw new RuntimeException("read pinyin dic error.", ex);
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (Exception ex) {
//ignore ex
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<ProjectMailTicketConfig> findAll() {
List<ProjectMailTicketConfig> configs = queries.findAllConfigs();
List<ProjectMailTicket> ticketConfigs = queries.findAllTickets();
Map<Integer, List<ProjectMailTicket>> ticketConfigsByConfigId = new HashMap<>();
for(ProjectMailTicket ticketConfig: ticketConfigs) {
if(!ticketConfigsByConfigId.containsKey(ticketConfig.getConfigId())) {
ticketConfigsByConfigId.put(ticketConfig.getConfigId(), new ArrayList<ProjectMailTicket>());
}
ticketConfigsByConfigId.get(ticketConfig.getConfigId()).add(ticketConfig);
}
for(ProjectMailTicketConfig config: configs) {
if(ticketConfigsByConfigId.containsKey(config.getId())) {
config.getEntries().addAll(ticketConfigsByConfigId.get(config.getId()));
}
}
return configs;
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
public List<ProjectMailTicketConfig> findAll() {
return aggregateByConfig(queries.findAllConfigs(), queries.findAllTickets());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testFindCardsId() {
Card c1 = cardService.createCard("card1", col1.getId(), new Date(), user);
Card c2 = cardService.createCard("card2", col1.getId(), new Date(), user);
Card c3 = cardService.createCard("card3", col1.getId(), new Date(), user);
Map<String, Integer> res = cardRepository.findCardsIds(Arrays.asList("TEST-BRD-" + c1.getSequence(),
"TEST-BRD-" + c2.getSequence(), "TEST-BRD-" + c3.getSequence()));
Assert.assertEquals(res.get("TEST-BRD-" + c1.getSequence()).intValue(), c1.getId());
Assert.assertEquals(res.get("TEST-BRD-" + c2.getSequence()).intValue(), c2.getId());
Assert.assertEquals(res.get("TEST-BRD-" + c3.getSequence()).intValue(), c3.getId());
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testFindCardsId() {
Card c1 = cardService.createCard("card1", col1.getId(), new Date(), user);
Card c2 = cardService.createCard("card2", col1.getId(), new Date(), user);
Card c3 = cardService.createCard("card3", col1.getId(), new Date(), user);
Map<String, Integer> res = cardRepository.findCardsIds(Arrays.asList("TESTBRD-" + c1.getSequence(),
"TESTBRD-" + c2.getSequence(), "TESTBRD-" + c3.getSequence()));
Assert.assertEquals(res.get("TESTBRD-" + c1.getSequence()).intValue(), c1.getId());
Assert.assertEquals(res.get("TESTBRD-" + c2.getSequence()).intValue(), c2.getId());
Assert.assertEquals(res.get("TESTBRD-" + c3.getSequence()).intValue(), c3.getId());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void checkNew() {
List<ProjectMailTicketConfig> entries = mailTicketRepository.findAll();
for(ProjectMailTicketConfig entry: entries) {
MailReceiver receiver = entry.getConfig().getInboundProtocol().startsWith("pop3") ?
getPop3MailReceiver(entry.getConfig(), entry.getProperties()) :
getImapMailReceiver(entry.getConfig(), entry.getProperties());
try {
Object[] messages = receiver.receive();
LOG.info("found {} messages", messages.length);
for(int i = 0; i < messages.length; i++) {
MimeMessage message = (MimeMessage) messages[i];
String deliveredTo = message.getHeader("Delivered-To", "");
for(ProjectMailTicket ticketConfig: entry.getEntries()) {
if(entry.getConfig().getFrom().equals(deliveredTo)) {
Address[] froms = message.getFrom();
String from = froms == null ? null : ((InternetAddress) froms[0]).getAddress();
try {
createCard(message.getSubject(), getTextFromMessage(message), ticketConfig.getColumnId(), from);
} catch (IOException|MessagingException e) {
LOG.error("failed to parse message content", e);
}
}
}
}
} catch (MessagingException e) {
LOG.error("could not retrieve messages for ticket mail config id: {}", entry.getId());
}
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
public void checkNew() {
List<ProjectMailTicketConfig> entries = mailTicketRepository.findAll();
for(ProjectMailTicketConfig entry: entries) {
MailReceiver receiver = entry.getConfig().getInboundProtocol().startsWith("pop3") ?
getPop3MailReceiver(entry.getConfig(), entry.getProperties()) :
getImapMailReceiver(entry.getConfig(), entry.getProperties());
try {
Object[] messages = receiver.receive();
LOG.info("found {} messages", messages.length);
for(int i = 0; i < messages.length; i++) {
MimeMessage message = (MimeMessage) messages[i];
String deliveredTo = getDeliveredTo(message);
for(ProjectMailTicket ticketConfig: entry.getEntries()) {
if(entry.getConfig().getFrom().equals(deliveredTo)) {
String from = getFrom(message);
try {
createCard(message.getSubject(), getTextFromMessage(message), ticketConfig.getColumnId(), from);
} catch (IOException|MessagingException e) {
LOG.error("failed to parse message content", e);
}
}
}
}
} catch (MessagingException e) {
LOG.error("could not retrieve messages for ticket mail config id: {}", entry.getId());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) {
history.getData().winrate = stats.maxWinrate;
if (Lizzie.leelaz.isKataGo) {
history.getData().scoreMean = stats.maxScoreMean;
}
// we won't set playouts here. but setting winrate is ok... it shows the user that we are
// computing. i think its fine.
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void updateWinrate() {
Leelaz.WinrateStats stats = Lizzie.leelaz.getWinrateStats();
if (stats.maxWinrate >= 0 && stats.totalPlayouts > history.getData().getPlayouts()) {
history.getData().winrate = stats.maxWinrate;
// we won't set playouts here. but setting winrate is ok... it shows the user that we are
// computing. i think its fine.
}
} | 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.