input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
public void testSimpleHttpPostsContentNotConsumed() throws Exception {
HttpRequestHandler requestHandler = new HttpRequestHandler() {
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
// Request content body has not been consumed!!!
response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
NStringEntity outgoing = new NStringEntity("Ooopsie");
response.setEntity(outgoing);
}
};
HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(TestJob testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
NStringEntity entity = null;
try {
entity = new NStringEntity(testjob.getExpected(), "US-ASCII");
entity.setChunked(testjob.getCount() % 2 == 0);
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
return r;
}
};
int connNo = 3;
int reqNo = 20;
TestJob[] jobs = new TestJob[connNo * reqNo];
for (int i = 0; i < jobs.length; i++) {
jobs[i] = new TestJob();
}
Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(requestHandler));
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>();
for (int i = 0; i < connNo; i++) {
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
connRequests.add(sessionRequest);
}
while (!connRequests.isEmpty()) {
SessionRequest sessionRequest = connRequests.remove();
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
}
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < jobs.length; i++) {
TestJob testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, testjob.getStatusCode());
assertEquals("Ooopsie", testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
}
#location 83
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void testSimpleHttpPostsContentNotConsumed() throws Exception {
HttpRequestHandler requestHandler = new HttpRequestHandler() {
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
// Request content body has not been consumed!!!
response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
NStringEntity outgoing = new NStringEntity("Ooopsie");
response.setEntity(outgoing);
}
};
HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(Job testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
NStringEntity entity = null;
try {
entity = new NStringEntity(testjob.getExpected(), "US-ASCII");
entity.setChunked(testjob.getCount() % 2 == 0);
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
return r;
}
};
int connNo = 3;
int reqNo = 20;
Job[] jobs = new Job[connNo * reqNo];
for (int i = 0; i < jobs.length; i++) {
jobs[i] = new Job();
}
Queue<Job> queue = new ConcurrentLinkedQueue<Job>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(requestHandler));
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>();
for (int i = 0; i < connNo; i++) {
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
connRequests.add(sessionRequest);
}
while (!connRequests.isEmpty()) {
SessionRequest sessionRequest = connRequests.remove();
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
}
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < jobs.length; i++) {
Job testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(HttpStatus.SC_INTERNAL_SERVER_ERROR, testjob.getStatusCode());
assertEquals("Ooopsie", testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String toString(
final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
String charset = getContentCharSet(entity);
if (charset == null) {
charset = defaultCharset;
}
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
instream.close();
}
}
#location 34
#vulnerability type RESOURCE_LEAK | #fixed code
public static String toString(
final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
ContentType contentType = ContentType.getOrDefault(entity);
String charset = contentType.getCharset();
if (charset == null) {
charset = defaultCharset;
}
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
instream.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void processEvent(final SelectionKey key) {
SessionHandle handle = (SessionHandle) key.attachment();
IOSession session = handle.getSession();
try {
if (key.isAcceptable()) {
acceptable(key);
}
if (key.isConnectable()) {
connectable(key);
}
if (key.isReadable()) {
handle.resetLastRead();
readable(key);
}
if (key.isWritable()) {
handle.resetLastWrite();
writable(key);
}
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
}
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void processEvent(final SelectionKey key) {
IOSessionImpl session = (IOSessionImpl) key.attachment();
try {
if (key.isAcceptable()) {
acceptable(key);
}
if (key.isConnectable()) {
connectable(key);
}
if (key.isReadable()) {
session.resetLastRead();
readable(key);
}
if (key.isWritable()) {
session.resetLastWrite();
writable(key);
}
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEmptyChunkedInputStream() throws IOException {
final String input = "0\r\n";
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(input, Consts.ISO_8859_1));
final byte[] buffer = new byte[300];
final ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
Assert.assertEquals(0, out.size());
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEmptyChunkedInputStream() throws IOException {
final String input = "0\r\n";
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(input, Consts.ISO_8859_1));
final byte[] buffer = new byte[300];
final ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
Assert.assertEquals(0, out.size());
in.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void onRequestReceived(final HttpRequest request) throws IOException {
this.request = request;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) this.request).getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (len > Integer.MAX_VALUE) {
throw new ContentTooLongException("Entity content is too long: " + len);
}
if (len < 0) {
len = 4096;
}
this.buf = new SimpleInputBuffer((int) len, HeapByteBufferAllocator.INSTANCE);
((HttpEntityEnclosingRequest) this.request).setEntity(
new ContentBufferEntity(entity, this.buf));
}
}
}
#location 14
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
@Override
protected void onRequestReceived(final HttpRequest request) throws IOException {
this.request = request;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEndOfStreamConditionReadingLastChunk() throws Exception {
String s = "10\r\n1234567890123456\r\n" +
"5\r\n12345\r\n5\r\n12345";
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
ByteBuffer dst = ByteBuffer.allocate(1024);
int bytesRead = 0;
while (dst.hasRemaining() && !decoder.isCompleted()) {
int i = decoder.read(dst);
if (i > 0) {
bytesRead += i;
}
}
Assert.assertEquals(26, bytesRead);
Assert.assertEquals("12345678901234561234512345", convert(dst));
Assert.assertTrue(decoder.isCompleted());
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEndOfStreamConditionReadingLastChunk() throws Exception {
String s = "10\r\n1234567890123456\r\n" +
"5\r\n12345\r\n5\r\n12345";
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
ByteBuffer dst = ByteBuffer.allocate(1024);
int bytesRead = 0;
while (dst.hasRemaining() && !decoder.isCompleted()) {
int i = decoder.read(dst);
if (i > 0) {
bytesRead += i;
}
}
Assert.assertEquals(26, bytesRead);
Assert.assertEquals("12345678901234561234512345", convert(dst));
Assert.assertTrue(decoder.isCompleted());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testWriteBeyondFileSize() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"a"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
IdentityDecoder decoder = new IdentityDecoder(
channel, inbuf, metrics);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
Assert.assertEquals(0, testfile.length());
try {
decoder.transfer(fchannel, 5, 10);
Assert.fail("expected IOException");
} catch(IOException iox) {}
testfile.close();
deleteWithCheck(fileHandle);
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testWriteBeyondFileSize() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {"a"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
IdentityDecoder decoder = new IdentityDecoder(
channel, inbuf, metrics);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
Assert.assertEquals(0, testfile.length());
try {
decoder.transfer(fchannel, 5, 10);
Assert.fail("expected IOException");
} catch(IOException iox) {}
testfile.close();
deleteWithCheck(fileHandle);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void processEvent(final SelectionKey key) {
SessionHandle handle = (SessionHandle) key.attachment();
IOSession session = handle.getSession();
try {
if (key.isAcceptable()) {
acceptable(key);
}
if (key.isConnectable()) {
connectable(key);
}
if (key.isReadable()) {
handle.resetLastRead();
readable(key);
}
if (key.isWritable()) {
handle.resetLastWrite();
writable(key);
}
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
}
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void processEvent(final SelectionKey key) {
IOSessionImpl session = (IOSessionImpl) key.attachment();
try {
if (key.isAcceptable()) {
acceptable(key);
}
if (key.isConnectable()) {
connectable(key);
}
if (key.isReadable()) {
session.resetLastRead();
readable(key);
}
if (key.isWritable()) {
session.resetLastWrite();
writable(key);
}
} catch (CancelledKeyException ex) {
queueClosedSession(session);
key.attach(null);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testBasicDecodingFile() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"stuff; ", "more stuff; ", "a lot more stuff!!!"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 36);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
long pos = 0;
while (!decoder.isCompleted()) {
long bytesRead = decoder.transfer(fchannel, pos, 10);
if (bytesRead > 0) {
pos += bytesRead;
}
}
fchannel.close();
assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle));
fileHandle.delete();
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
public void testBasicDecodingFile() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"stuff; ", "more stuff; ", "a lot more stuff!!!"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 36);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
long pos = 0;
while (!decoder.isCompleted()) {
long bytesRead = decoder.transfer(fchannel, pos, 10);
if (bytesRead > 0) {
pos += bytesRead;
}
}
assertEquals(testfile.length(), metrics.getBytesTransferred());
fchannel.close();
assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle));
fileHandle.delete();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = MalformedChunkCodingException.class)
public void testCorruptChunkedInputStreamNegativeSize() throws IOException {
final String s = "-5\r\n01234\r\n5\r\n56789\r\n0\r\n";
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(s, Consts.ISO_8859_1));
in.read();
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = MalformedChunkCodingException.class)
public void testCorruptChunkedInputStreamNegativeSize() throws IOException {
final String s = "-5\r\n01234\r\n5\r\n56789\r\n0\r\n";
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(s, Consts.ISO_8859_1));
in.read();
in.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testBasicDecodingFile() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"stuff;", "more stuff"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 16);
File tmpFile = File.createTempFile("testFile", ".txt");
FileChannel fchannel = new FileOutputStream(tmpFile).getChannel();
long bytesRead = decoder.transfer(fchannel, 0, 6);
assertEquals(6, bytesRead);
assertEquals("stuff;", readFromFile(tmpFile, 6));
assertFalse(decoder.isCompleted());
bytesRead = decoder.transfer(fchannel,0 , 10);
assertEquals(10, bytesRead);
assertEquals("more stuff", readFromFile(tmpFile, 10));
assertTrue(decoder.isCompleted());
bytesRead = decoder.transfer(fchannel, 0, 1);
assertEquals(0, bytesRead);
assertTrue(decoder.isCompleted());
tmpFile.delete();
}
#location 29
#vulnerability type RESOURCE_LEAK | #fixed code
public void testBasicDecodingFile() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"stuff; ", "more stuff; ", "a lot more stuff!!!"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 36);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
long pos = 0;
while (!decoder.isCompleted()) {
long bytesRead = decoder.transfer(fchannel, pos, 10);
if (bytesRead > 0) {
pos += bytesRead;
}
}
fchannel.close();
assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle));
fileHandle.delete();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testChunkedConsistence() throws IOException {
final String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb";
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final OutputStream out = new ChunkedOutputStream(2048, new SessionOutputBufferMock(buffer));
out.write(EncodingUtils.getBytes(input, CONTENT_CHARSET));
out.flush();
out.close();
out.close();
buffer.close();
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(
buffer.toByteArray()));
final byte[] d = new byte[10];
final ByteArrayOutputStream result = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(d)) > 0) {
result.write(d, 0, len);
}
final String output = EncodingUtils.getString(result.toByteArray(), CONTENT_CHARSET);
Assert.assertEquals(input, output);
in.close();
}
#location 20
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testChunkedConsistence() throws IOException {
final String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb";
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final OutputStream out = new ChunkedOutputStream(2048, new SessionOutputBufferMock(buffer));
out.write(input.getBytes(Consts.ISO_8859_1));
out.flush();
out.close();
out.close();
buffer.close();
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(
buffer.toByteArray()));
final byte[] d = new byte[10];
final ByteArrayOutputStream result = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(d)) > 0) {
result.write(d, 0, len);
}
final String output = new String(result.toByteArray(), Consts.ISO_8859_1);
Assert.assertEquals(input, output);
in.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTooLongChunkHeader() throws IOException {
final String input = "5; and some very looooong commend\r\n12345\r\n0\r\n";
final InputStream in1 = new ChunkedInputStream(
new SessionInputBufferMock(input, MessageConstraints.DEFAULT, Consts.ISO_8859_1));
final byte[] buffer = new byte[300];
Assert.assertEquals(5, in1.read(buffer));
final InputStream in2 = new ChunkedInputStream(
new SessionInputBufferMock(input, MessageConstraints.lineLen(10), Consts.ISO_8859_1));
try {
in2.read(buffer);
Assert.fail("MessageConstraintException expected");
} catch (MessageConstraintException ex) {
}
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTooLongChunkHeader() throws IOException {
final String input = "5; and some very looooong commend\r\n12345\r\n0\r\n";
final InputStream in1 = new ChunkedInputStream(
new SessionInputBufferMock(input, MessageConstraints.DEFAULT, Consts.ISO_8859_1));
final byte[] buffer = new byte[300];
Assert.assertEquals(5, in1.read(buffer));
in1.close();
final InputStream in2 = new ChunkedInputStream(
new SessionInputBufferMock(input, MessageConstraints.lineLen(10), Consts.ISO_8859_1));
try {
in2.read(buffer);
Assert.fail("MessageConstraintException expected");
} catch (MessageConstraintException ex) {
} finally {
in2.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void onResponseReceived(final HttpResponse response) throws IOException {
this.response = response;
HttpEntity entity = this.response.getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (len > Integer.MAX_VALUE) {
throw new ContentTooLongException("Entity content is too long: " + len);
}
if (len < 0) {
len = 4096;
}
this.buf = new SimpleInputBuffer((int) len, HeapByteBufferAllocator.INSTANCE);
response.setEntity(new ContentBufferEntity(entity, this.buf));
}
}
#location 13
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
@Override
protected void onResponseReceived(final HttpResponse response) throws IOException {
this.response = response;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testInputBufferOperations() throws IOException {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"stuff;", "more stuff"}, "US-ASCII");
ContentDecoder decoder = new MockupDecoder(channel);
SimpleInputBuffer buffer = new SimpleInputBuffer(4, new DirectByteBufferAllocator());
int count = buffer.consumeContent(decoder);
Assert.assertEquals(16, count);
Assert.assertTrue(decoder.isCompleted());
byte[] b1 = new byte[5];
int len = buffer.read(b1);
Assert.assertEquals("stuff", EncodingUtils.getAsciiString(b1, 0, len));
int c = buffer.read();
Assert.assertEquals(';', c);
byte[] b2 = new byte[1024];
len = buffer.read(b2);
Assert.assertEquals("more stuff", EncodingUtils.getAsciiString(b2, 0, len));
Assert.assertEquals(-1, buffer.read());
Assert.assertEquals(-1, buffer.read(b2));
Assert.assertEquals(-1, buffer.read(b2, 0, b2.length));
Assert.assertTrue(buffer.isEndOfStream());
buffer.reset();
Assert.assertFalse(buffer.isEndOfStream());
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testInputBufferOperations() throws IOException {
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {"stuff;", "more stuff"}, "US-ASCII");
ContentDecoder decoder = new ContentDecoderMock(channel);
SimpleInputBuffer buffer = new SimpleInputBuffer(4, new DirectByteBufferAllocator());
int count = buffer.consumeContent(decoder);
Assert.assertEquals(16, count);
Assert.assertTrue(decoder.isCompleted());
byte[] b1 = new byte[5];
int len = buffer.read(b1);
Assert.assertEquals("stuff", EncodingUtils.getAsciiString(b1, 0, len));
int c = buffer.read();
Assert.assertEquals(';', c);
byte[] b2 = new byte[1024];
len = buffer.read(b2);
Assert.assertEquals("more stuff", EncodingUtils.getAsciiString(b2, 0, len));
Assert.assertEquals(-1, buffer.read());
Assert.assertEquals(-1, buffer.read(b2));
Assert.assertEquals(-1, buffer.read(b2, 0, b2.length));
Assert.assertTrue(buffer.isEndOfStream());
buffer.reset();
Assert.assertFalse(buffer.isEndOfStream());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConstructor() throws Exception {
final SessionInputBuffer receiver = new SessionInputBufferMock(new byte[] {});
new IdentityInputStream(receiver);
try {
new IdentityInputStream(null);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
//expected
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testConstructor() throws Exception {
final SessionInputBuffer receiver = new SessionInputBufferMock(new byte[] {});
final IdentityInputStream in = new IdentityInputStream(receiver);
in.close();
try {
new IdentityInputStream(null);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
//expected
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testChunkedConsistence() throws IOException {
final String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb";
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final OutputStream out = new ChunkedOutputStream(2048, new SessionOutputBufferMock(buffer));
out.write(EncodingUtils.getBytes(input, CONTENT_CHARSET));
out.flush();
out.close();
out.close();
buffer.close();
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(
buffer.toByteArray()));
final byte[] d = new byte[10];
final ByteArrayOutputStream result = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(d)) > 0) {
result.write(d, 0, len);
}
final String output = EncodingUtils.getString(result.toByteArray(), CONTENT_CHARSET);
Assert.assertEquals(input, output);
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testChunkedConsistence() throws IOException {
final String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb";
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final OutputStream out = new ChunkedOutputStream(2048, new SessionOutputBufferMock(buffer));
out.write(EncodingUtils.getBytes(input, CONTENT_CHARSET));
out.flush();
out.close();
out.close();
buffer.close();
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(
buffer.toByteArray()));
final byte[] d = new byte[10];
final ByteArrayOutputStream result = new ByteArrayOutputStream();
int len = 0;
while ((len = in.read(d)) > 0) {
result.write(d, 0, len);
}
final String output = EncodingUtils.getString(result.toByteArray(), CONTENT_CHARSET);
Assert.assertEquals(input, output);
in.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected=MalformedChunkCodingException.class)
public void testCorruptChunkedInputStreamMissingCRLF() throws IOException {
final String s = "5\r\n012345\r\n56789\r\n0\r\n";
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(s, Consts.ISO_8859_1));
final byte[] buffer = new byte[300];
final ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected=MalformedChunkCodingException.class)
public void testCorruptChunkedInputStreamMissingCRLF() throws IOException {
final String s = "5\r\n012345\r\n56789\r\n0\r\n";
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(s, Consts.ISO_8859_1));
final byte[] buffer = new byte[300];
final ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
in.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConstructor() throws Exception {
final SessionOutputBufferMock transmitter = new SessionOutputBufferMock();
new IdentityOutputStream(transmitter);
try {
new IdentityOutputStream(null);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
//expected
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testConstructor() throws Exception {
final SessionOutputBufferMock transmitter = new SessionOutputBufferMock();
new IdentityOutputStream(transmitter).close();
try {
new IdentityOutputStream(null);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
//expected
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testSimpleHttpPostsWithContentLength() throws Exception {
HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(TestJob testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
NStringEntity entity = null;
try {
entity = new NStringEntity(testjob.getExpected(), "US-ASCII");
entity.setChunked(false);
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
return r;
}
};
executeStandardTest(new TestRequestHandler(), requestExecutionHandler);
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void testSimpleHttpPostsWithContentLength() throws Exception {
HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(Job testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
NStringEntity entity = null;
try {
entity = new NStringEntity(testjob.getExpected(), "US-ASCII");
entity.setChunked(false);
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
return r;
}
};
executeStandardTest(new RequestHandler(), requestExecutionHandler);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testFoldedFooters() throws Exception {
String s = "10;key=\"value\"\r\n1234567890123456\r\n" +
"5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\n \r\n fghij\r\n\r\n";
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
ByteBuffer dst = ByteBuffer.allocate(1024);
int bytesRead = decoder.read(dst);
Assert.assertEquals(26, bytesRead);
Assert.assertEquals("12345678901234561234512345", convert(dst));
Header[] footers = decoder.getFooters();
Assert.assertEquals(1, footers.length);
Assert.assertEquals("Footer1", footers[0].getName());
Assert.assertEquals("abcde fghij", footers[0].getValue());
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testFoldedFooters() throws Exception {
String s = "10;key=\"value\"\r\n1234567890123456\r\n" +
"5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\n \r\n fghij\r\n\r\n";
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
ByteBuffer dst = ByteBuffer.allocate(1024);
int bytesRead = decoder.read(dst);
Assert.assertEquals(26, bytesRead);
Assert.assertEquals("12345678901234561234512345", convert(dst));
Header[] footers = decoder.getFooters();
Assert.assertEquals(1, footers.length);
Assert.assertEquals("Footer1", footers[0].getName());
Assert.assertEquals("abcde fghij", footers[0].getValue());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntityWithInvalidContentLength() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(-1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertFalse(instream instanceof ContentLengthInputStream);
Assert.assertTrue(instream instanceof IdentityInputStream);
// strict mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true);
try {
entitygen.deserialize(inbuffer, message);
Assert.fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
// expected
}
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntityWithInvalidContentLength() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(-1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertFalse(instream instanceof ContentLengthInputStream);
Assert.assertTrue(instream instanceof IdentityInputStream);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAvailable() throws Exception {
final byte[] input = new byte[] {'a', 'b', 'c'};
final SessionInputBufferMock receiver = new SessionInputBufferMock(input);
final IdentityInputStream instream = new IdentityInputStream(receiver);
instream.read();
Assert.assertEquals(2, instream.available());
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAvailable() throws Exception {
final byte[] input = new byte[] {'a', 'b', 'c'};
final SessionInputBufferMock receiver = new SessionInputBufferMock(input);
final IdentityInputStream instream = new IdentityInputStream(receiver);
instream.read();
Assert.assertEquals(2, instream.available());
instream.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public DefaultNHttpClientConnection createConnection(final IOSession iosession) {
final SSLIOSession ssliosession = createSSLIOSession(iosession, this.sslcontext, this.sslHandler);
CharsetDecoder chardecoder = null;
CharsetEncoder charencoder = null;
final Charset charset = this.config.getCharset();
final CodingErrorAction malformedInputAction = this.config.getMalformedInputAction() != null ?
this.config.getMalformedInputAction() : CodingErrorAction.REPORT;
final CodingErrorAction unmappableInputAction = this.config.getUnmappableInputAction() != null ?
this.config.getUnmappableInputAction() : CodingErrorAction.REPORT;
if (charset != null) {
chardecoder = charset.newDecoder();
chardecoder.onMalformedInput(malformedInputAction);
chardecoder.onUnmappableCharacter(unmappableInputAction);
charencoder = charset.newEncoder();
charencoder.onMalformedInput(malformedInputAction);
charencoder.onUnmappableCharacter(unmappableInputAction);
}
return new DefaultNHttpClientConnection(
ssliosession,
this.config.getBufferSize(),
this.config.getFragmentSizeHint(),
this.allocator,
chardecoder, charencoder, this.config.getMessageConstraints(),
null, null, null,
this.responseParserFactory);
}
#location 23
#vulnerability type NULL_DEREFERENCE | #fixed code
public DefaultNHttpClientConnection createConnection(final IOSession iosession) {
final SSLIOSession ssliosession = createSSLIOSession(iosession, this.sslcontext, this.sslHandler);
return new DefaultNHttpClientConnection(
ssliosession,
this.cconfig.getBufferSize(),
this.cconfig.getFragmentSizeHint(),
this.allocator,
ConnSupport.createDecoder(this.cconfig),
ConnSupport.createEncoder(this.cconfig),
this.cconfig.getMessageConstraints(),
null, null, null,
this.responseParserFactory);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCorruptChunkedInputStreamNegativeSize() throws IOException {
final String s = "-5\r\n01234\r\n5\r\n56789\r\n0\r\n";
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(
EncodingUtils.getBytes(s, CONTENT_CHARSET)));
try {
in.read();
Assert.fail("MalformedChunkCodingException should have been thrown");
} catch(final MalformedChunkCodingException e) {
/* expected exception */
}
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCorruptChunkedInputStreamNegativeSize() throws IOException {
final String s = "-5\r\n01234\r\n5\r\n56789\r\n0\r\n";
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(
EncodingUtils.getBytes(s, CONTENT_CHARSET)));
try {
in.read();
Assert.fail("MalformedChunkCodingException should have been thrown");
} catch(final MalformedChunkCodingException e) {
/* expected exception */
}
try {
in.close();
} catch (TruncatedChunkException expected) {
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testCodingCompletedFromFile() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
WritableByteChannel channel = newChannel(baos);
HttpParams params = new BasicHttpParams();
SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(
channel, outbuf, metrics, 5);
encoder.write(wrap("stuff"));
File tmpFile = File.createTempFile("testFile", "txt");
FileOutputStream fout = new FileOutputStream(tmpFile);
OutputStreamWriter wrtout = new OutputStreamWriter(fout);
wrtout.write("more stuff");
wrtout.flush();
wrtout.close();
try {
FileChannel fchannel = new FileInputStream(tmpFile).getChannel();
encoder.transfer(fchannel, 0, 10);
fail("IllegalStateException should have been thrown");
} catch (IllegalStateException ex) {
// ignore
} finally {
deleteWithCheck(tmpFile);
}
}
#location 23
#vulnerability type RESOURCE_LEAK | #fixed code
public void testCodingCompletedFromFile() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
WritableByteChannel channel = newChannel(baos);
HttpParams params = new BasicHttpParams();
SessionOutputBuffer outbuf = new SessionOutputBufferImpl(1024, 128, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedEncoder encoder = new LengthDelimitedEncoder(
channel, outbuf, metrics, 5);
encoder.write(wrap("stuff"));
File tmpFile = File.createTempFile("testFile", ".txt");
FileOutputStream fout = new FileOutputStream(tmpFile);
OutputStreamWriter wrtout = new OutputStreamWriter(fout);
wrtout.write("more stuff");
wrtout.flush();
wrtout.close();
FileChannel fchannel = new FileInputStream(tmpFile).getChannel();
try {
encoder.transfer(fchannel, 0, 10);
fail("IllegalStateException should have been thrown");
} catch (IllegalStateException ex) {
// ignore
} finally {
fchannel.close();
deleteWithCheck(tmpFile);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testSimpleHttpHeads() throws Exception {
int connNo = 3;
int reqNo = 20;
TestJob[] jobs = new TestJob[connNo * reqNo];
for (int i = 0; i < jobs.length; i++) {
jobs[i] = new TestJob();
}
Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(TestJob testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
return new BasicHttpRequest("HEAD", s);
}
};
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new TestRequestHandler()));
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>();
for (int i = 0; i < connNo; i++) {
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
connRequests.add(sessionRequest);
}
while (!connRequests.isEmpty()) {
SessionRequest sessionRequest = connRequests.remove();
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
}
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < jobs.length; i++) {
TestJob testjob = jobs[i];
testjob.waitFor();
if (testjob.getFailureMessage() != null) {
fail(testjob.getFailureMessage());
}
assertEquals(HttpStatus.SC_OK, testjob.getStatusCode());
assertNull(testjob.getResult());
}
}
#location 58
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void testSimpleHttpHeads() throws Exception {
int connNo = 3;
int reqNo = 20;
Job[] jobs = new Job[connNo * reqNo];
for (int i = 0; i < jobs.length; i++) {
jobs[i] = new Job();
}
Queue<Job> queue = new ConcurrentLinkedQueue<Job>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(Job testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
return new BasicHttpRequest("HEAD", s);
}
};
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new RequestHandler()));
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>();
for (int i = 0; i < connNo; i++) {
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
connRequests.add(sessionRequest);
}
while (!connRequests.isEmpty()) {
SessionRequest sessionRequest = connRequests.remove();
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
}
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < jobs.length; i++) {
Job testjob = jobs[i];
testjob.waitFor();
if (testjob.getFailureMessage() != null) {
fail(testjob.getFailureMessage());
}
assertEquals(HttpStatus.SC_OK, testjob.getStatusCode());
assertNull(testjob.getResult());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void handleRequest(
final ServerConnState connState,
final HttpContext context) throws HttpException, IOException {
HttpRequest request = connState.getRequest();
context.setAttribute(HttpExecutionContext.HTTP_REQUEST, request);
HttpVersion ver = request.getRequestLine().getHttpVersion();
if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
// Downgrade protocol version if greater than HTTP/1.1
ver = HttpVersion.HTTP_1_1;
}
HttpResponse response;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest entityReq = (HttpEntityEnclosingRequest) request;
if (entityReq.expectContinue()) {
response = this.responseFactory.newHttpResponse(
ver,
HttpStatus.SC_CONTINUE,
context);
response.getParams().setDefaults(this.params);
if (this.expectationVerifier != null) {
try {
this.expectationVerifier.verify(request, response, context);
} catch (HttpException ex) {
handleException(connState, ex ,context);
return;
}
}
if (response.getStatusLine().getStatusCode() < 200) {
// Send 1xx response indicating the server expections
// have been met
waitForOutput(connState, ServerConnState.READY);
connState.setResponse(response);
synchronized (connState) {
waitForOutput(connState, ServerConnState.RESPONSE_SENT);
connState.resetOutput();
}
} else {
// The request does not meet the server expections
context.setAttribute(HttpExecutionContext.HTTP_RESPONSE, response);
this.httpProcessor.process(response, context);
connState.setResponse(response);
return;
}
}
// Create a wrapper entity instead of the original one
if (entityReq.getEntity() != null) {
entityReq.setEntity(new BufferedContent(
entityReq.getEntity(),
connState.getInbuffer()));
}
}
response = this.responseFactory.newHttpResponse(
ver,
HttpStatus.SC_OK,
context);
response.getParams().setDefaults(this.params);
context.setAttribute(HttpExecutionContext.HTTP_RESPONSE, response);
try {
this.httpProcessor.process(request, context);
HttpRequestHandler handler = null;
if (this.handlerResolver != null) {
String requestURI = request.getRequestLine().getUri();
handler = this.handlerResolver.lookup(requestURI);
}
if (handler != null) {
handler.handle(request, response, context);
} else {
response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
}
} catch (HttpException ex) {
handleException(connState, ex ,context);
return;
}
this.httpProcessor.process(response, context);
connState.setResponse(response);
}
#location 55
#vulnerability type RESOURCE_LEAK | #fixed code
private void handleRequest(
final ServerConnState connState,
final HttpContext context) throws HttpException, IOException {
HttpRequest request = connState.getRequest();
context.setAttribute(HttpExecutionContext.HTTP_REQUEST, request);
HttpVersion ver = request.getRequestLine().getHttpVersion();
if (!ver.lessEquals(HttpVersion.HTTP_1_1)) {
// Downgrade protocol version if greater than HTTP/1.1
ver = HttpVersion.HTTP_1_1;
}
HttpResponse response;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntityEnclosingRequest entityReq = (HttpEntityEnclosingRequest) request;
if (entityReq.expectContinue()) {
response = this.responseFactory.newHttpResponse(
ver,
HttpStatus.SC_CONTINUE,
context);
response.getParams().setDefaults(this.params);
if (this.expectationVerifier != null) {
try {
this.expectationVerifier.verify(request, response, context);
} catch (HttpException ex) {
handleException(connState, ex ,context);
return;
}
}
if (response.getStatusLine().getStatusCode() < 200) {
// Send 1xx response indicating the server expections
// have been met
waitForOutput(connState, ServerConnState.READY);
connState.setResponse(response);
synchronized (connState) {
waitForOutput(connState, ServerConnState.RESPONSE_SENT);
connState.resetOutput();
}
} else {
// The request does not meet the server expections
context.setAttribute(HttpExecutionContext.HTTP_RESPONSE, response);
this.httpProcessor.process(response, context);
connState.setResponse(response);
return;
}
}
// Create a wrapper entity instead of the original one
if (entityReq.getEntity() != null) {
entityReq.setEntity(new ContentBufferEntity(
entityReq.getEntity(),
connState.getInbuffer()));
}
}
response = this.responseFactory.newHttpResponse(
ver,
HttpStatus.SC_OK,
context);
response.getParams().setDefaults(this.params);
context.setAttribute(HttpExecutionContext.HTTP_RESPONSE, response);
try {
this.httpProcessor.process(request, context);
HttpRequestHandler handler = null;
if (this.handlerResolver != null) {
String requestURI = request.getRequestLine().getUri();
handler = this.handlerResolver.lookup(requestURI);
}
if (handler != null) {
handler.handle(request, response, context);
} else {
response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED);
}
} catch (HttpException ex) {
handleException(connState, ex ,context);
return;
}
this.httpProcessor.process(response, context);
connState.setResponse(response);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntityWithMultipleContentLengthAllWrong() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "yyy");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(-1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertFalse(instream instanceof ContentLengthInputStream);
Assert.assertTrue(instream instanceof IdentityInputStream);
// strict mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true);
try {
entitygen.deserialize(inbuffer, message);
Assert.fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
// expected
}
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntityWithMultipleContentLengthAllWrong() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "yyy");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(-1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertFalse(instream instanceof ContentLengthInputStream);
Assert.assertTrue(instream instanceof IdentityInputStream);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void doShutdown() throws InterruptedIOException {
if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) {
return;
}
this.status = IOReactorStatus.SHUTTING_DOWN;
try {
cancelRequests();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
this.selector.wakeup();
// Close out all channels
if (this.selector.isOpen()) {
Set<SelectionKey> keys = this.selector.keys();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) {
try {
SelectionKey key = it.next();
Channel channel = key.channel();
if (channel != null) {
channel.close();
}
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Stop dispatching I/O events
try {
this.selector.close();
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Attempt to shut down I/O dispatchers gracefully
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
dispatcher.gracefulShutdown();
}
long gracePeriod = NIOReactorParams.getGracePeriod(this.params);
try {
// Force shut down I/O dispatchers if they fail to terminate
// in time
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) {
dispatcher.awaitShutdown(gracePeriod);
}
if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) {
try {
dispatcher.hardShutdown();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
}
}
// Join worker threads
for (int i = 0; i < this.workerCount; i++) {
Thread t = this.threads[i];
if (t != null) {
t.join(gracePeriod);
}
}
} catch (InterruptedException ex) {
throw new InterruptedIOException(ex.getMessage());
} finally {
synchronized (this.shutdownMutex) {
this.status = IOReactorStatus.SHUT_DOWN;
this.shutdownMutex.notifyAll();
}
}
}
#location 39
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void doShutdown() throws InterruptedIOException {
if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) {
return;
}
this.status = IOReactorStatus.SHUTTING_DOWN;
try {
cancelRequests();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
this.selector.wakeup();
// Close out all channels
if (this.selector.isOpen()) {
Set<SelectionKey> keys = this.selector.keys();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) {
try {
SelectionKey key = it.next();
Channel channel = key.channel();
if (channel != null) {
channel.close();
}
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Stop dispatching I/O events
try {
this.selector.close();
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Attempt to shut down I/O dispatchers gracefully
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
dispatcher.gracefulShutdown();
}
long gracePeriod = NIOReactorParams.getGracePeriod(this.params);
try {
// Force shut down I/O dispatchers if they fail to terminate
// in time
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) {
dispatcher.awaitShutdown(gracePeriod);
}
if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) {
try {
dispatcher.hardShutdown();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
}
}
// Join worker threads
for (int i = 0; i < this.workerCount; i++) {
Thread t = this.threads[i];
if (t != null) {
t.join(gracePeriod);
}
}
} catch (InterruptedException ex) {
throw new InterruptedIOException(ex.getMessage());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void connected(final IOSession session) {
SSLIOSession sslSession = new SSLIOSession(
session,
this.sslcontext,
this.sslHandler);
NHttpClientIOTarget conn = createConnection(
sslSession);
session.setAttribute(NHTTP_CONN, conn);
session.setAttribute(SSL_SESSION, sslSession);
Object attachment = session.getAttribute(IOSession.ATTACHMENT_KEY);
this.handler.connected(conn, attachment);
try {
sslSession.bind(SSLMode.CLIENT, this.params);
} catch (SSLException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
public void connected(final IOSession session) {
SSLIOSession sslSession = createSSLIOSession(
session,
this.sslcontext,
this.sslHandler);
NHttpClientIOTarget conn = createConnection(
sslSession);
session.setAttribute(NHTTP_CONN, conn);
session.setAttribute(SSL_SESSION, sslSession);
Object attachment = session.getAttribute(IOSession.ATTACHMENT_KEY);
this.handler.connected(conn, attachment);
try {
sslSession.bind(SSLMode.CLIENT, this.params);
} catch (SSLException ex) {
this.handler.exception(conn, ex);
sslSession.shutdown();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void onRequestReceived(final HttpRequest request) throws IOException {
this.request = request;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) this.request).getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (len > Integer.MAX_VALUE) {
throw new ContentTooLongException("Entity content is too long: " + len);
}
if (len < 0) {
len = 4096;
}
this.buf = new SimpleInputBuffer((int) len, HeapByteBufferAllocator.INSTANCE);
((HttpEntityEnclosingRequest) this.request).setEntity(
new ContentBufferEntity(entity, this.buf));
}
}
}
#location 7
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
@Override
protected void onRequestReceived(final HttpRequest request) throws IOException {
this.request = request;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConstructors() throws Exception {
new ContentLengthInputStream(new SessionInputBufferMock(new byte[] {}), 10);
try {
new ContentLengthInputStream(null, 10);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
new ContentLengthInputStream(new SessionInputBufferMock(new byte[] {}), -10);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testConstructors() throws Exception {
final ContentLengthInputStream in = new ContentLengthInputStream(
new SessionInputBufferMock(new byte[] {}), 0);
in.close();
try {
new ContentLengthInputStream(null, 10);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
try {
new ContentLengthInputStream(new SessionInputBufferMock(new byte[] {}), -10);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
// expected
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testBasicDecodingFile() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"stuff;", "more stuff"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
IdentityDecoder decoder = new IdentityDecoder(channel, inbuf, metrics);
File tmpFile = File.createTempFile("testFile", ".txt");
FileChannel fchannel = new FileOutputStream(tmpFile).getChannel();
long bytesRead = decoder.transfer(fchannel, 0, 6);
assertEquals(6, bytesRead);
assertEquals("stuff;", readFromFile(tmpFile, 6));
assertFalse(decoder.isCompleted());
bytesRead = decoder.transfer(fchannel,0 , 10);
assertEquals(10, bytesRead);
assertEquals("more stuff", readFromFile(tmpFile, 10));
assertFalse(decoder.isCompleted());
bytesRead = decoder.transfer(fchannel, 0, 1);
assertEquals(0, bytesRead);
assertTrue(decoder.isCompleted());
bytesRead = decoder.transfer(fchannel, 0, 1);
assertEquals(0, bytesRead);
assertTrue(decoder.isCompleted());
tmpFile.delete();
}
#location 32
#vulnerability type RESOURCE_LEAK | #fixed code
public void testBasicDecodingFile() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"stuff; ", "more stuff; ", "a lot more stuff!"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
IdentityDecoder decoder = new IdentityDecoder(
channel, inbuf, metrics);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
long pos = 0;
while (!decoder.isCompleted()) {
long bytesRead = decoder.transfer(fchannel, pos, 10);
if (bytesRead > 0) {
pos += bytesRead;
}
}
fchannel.close();
assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle));
fileHandle.delete();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBasicDecoding() throws Exception {
String s = "5\r\n01234\r\n5\r\n56789\r\n6\r\nabcdef\r\n0\r\n\r\n";
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
ByteBuffer dst = ByteBuffer.allocate(1024);
int bytesRead = decoder.read(dst);
Assert.assertEquals(16, bytesRead);
Assert.assertEquals("0123456789abcdef", convert(dst));
Header[] footers = decoder.getFooters();
Assert.assertEquals(0, footers.length);
dst.clear();
bytesRead = decoder.read(dst);
Assert.assertEquals(-1, bytesRead);
Assert.assertTrue(decoder.isCompleted());
}
#location 23
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testBasicDecoding() throws Exception {
String s = "5\r\n01234\r\n5\r\n56789\r\n6\r\nabcdef\r\n0\r\n\r\n";
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
ByteBuffer dst = ByteBuffer.allocate(1024);
int bytesRead = decoder.read(dst);
Assert.assertEquals(16, bytesRead);
Assert.assertEquals("0123456789abcdef", convert(dst));
Header[] footers = decoder.getFooters();
Assert.assertEquals(0, footers.length);
dst.clear();
bytesRead = decoder.read(dst);
Assert.assertEquals(-1, bytesRead);
Assert.assertTrue(decoder.isCompleted());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testInvalidInput() throws Exception {
String s = "10;key=\"value\"\r\n1234567890123456\r\n" +
"5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1 abcde\r\n\r\n";
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
try {
decoder.read(null);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testInvalidInput() throws Exception {
String s = "10;key=\"value\"\r\n1234567890123456\r\n" +
"5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1 abcde\r\n\r\n";
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
try {
decoder.read(null);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (IllegalArgumentException ex) {
// expected
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBasicDecodingFile() throws Exception {
final ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {"stuff; ", "more stuff; ", "a lot more stuff!"}, "US-ASCII");
final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII);
final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
final IdentityDecoder decoder = new IdentityDecoder(
channel, inbuf, metrics);
final File fileHandle = File.createTempFile("testFile", ".txt");
final RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
final FileChannel fchannel = testfile.getChannel();
long pos = 0;
while (!decoder.isCompleted()) {
final long bytesRead = decoder.transfer(fchannel, pos, 10);
if (bytesRead > 0) {
pos += bytesRead;
}
}
Assert.assertEquals(testfile.length(), metrics.getBytesTransferred());
fchannel.close();
Assert.assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle));
deleteWithCheck(fileHandle);
}
#location 21
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testBasicDecodingFile() throws Exception {
final ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {"stuff; ", "more stuff; ", "a lot more stuff!"}, "US-ASCII");
final SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, Consts.ASCII);
final HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
final IdentityDecoder decoder = new IdentityDecoder(
channel, inbuf, metrics);
final File fileHandle = File.createTempFile("testFile", ".txt");
final RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
final FileChannel fchannel = testfile.getChannel();
long pos = 0;
while (!decoder.isCompleted()) {
final long bytesRead = decoder.transfer(fchannel, pos, 10);
if (bytesRead > 0) {
pos += bytesRead;
}
}
Assert.assertEquals(testfile.length(), metrics.getBytesTransferred());
fchannel.close();
Assert.assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle));
deleteWithCheck(fileHandle);
testfile.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testComplexDecoding() throws Exception {
String s = "10;key=\"value\"\r\n1234567890123456\r\n" +
"5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\nFooter2: fghij\r\n\r\n";
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
ByteBuffer dst = ByteBuffer.allocate(1024);
int bytesRead = 0;
while (dst.hasRemaining() && !decoder.isCompleted()) {
int i = decoder.read(dst);
if (i > 0) {
bytesRead += i;
}
}
Assert.assertEquals(26, bytesRead);
Assert.assertEquals("12345678901234561234512345", convert(dst));
Header[] footers = decoder.getFooters();
Assert.assertEquals(2, footers.length);
Assert.assertEquals("Footer1", footers[0].getName());
Assert.assertEquals("abcde", footers[0].getValue());
Assert.assertEquals("Footer2", footers[1].getName());
Assert.assertEquals("fghij", footers[1].getValue());
dst.clear();
bytesRead = decoder.read(dst);
Assert.assertEquals(-1, bytesRead);
Assert.assertTrue(decoder.isCompleted());
}
#location 36
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testComplexDecoding() throws Exception {
String s = "10;key=\"value\"\r\n1234567890123456\r\n" +
"5\r\n12345\r\n5\r\n12345\r\n0\r\nFooter1: abcde\r\nFooter2: fghij\r\n\r\n";
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
ByteBuffer dst = ByteBuffer.allocate(1024);
int bytesRead = 0;
while (dst.hasRemaining() && !decoder.isCompleted()) {
int i = decoder.read(dst);
if (i > 0) {
bytesRead += i;
}
}
Assert.assertEquals(26, bytesRead);
Assert.assertEquals("12345678901234561234512345", convert(dst));
Header[] footers = decoder.getFooters();
Assert.assertEquals(2, footers.length);
Assert.assertEquals("Footer1", footers[0].getName());
Assert.assertEquals("abcde", footers[0].getValue());
Assert.assertEquals("Footer2", footers[1].getName());
Assert.assertEquals("fghij", footers[1].getValue());
dst.clear();
bytesRead = decoder.read(dst);
Assert.assertEquals(-1, bytesRead);
Assert.assertTrue(decoder.isCompleted());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String toString(
final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
String charset = getContentCharSet(entity);
if (charset == null) {
charset = defaultCharset;
}
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
instream.close();
}
}
#location 32
#vulnerability type RESOURCE_LEAK | #fixed code
public static String toString(
final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
ContentType contentType = ContentType.getOrDefault(entity);
String charset = contentType.getCharset();
if (charset == null) {
charset = defaultCharset;
}
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
instream.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCodingBeyondContentLimitFile() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {
"stuff;",
"more stuff; and a lot more stuff"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 16);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
long bytesRead = decoder.transfer(fchannel, 0, 6);
Assert.assertEquals(6, bytesRead);
Assert.assertFalse(decoder.isCompleted());
Assert.assertEquals(6, metrics.getBytesTransferred());
bytesRead = decoder.transfer(fchannel,0 , 10);
Assert.assertEquals(10, bytesRead);
Assert.assertTrue(decoder.isCompleted());
Assert.assertEquals(16, metrics.getBytesTransferred());
bytesRead = decoder.transfer(fchannel, 0, 1);
Assert.assertEquals(-1, bytesRead);
Assert.assertTrue(decoder.isCompleted());
Assert.assertEquals(16, metrics.getBytesTransferred());
testfile.close();
deleteWithCheck(fileHandle);
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCodingBeyondContentLimitFile() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {
"stuff;",
"more stuff; and a lot more stuff"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 16);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
long bytesRead = decoder.transfer(fchannel, 0, 6);
Assert.assertEquals(6, bytesRead);
Assert.assertFalse(decoder.isCompleted());
Assert.assertEquals(6, metrics.getBytesTransferred());
bytesRead = decoder.transfer(fchannel,0 , 10);
Assert.assertEquals(10, bytesRead);
Assert.assertTrue(decoder.isCompleted());
Assert.assertEquals(16, metrics.getBytesTransferred());
bytesRead = decoder.transfer(fchannel, 0, 1);
Assert.assertEquals(-1, bytesRead);
Assert.assertTrue(decoder.isCompleted());
Assert.assertEquals(16, metrics.getBytesTransferred());
testfile.close();
deleteWithCheck(fileHandle);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testReadingWitSmallBuffer() throws Exception {
String s = "10\r\n1234567890123456\r\n" +
"40\r\n12345678901234561234567890123456" +
"12345678901234561234567890123456\r\n0\r\n";
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
ByteBuffer dst = ByteBuffer.allocate(1024);
ByteBuffer tmp = ByteBuffer.allocate(10);
int bytesRead = 0;
while (dst.hasRemaining() && !decoder.isCompleted()) {
int i = decoder.read(tmp);
if (i > 0) {
bytesRead += i;
tmp.flip();
dst.put(tmp);
tmp.compact();
}
}
Assert.assertEquals(80, bytesRead);
Assert.assertEquals("12345678901234561234567890123456" +
"12345678901234561234567890123456" +
"1234567890123456", convert(dst));
Assert.assertTrue(decoder.isCompleted());
}
#location 32
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testReadingWitSmallBuffer() throws Exception {
String s = "10\r\n1234567890123456\r\n" +
"40\r\n12345678901234561234567890123456" +
"12345678901234561234567890123456\r\n0\r\n";
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {s}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
ByteBuffer dst = ByteBuffer.allocate(1024);
ByteBuffer tmp = ByteBuffer.allocate(10);
int bytesRead = 0;
while (dst.hasRemaining() && !decoder.isCompleted()) {
int i = decoder.read(tmp);
if (i > 0) {
bytesRead += i;
tmp.flip();
dst.put(tmp);
tmp.compact();
}
}
Assert.assertEquals(80, bytesRead);
Assert.assertEquals("12345678901234561234567890123456" +
"12345678901234561234567890123456" +
"1234567890123456", convert(dst));
Assert.assertTrue(decoder.isCompleted());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void onRequestReceived(final HttpRequest request) throws IOException {
this.request = request;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) this.request).getEntity();
if (entity != null) {
long len = entity.getContentLength();
if (len > Integer.MAX_VALUE) {
throw new ContentTooLongException("Entity content is too long: " + len);
}
if (len < 0) {
len = 4096;
}
this.buf = new SimpleInputBuffer((int) len, HeapByteBufferAllocator.INSTANCE);
((HttpEntityEnclosingRequest) this.request).setEntity(
new ContentBufferEntity(entity, this.buf));
}
}
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
protected void onRequestReceived(final HttpRequest request) throws IOException {
this.request = request;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDecodingWithSmallBuffer() throws Exception {
String s1 = "5\r\n01234\r\n5\r\n5678";
String s2 = "9\r\n6\r\nabcdef\r\n0\r\n\r\n";
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {s1, s2}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
ByteBuffer dst = ByteBuffer.allocate(1024);
ByteBuffer tmp = ByteBuffer.allocate(4);
int bytesRead = 0;
while (dst.hasRemaining() && !decoder.isCompleted()) {
int i = decoder.read(tmp);
if (i > 0) {
bytesRead += i;
}
tmp.flip();
dst.put(tmp);
tmp.compact();
}
Assert.assertEquals(16, bytesRead);
Assert.assertEquals("0123456789abcdef", convert(dst));
Assert.assertTrue(decoder.isCompleted());
dst.clear();
bytesRead = decoder.read(dst);
Assert.assertEquals(-1, bytesRead);
Assert.assertTrue(decoder.isCompleted());
}
#location 29
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testDecodingWithSmallBuffer() throws Exception {
String s1 = "5\r\n01234\r\n5\r\n5678";
String s2 = "9\r\n6\r\nabcdef\r\n0\r\n\r\n";
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {s1, s2}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics);
ByteBuffer dst = ByteBuffer.allocate(1024);
ByteBuffer tmp = ByteBuffer.allocate(4);
int bytesRead = 0;
while (dst.hasRemaining() && !decoder.isCompleted()) {
int i = decoder.read(tmp);
if (i > 0) {
bytesRead += i;
}
tmp.flip();
dst.put(tmp);
tmp.compact();
}
Assert.assertEquals(16, bytesRead);
Assert.assertEquals("0123456789abcdef", convert(dst));
Assert.assertTrue(decoder.isCompleted());
dst.clear();
bytesRead = decoder.read(dst);
Assert.assertEquals(-1, bytesRead);
Assert.assertTrue(decoder.isCompleted());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = MalformedChunkCodingException.class)
public void testCorruptChunkedInputStreamInvalidFooter() throws IOException {
final String s = "1\r\n0\r\n0\r\nstuff\r\n";
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(s, Consts.ISO_8859_1));
in.read();
in.read();
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = MalformedChunkCodingException.class)
public void testCorruptChunkedInputStreamInvalidFooter() throws IOException {
final String s = "1\r\n0\r\n0\r\nstuff\r\n";
final InputStream in = new ChunkedInputStream(
new SessionInputBufferMock(s, Consts.ISO_8859_1));
in.read();
in.read();
in.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntityWithMultipleContentLengthAllWrong() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "yyy");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(-1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertFalse(instream instanceof ContentLengthInputStream);
Assert.assertTrue(instream instanceof IdentityInputStream);
// strict mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true);
try {
entitygen.deserialize(inbuffer, message);
Assert.fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
// expected
}
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntityWithMultipleContentLengthAllWrong() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "yyy");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(-1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertFalse(instream instanceof ContentLengthInputStream);
Assert.assertTrue(instream instanceof IdentityInputStream);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testHttpPostsWithExpectationVerification() throws Exception {
TestJob[] jobs = new TestJob[3];
jobs[0] = new TestJob("AAAAA", 10);
jobs[1] = new TestJob("AAAAA", 10);
jobs[2] = new TestJob("BBBBB", 20);
Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() {
public void verify(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException {
String s = request.getRequestLine().getUri();
if (!s.equals("AAAAAx10")) {
response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED);
NByteArrayEntity outgoing = new NByteArrayEntity(
EncodingUtils.getAsciiBytes("Expectation failed"));
response.setEntity(outgoing);
}
}
};
HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(TestJob testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
NStringEntity entity = null;
try {
entity = new NStringEntity(testjob.getExpected(), "US-ASCII");
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
return r;
}
};
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new TestRequestHandler()));
serviceHandler.setExpectationVerifier(
expectationVerifier);
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < 2; i++) {
TestJob testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(testjob.getExpected(), testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
TestJob failedExpectation = jobs[2];
failedExpectation.waitFor();
assertEquals(HttpStatus.SC_EXPECTATION_FAILED, failedExpectation.getStatusCode());
}
#location 84
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void testHttpPostsWithExpectationVerification() throws Exception {
Job[] jobs = new Job[3];
jobs[0] = new Job("AAAAA", 10);
jobs[1] = new Job("AAAAA", 10);
jobs[2] = new Job("BBBBB", 20);
Queue<Job> queue = new ConcurrentLinkedQueue<Job>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() {
public void verify(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException {
String s = request.getRequestLine().getUri();
if (!s.equals("AAAAAx10")) {
response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED);
NByteArrayEntity outgoing = new NByteArrayEntity(
EncodingUtils.getAsciiBytes("Expectation failed"));
response.setEntity(outgoing);
}
}
};
HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(Job testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
NStringEntity entity = null;
try {
entity = new NStringEntity(testjob.getExpected(), "US-ASCII");
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
return r;
}
};
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new RequestHandler()));
serviceHandler.setExpectationVerifier(
expectationVerifier);
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < 2; i++) {
Job testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(testjob.getExpected(), testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
Job failedExpectation = jobs[2];
failedExpectation.waitFor();
assertEquals(HttpStatus.SC_EXPECTATION_FAILED, failedExpectation.getStatusCode());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
HttpResponse response = null;
BenchmarkConnection conn = new BenchmarkConnection(this.stats);
String scheme = targetHost.getSchemeName();
String hostname = targetHost.getHostName();
int port = targetHost.getPort();
if (port == -1) {
if (scheme.equalsIgnoreCase("https")) {
port = 443;
} else {
port = 80;
}
}
// Populate the execution context
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost);
this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request);
stats.start();
for (int i = 0; i < count; i++) {
try {
resetHeader(request);
if (!conn.isOpen()) {
Socket socket;
if (socketFactory != null) {
socket = socketFactory.createSocket();
} else {
socket = new Socket();
}
HttpParams params = request.getParams();
int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
int soTimeout = HttpConnectionParams.getSoTimeout(params);
socket.setSoTimeout(soTimeout);
socket.connect(new InetSocketAddress(hostname, port), connTimeout);
conn.bind(socket, params);
}
try {
// Prepare request
this.httpexecutor.preProcess(this.request, this.httpProcessor, this.context);
// Execute request and get a response
response = this.httpexecutor.execute(this.request, conn, this.context);
// Finalize response
this.httpexecutor.postProcess(response, this.httpProcessor, this.context);
} catch (HttpException e) {
stats.incWriteErrors();
if (this.verbosity >= 2) {
System.err.println("Failed HTTP request : " + e.getMessage());
}
continue;
}
verboseOutput(response);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
stats.incSuccessCount();
} else {
stats.incFailureCount();
continue;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
ContentType ct = ContentType.get(entity);
Charset charset = ct.getCharset();
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
long contentlen = 0;
InputStream instream = entity.getContent();
int l = 0;
while ((l = instream.read(this.buffer)) != -1) {
contentlen += l;
if (this.verbosity >= 4) {
String s = new String(this.buffer, 0, l, charset.name());
System.out.print(s);
}
}
instream.close();
stats.setContentLength(contentlen);
}
if (this.verbosity >= 4) {
System.out.println();
System.out.println();
}
if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) {
conn.close();
} else {
stats.incKeepAliveCount();
}
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
} catch (Exception ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("Generic error: " + ex.getMessage());
}
}
}
stats.finish();
if (response != null) {
Header header = response.getFirstHeader("Server");
if (header != null) {
stats.setServerName(header.getValue());
}
}
try {
conn.close();
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
}
}
#location 103
#vulnerability type RESOURCE_LEAK | #fixed code
public void run() {
HttpResponse response = null;
BenchmarkConnection conn = new BenchmarkConnection(this.stats);
String scheme = targetHost.getSchemeName();
String hostname = targetHost.getHostName();
int port = targetHost.getPort();
if (port == -1) {
if (scheme.equalsIgnoreCase("https")) {
port = 443;
} else {
port = 80;
}
}
// Populate the execution context
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost);
this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request);
stats.start();
for (int i = 0; i < count; i++) {
try {
resetHeader(request);
if (!conn.isOpen()) {
Socket socket;
if (socketFactory != null) {
socket = socketFactory.createSocket();
} else {
socket = new Socket();
}
HttpParams params = request.getParams();
int connTimeout = params.getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 0);
int soTimeout = params.getIntParameter(CoreConnectionPNames.SO_TIMEOUT, 0);
socket.setSoTimeout(soTimeout);
socket.connect(new InetSocketAddress(hostname, port), connTimeout);
conn.bind(socket, params);
}
try {
// Prepare request
this.httpexecutor.preProcess(this.request, this.httpProcessor, this.context);
// Execute request and get a response
response = this.httpexecutor.execute(this.request, conn, this.context);
// Finalize response
this.httpexecutor.postProcess(response, this.httpProcessor, this.context);
} catch (HttpException e) {
stats.incWriteErrors();
if (this.verbosity >= 2) {
System.err.println("Failed HTTP request : " + e.getMessage());
}
continue;
}
verboseOutput(response);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
stats.incSuccessCount();
} else {
stats.incFailureCount();
continue;
}
HttpEntity entity = response.getEntity();
if (entity != null) {
ContentType ct = ContentType.get(entity);
Charset charset = ct.getCharset();
if (charset == null) {
charset = HTTP.DEF_CONTENT_CHARSET;
}
long contentlen = 0;
InputStream instream = entity.getContent();
int l = 0;
while ((l = instream.read(this.buffer)) != -1) {
contentlen += l;
if (this.verbosity >= 4) {
String s = new String(this.buffer, 0, l, charset.name());
System.out.print(s);
}
}
instream.close();
stats.setContentLength(contentlen);
}
if (this.verbosity >= 4) {
System.out.println();
System.out.println();
}
if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) {
conn.close();
} else {
stats.incKeepAliveCount();
}
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
} catch (Exception ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("Generic error: " + ex.getMessage());
}
}
}
stats.finish();
if (response != null) {
Header header = response.getFirstHeader("Server");
if (header != null) {
stats.setServerName(header.getValue());
}
}
try {
conn.close();
} catch (IOException ex) {
stats.incFailureCount();
if (this.verbosity >= 2) {
System.err.println("I/O error: " + ex.getMessage());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testInputThrottling() throws Exception {
HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() {
public void initalizeContext(final HttpContext context, final Object attachment) {
context.setAttribute("queue", attachment);
}
public HttpRequest submitRequest(final HttpContext context) {
@SuppressWarnings("unchecked")
Queue<TestJob> queue = (Queue<TestJob>) context.getAttribute("queue");
if (queue == null) {
throw new IllegalStateException("Queue is null");
}
TestJob testjob = queue.poll();
context.setAttribute("job", testjob);
if (testjob != null) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
StringEntity entity = null;
try {
entity = new StringEntity(testjob.getExpected(), "US-ASCII");
entity.setChunked(testjob.getCount() % 2 == 0);
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
return r;
} else {
return null;
}
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
TestJob testjob = (TestJob) context.removeAttribute("job");
if (testjob == null) {
throw new IllegalStateException("TestJob is null");
}
int statusCode = response.getStatusLine().getStatusCode();
String content = null;
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
// Simulate slow response handling in order to cause the
// internal content buffer to fill up, forcing the
// protocol handler to throttle input rate
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
InputStream instream = entity.getContent();
byte[] tmp = new byte[2048];
int l;
while((l = instream.read(tmp)) != -1) {
Thread.sleep(1);
outstream.write(tmp, 0, l);
}
content = new String(outstream.toByteArray(),
EntityUtils.getContentCharSet(entity));
} catch (InterruptedException ex) {
content = "Interrupted: " + ex.getMessage();
} catch (IOException ex) {
content = "I/O exception: " + ex.getMessage();
}
}
testjob.setResult(statusCode, content);
}
public void finalizeContext(final HttpContext context) {
TestJob testjob = (TestJob) context.removeAttribute("job");
if (testjob != null) {
testjob.fail("Request failed");
}
}
};
int connNo = 3;
int reqNo = 20;
TestJob[] jobs = new TestJob[connNo * reqNo];
for (int i = 0; i < jobs.length; i++) {
jobs[i] = new TestJob(10000);
}
Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new TestRequestHandler()));
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>();
for (int i = 0; i < connNo; i++) {
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
connRequests.add(sessionRequest);
}
while (!connRequests.isEmpty()) {
SessionRequest sessionRequest = connRequests.remove();
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
}
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < jobs.length; i++) {
TestJob testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(HttpStatus.SC_OK, testjob.getStatusCode());
assertEquals(testjob.getExpected(), testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
}
#location 124
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void testInputThrottling() throws Exception {
HttpRequestExecutionHandler requestExecutionHandler = new HttpRequestExecutionHandler() {
public void initalizeContext(final HttpContext context, final Object attachment) {
context.setAttribute("queue", attachment);
}
public HttpRequest submitRequest(final HttpContext context) {
@SuppressWarnings("unchecked")
Queue<Job> queue = (Queue<Job>) context.getAttribute("queue");
if (queue == null) {
throw new IllegalStateException("Queue is null");
}
Job testjob = queue.poll();
context.setAttribute("job", testjob);
if (testjob != null) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
StringEntity entity = null;
try {
entity = new StringEntity(testjob.getExpected(), "US-ASCII");
entity.setChunked(testjob.getCount() % 2 == 0);
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
return r;
} else {
return null;
}
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
Job testjob = (Job) context.removeAttribute("job");
if (testjob == null) {
throw new IllegalStateException("TestJob is null");
}
int statusCode = response.getStatusLine().getStatusCode();
String content = null;
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
// Simulate slow response handling in order to cause the
// internal content buffer to fill up, forcing the
// protocol handler to throttle input rate
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
InputStream instream = entity.getContent();
byte[] tmp = new byte[2048];
int l;
while((l = instream.read(tmp)) != -1) {
Thread.sleep(1);
outstream.write(tmp, 0, l);
}
content = new String(outstream.toByteArray(),
EntityUtils.getContentCharSet(entity));
} catch (InterruptedException ex) {
content = "Interrupted: " + ex.getMessage();
} catch (IOException ex) {
content = "I/O exception: " + ex.getMessage();
}
}
testjob.setResult(statusCode, content);
}
public void finalizeContext(final HttpContext context) {
Job testjob = (Job) context.removeAttribute("job");
if (testjob != null) {
testjob.fail("Request failed");
}
}
};
int connNo = 3;
int reqNo = 20;
Job[] jobs = new Job[connNo * reqNo];
for (int i = 0; i < jobs.length; i++) {
jobs[i] = new Job(10000);
}
Queue<Job> queue = new ConcurrentLinkedQueue<Job>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new RequestHandler()));
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
Queue<SessionRequest> connRequests = new LinkedList<SessionRequest>();
for (int i = 0; i < connNo; i++) {
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
connRequests.add(sessionRequest);
}
while (!connRequests.isEmpty()) {
SessionRequest sessionRequest = connRequests.remove();
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
}
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < jobs.length; i++) {
Job testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(HttpStatus.SC_OK, testjob.getStatusCode());
assertEquals(testjob.getExpected(), testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntityWithMultipleContentLength() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "1");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertTrue(instream instanceof ContentLengthInputStream);
// strict mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true);
try {
entitygen.deserialize(inbuffer, message);
Assert.fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
// expected
}
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntityWithMultipleContentLength() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "1");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertTrue(instream instanceof ContentLengthInputStream);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTooLongChunkHeader() throws IOException {
final String input = "5; and some very looooong commend\r\n12345\r\n0\r\n";
final InputStream in1 = new ChunkedInputStream(
new SessionInputBufferMock(input, MessageConstraints.DEFAULT, Consts.ISO_8859_1));
final byte[] buffer = new byte[300];
Assert.assertEquals(5, in1.read(buffer));
final InputStream in2 = new ChunkedInputStream(
new SessionInputBufferMock(input, MessageConstraints.lineLen(10), Consts.ISO_8859_1));
try {
in2.read(buffer);
Assert.fail("MessageConstraintException expected");
} catch (MessageConstraintException ex) {
}
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTooLongChunkHeader() throws IOException {
final String input = "5; and some very looooong commend\r\n12345\r\n0\r\n";
final InputStream in1 = new ChunkedInputStream(
new SessionInputBufferMock(input, MessageConstraints.DEFAULT, Consts.ISO_8859_1));
final byte[] buffer = new byte[300];
Assert.assertEquals(5, in1.read(buffer));
in1.close();
final InputStream in2 = new ChunkedInputStream(
new SessionInputBufferMock(input, MessageConstraints.lineLen(10), Consts.ISO_8859_1));
try {
in2.read(buffer);
Assert.fail("MessageConstraintException expected");
} catch (MessageConstraintException ex) {
} finally {
in2.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testWriteBeyondFileSize() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"a"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 1);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
Assert.assertEquals(0, testfile.length());
try {
decoder.transfer(fchannel, 5, 10);
Assert.fail("expected IOException");
} catch(IOException iox) {}
testfile.close();
deleteWithCheck(fileHandle);
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testWriteBeyondFileSize() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMock(
new String[] {"a"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 1);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
Assert.assertEquals(0, testfile.length());
try {
decoder.transfer(fchannel, 5, 10);
Assert.fail("expected IOException");
} catch(IOException iox) {}
testfile.close();
deleteWithCheck(fileHandle);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testCodingBeyondContentLimitFile() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {
"stuff;",
"more stuff; and a lot more stuff"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 16);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
long bytesRead = decoder.transfer(fchannel, 0, 6);
assertEquals(6, bytesRead);
assertFalse(decoder.isCompleted());
bytesRead = decoder.transfer(fchannel,0 , 10);
assertEquals(10, bytesRead);
assertTrue(decoder.isCompleted());
bytesRead = decoder.transfer(fchannel, 0, 1);
assertEquals(-1, bytesRead);
assertTrue(decoder.isCompleted());
fileHandle.delete();
}
#location 23
#vulnerability type RESOURCE_LEAK | #fixed code
public void testCodingBeyondContentLimitFile() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {
"stuff;",
"more stuff; and a lot more stuff"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 16);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
long bytesRead = decoder.transfer(fchannel, 0, 6);
assertEquals(6, bytesRead);
assertFalse(decoder.isCompleted());
assertEquals(6, metrics.getBytesTransferred());
bytesRead = decoder.transfer(fchannel,0 , 10);
assertEquals(10, bytesRead);
assertTrue(decoder.isCompleted());
assertEquals(16, metrics.getBytesTransferred());
bytesRead = decoder.transfer(fchannel, 0, 1);
assertEquals(-1, bytesRead);
assertTrue(decoder.isCompleted());
assertEquals(16, metrics.getBytesTransferred());
fileHandle.delete();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testWriteBeyondFileSize() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"a"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 1);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
assertEquals(0, testfile.length());
try {
decoder.transfer(fchannel, 5, 10);
fail("expected IOException");
} catch(IOException iox) {}
deleteWithCheck(fileHandle);
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
public void testWriteBeyondFileSize() throws Exception {
ReadableByteChannel channel = new ReadableByteChannelMockup(
new String[] {"a"}, "US-ASCII");
HttpParams params = new BasicHttpParams();
SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params);
HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl();
LengthDelimitedDecoder decoder = new LengthDelimitedDecoder(
channel, inbuf, metrics, 1);
File fileHandle = File.createTempFile("testFile", ".txt");
RandomAccessFile testfile = new RandomAccessFile(fileHandle, "rw");
FileChannel fchannel = testfile.getChannel();
assertEquals(0, testfile.length());
try {
decoder.transfer(fchannel, 5, 10);
fail("expected IOException");
} catch(IOException iox) {}
testfile.close();
deleteWithCheck(fileHandle);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void validate(final Set keys) {
long currentTime = System.currentTimeMillis();
if( (currentTime - this.lastTimeoutCheck) >= this.timeoutCheckInterval) {
this.lastTimeoutCheck = currentTime;
if (keys != null) {
for (Iterator it = keys.iterator(); it.hasNext();) {
SelectionKey key = (SelectionKey) it.next();
timeoutCheck(key, currentTime);
}
}
}
synchronized (this.bufferingSessions) {
if (!this.bufferingSessions.isEmpty()) {
for (Iterator it = this.bufferingSessions.iterator(); it.hasNext(); ) {
IOSession session = (IOSession) it.next();
SessionBufferStatus bufStatus = session.getBufferStatus();
if (bufStatus != null) {
if (!bufStatus.hasBufferedInput()) {
it.remove();
continue;
}
}
try {
int ops = session.getEventMask();
if ((ops & EventMask.READ) > 0) {
this.eventDispatch.inputReady(session);
if (bufStatus != null) {
if (!bufStatus.hasBufferedInput()) {
it.remove();
}
}
}
} catch (CancelledKeyException ex) {
it.remove();
}
}
}
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void validate(final Set keys) {
long currentTime = System.currentTimeMillis();
if( (currentTime - this.lastTimeoutCheck) >= this.timeoutCheckInterval) {
this.lastTimeoutCheck = currentTime;
if (keys != null) {
for (Iterator it = keys.iterator(); it.hasNext();) {
SelectionKey key = (SelectionKey) it.next();
timeoutCheck(key, currentTime);
}
}
}
if (!this.bufferingSessions.isEmpty()) {
for (Iterator it = this.bufferingSessions.iterator(); it.hasNext(); ) {
IOSession session = (IOSession) it.next();
SessionBufferStatus bufStatus = session.getBufferStatus();
if (bufStatus != null) {
if (!bufStatus.hasBufferedInput()) {
it.remove();
continue;
}
}
try {
int ops = session.getEventMask();
if ((ops & EventMask.READ) > 0) {
this.eventDispatch.inputReady(session);
if (bufStatus != null) {
if (!bufStatus.hasBufferedInput()) {
it.remove();
}
}
}
} catch (CancelledKeyException ex) {
it.remove();
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public HttpClientConnection create(final HttpHost host) throws IOException {
final String scheme = host.getSchemeName();
Socket socket = null;
if ("http".equalsIgnoreCase(scheme)) {
socket = this.plainfactory != null ? this.plainfactory.createSocket() :
new Socket();
} if ("https".equalsIgnoreCase(scheme)) {
if (this.sslfactory != null) {
socket = this.sslfactory.createSocket();
}
}
if (socket == null) {
throw new IOException(scheme + " scheme is not supported");
}
final String hostname = host.getHostName();
int port = host.getPort();
if (port == -1) {
if (host.getSchemeName().equalsIgnoreCase("http")) {
port = 80;
} else if (host.getSchemeName().equalsIgnoreCase("https")) {
port = 443;
}
}
socket.setSoTimeout(this.sconfig.getSoTimeout());
socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout);
socket.setTcpNoDelay(this.sconfig.isTcpNoDelay());
final int linger = this.sconfig.getSoLinger();
if (linger >= 0) {
socket.setSoLinger(linger > 0, linger);
}
return this.connFactory.createConnection(socket);
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
public HttpClientConnection create(final HttpHost host) throws IOException {
final String scheme = host.getSchemeName();
Socket socket = null;
if ("http".equalsIgnoreCase(scheme)) {
socket = this.plainfactory != null ? this.plainfactory.createSocket() :
new Socket();
} if ("https".equalsIgnoreCase(scheme)) {
socket = (this.sslfactory != null ? this.sslfactory :
SSLSocketFactory.getDefault()).createSocket();
}
if (socket == null) {
throw new IOException(scheme + " scheme is not supported");
}
final String hostname = host.getHostName();
int port = host.getPort();
if (port == -1) {
if (host.getSchemeName().equalsIgnoreCase("http")) {
port = 80;
} else if (host.getSchemeName().equalsIgnoreCase("https")) {
port = 443;
}
}
socket.setSoTimeout(this.sconfig.getSoTimeout());
socket.connect(new InetSocketAddress(hostname, port), this.connectTimeout);
socket.setTcpNoDelay(this.sconfig.isTcpNoDelay());
final int linger = this.sconfig.getSoLinger();
if (linger >= 0) {
socket.setSoLinger(linger > 0, linger);
}
return this.connFactory.createConnection(socket);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Future<BasicNIOPoolEntry> lease(
final HttpHost route,
final Object state) {
int connectTimeout = Config.getInt(params, CoreConnectionPNames.CONNECTION_TIMEOUT, 0);
return super.lease(route, state, connectTimeout, TimeUnit.MILLISECONDS, null);
}
#location 5
#vulnerability type INTERFACE_NOT_THREAD_SAFE | #fixed code
@Override
public Future<BasicNIOPoolEntry> lease(
final HttpHost route,
final Object state) {
return super.lease(route, state, this.connectTimeout, this.tunit, null);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntityWithMultipleContentLengthSomeWrong() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "1");
message.addHeader("Content-Length", "yyy");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertTrue(instream instanceof ContentLengthInputStream);
// strict mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true);
try {
entitygen.deserialize(inbuffer, message);
Assert.fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
// expected
}
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntityWithMultipleContentLengthSomeWrong() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "1");
message.addHeader("Content-Length", "yyy");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertTrue(instream instanceof ContentLengthInputStream);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void doShutdown() throws InterruptedIOException {
if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) {
return;
}
this.status = IOReactorStatus.SHUTTING_DOWN;
try {
cancelRequests();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
this.selector.wakeup();
// Close out all channels
if (this.selector.isOpen()) {
Set<SelectionKey> keys = this.selector.keys();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) {
try {
SelectionKey key = it.next();
Channel channel = key.channel();
if (channel != null) {
channel.close();
}
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Stop dispatching I/O events
try {
this.selector.close();
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Attempt to shut down I/O dispatchers gracefully
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
dispatcher.gracefulShutdown();
}
long gracePeriod = NIOReactorParams.getGracePeriod(this.params);
try {
// Force shut down I/O dispatchers if they fail to terminate
// in time
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) {
dispatcher.awaitShutdown(gracePeriod);
}
if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) {
try {
dispatcher.hardShutdown();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
}
}
// Join worker threads
for (int i = 0; i < this.workerCount; i++) {
Thread t = this.threads[i];
if (t != null) {
t.join(gracePeriod);
}
}
} catch (InterruptedException ex) {
throw new InterruptedIOException(ex.getMessage());
}
}
#location 65
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void doShutdown() throws InterruptedIOException {
synchronized (this.statusLock) {
if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) {
return;
}
this.status = IOReactorStatus.SHUTTING_DOWN;
}
try {
cancelRequests();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
this.selector.wakeup();
// Close out all channels
if (this.selector.isOpen()) {
Set<SelectionKey> keys = this.selector.keys();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) {
try {
SelectionKey key = it.next();
Channel channel = key.channel();
if (channel != null) {
channel.close();
}
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Stop dispatching I/O events
try {
this.selector.close();
} catch (IOException ex) {
addExceptionEvent(ex);
}
}
// Attempt to shut down I/O dispatchers gracefully
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
dispatcher.gracefulShutdown();
}
long gracePeriod = NIOReactorParams.getGracePeriod(this.params);
try {
// Force shut down I/O dispatchers if they fail to terminate
// in time
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) {
dispatcher.awaitShutdown(gracePeriod);
}
if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) {
try {
dispatcher.hardShutdown();
} catch (IOReactorException ex) {
if (ex.getCause() != null) {
addExceptionEvent(ex.getCause());
}
}
}
}
// Join worker threads
for (int i = 0; i < this.workerCount; i++) {
Thread t = this.threads[i];
if (t != null) {
t.join(gracePeriod);
}
}
} catch (InterruptedException ex) {
throw new InterruptedIOException(ex.getMessage());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testHttpPostsWithExpectationVerification() throws Exception {
TestJob[] jobs = new TestJob[3];
jobs[0] = new TestJob("AAAAA", 10);
jobs[1] = new TestJob("AAAAA", 10);
jobs[2] = new TestJob("BBBBB", 20);
Queue<TestJob> queue = new ConcurrentLinkedQueue<TestJob>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() {
public void verify(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException {
String s = request.getRequestLine().getUri();
if (!s.equals("AAAAAx10")) {
response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED);
NByteArrayEntity outgoing = new NByteArrayEntity(
EncodingUtils.getAsciiBytes("Expectation failed"));
response.setEntity(outgoing);
}
}
};
HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(TestJob testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
NStringEntity entity = null;
try {
entity = new NStringEntity(testjob.getExpected(), "US-ASCII");
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
return r;
}
};
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new TestRequestHandler()));
serviceHandler.setExpectationVerifier(
expectationVerifier);
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < 2; i++) {
TestJob testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(testjob.getExpected(), testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
TestJob failedExpectation = jobs[2];
failedExpectation.waitFor();
assertEquals(HttpStatus.SC_EXPECTATION_FAILED, failedExpectation.getStatusCode());
}
#location 87
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void testHttpPostsWithExpectationVerification() throws Exception {
Job[] jobs = new Job[3];
jobs[0] = new Job("AAAAA", 10);
jobs[1] = new Job("AAAAA", 10);
jobs[2] = new Job("BBBBB", 20);
Queue<Job> queue = new ConcurrentLinkedQueue<Job>();
for (int i = 0; i < jobs.length; i++) {
queue.add(jobs[i]);
}
HttpExpectationVerifier expectationVerifier = new HttpExpectationVerifier() {
public void verify(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException {
String s = request.getRequestLine().getUri();
if (!s.equals("AAAAAx10")) {
response.setStatusCode(HttpStatus.SC_EXPECTATION_FAILED);
NByteArrayEntity outgoing = new NByteArrayEntity(
EncodingUtils.getAsciiBytes("Expectation failed"));
response.setEntity(outgoing);
}
}
};
HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() {
@Override
protected HttpRequest generateRequest(Job testjob) {
String s = testjob.getPattern() + "x" + testjob.getCount();
HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", s);
NStringEntity entity = null;
try {
entity = new NStringEntity(testjob.getExpected(), "US-ASCII");
} catch (UnsupportedEncodingException ignore) {
}
r.setEntity(entity);
r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true);
return r;
}
};
HttpProcessor serverHttpProc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
ThrottlingHttpServiceHandler serviceHandler = new ThrottlingHttpServiceHandler(
serverHttpProc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
this.execService,
this.server.getParams());
serviceHandler.setHandlerResolver(
new SimpleHttpRequestHandlerResolver(new RequestHandler()));
serviceHandler.setExpectationVerifier(
expectationVerifier);
serviceHandler.setEventListener(
new SimpleEventListener());
HttpProcessor clientHttpProc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
ThrottlingHttpClientHandler clientHandler = new ThrottlingHttpClientHandler(
clientHttpProc,
requestExecutionHandler,
new DefaultConnectionReuseStrategy(),
this.execService,
this.client.getParams());
clientHandler.setEventListener(
new SimpleEventListener());
this.server.start(serviceHandler);
this.client.start(clientHandler);
ListenerEndpoint endpoint = this.server.getListenerEndpoint();
endpoint.waitFor();
InetSocketAddress serverAddress = (InetSocketAddress) endpoint.getAddress();
assertEquals("Test server status", IOReactorStatus.ACTIVE, this.server.getStatus());
SessionRequest sessionRequest = this.client.openConnection(
new InetSocketAddress("localhost", serverAddress.getPort()),
queue);
sessionRequest.waitFor();
if (sessionRequest.getException() != null) {
throw sessionRequest.getException();
}
assertNotNull(sessionRequest.getSession());
assertEquals("Test client status", IOReactorStatus.ACTIVE, this.client.getStatus());
for (int i = 0; i < 2; i++) {
Job testjob = jobs[i];
testjob.waitFor();
if (testjob.isSuccessful()) {
assertEquals(testjob.getExpected(), testjob.getResult());
} else {
fail(testjob.getFailureMessage());
}
}
Job failedExpectation = jobs[2];
failedExpectation.waitFor();
assertEquals(HttpStatus.SC_EXPECTATION_FAILED, failedExpectation.getStatusCode());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntityWithMultipleContentLengthAllWrong() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "yyy");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(-1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertFalse(instream instanceof ContentLengthInputStream);
Assert.assertTrue(instream instanceof IdentityInputStream);
// strict mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true);
try {
entitygen.deserialize(inbuffer, message);
Assert.fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
// expected
}
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntityWithMultipleContentLengthAllWrong() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "yyy");
message.addHeader("Content-Length", "xxx");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(-1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertFalse(instream instanceof ContentLengthInputStream);
Assert.assertTrue(instream instanceof IdentityInputStream);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testEntityWithMultipleContentLength() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "1");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertTrue(instream instanceof ContentLengthInputStream);
// strict mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, true);
try {
entitygen.deserialize(inbuffer, message);
Assert.fail("ProtocolException should have been thrown");
} catch (ProtocolException ex) {
// expected
}
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testEntityWithMultipleContentLength() throws Exception {
SessionInputBuffer inbuffer = new SessionInputBufferMock(new byte[] {'0'});
HttpMessage message = new DummyHttpMessage();
// lenient mode
message.getParams().setBooleanParameter(CoreProtocolPNames.STRICT_TRANSFER_ENCODING, false);
message.addHeader("Content-Type", "unknown");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "0");
message.addHeader("Content-Length", "1");
EntityDeserializer entitygen = new EntityDeserializer(
new LaxContentLengthStrategy());
HttpEntity entity = entitygen.deserialize(inbuffer, message);
Assert.assertNotNull(entity);
Assert.assertEquals(1, entity.getContentLength());
Assert.assertFalse(entity.isChunked());
InputStream instream = entity.getContent();
Assert.assertNotNull(instream);
Assert.assertTrue(instream instanceof ContentLengthInputStream);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testResponseContentOverwriteHeaders() throws Exception {
ResponseContent interceptor = new ResponseContent(true);
HttpContext context = new BasicHttpContext(null);
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
response.addHeader(new BasicHeader(HTTP.CONTENT_LEN, "10"));
response.addHeader(new BasicHeader(HTTP.TRANSFER_ENCODING, "whatever"));
interceptor.process(response, context);
Assert.assertEquals("0", response.getFirstHeader(HTTP.CONTENT_LEN).getValue());
Assert.assertEquals("whatever", response.getFirstHeader(HTTP.TRANSFER_ENCODING).getValue());
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testResponseContentOverwriteHeaders() throws Exception {
ResponseContent interceptor = new ResponseContent(true);
HttpContext context = new BasicHttpContext(null);
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");
response.addHeader(new BasicHeader(HTTP.CONTENT_LEN, "10"));
response.addHeader(new BasicHeader(HTTP.TRANSFER_ENCODING, "whatever"));
interceptor.process(response, context);
Assert.assertEquals("0", response.getFirstHeader(HTTP.CONTENT_LEN).getValue());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testLoadReleaseConfigDefaultConfigsAndOverrideApp() {
long appId = 6666;
long versionId = 100;
long releaseId = 11111;
VersionDTO someVersion = assembleVersion(appId, "1.0", releaseId);
ReleaseSnapshotDTO[] someReleaseSnapShots = new ReleaseSnapshotDTO[1];
someReleaseSnapShots[0] = assembleReleaseSnapShot(11111, Constants.DEFAULT_CLUSTER_NAME,
"{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\", \"5555.bar\":\"demo2\", \"22.bar\":\"demo2\"}");
when(versionAPI.getVersionById(Env.DEV, versionId)).thenReturn(someVersion);
when(configAPI.getConfigByReleaseId(Env.DEV, releaseId)).thenReturn(someReleaseSnapShots);
AppConfigVO appConfigVO = configService.loadReleaseConfig(Env.DEV, appId, versionId);
assertEquals(appConfigVO.getAppId(), appId);
assertEquals(appConfigVO.getVersionId(), versionId);
assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 2);
assertEquals(2, appConfigVO.getOverrideAppConfigs().size());
assertEquals(appConfigVO.getOverrideClusterConfigs().size(), 0);
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testLoadReleaseConfigDefaultConfigsAndOverrideApp() {
long appId = 6666;
long versionId = 100;
long releaseId = 11111;
VersionDTO someVersion = assembleVersion(appId, "1.0", releaseId);
ReleaseSnapshotDTO[] someReleaseSnapShots = new ReleaseSnapshotDTO[1];
someReleaseSnapShots[0] = assembleReleaseSnapShot(11111, ConfigConsts.DEFAULT_CLUSTER_NAME,
"{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\", \"5555.bar\":\"demo2\", \"22.bar\":\"demo2\"}");
when(versionAPI.getVersionById(Env.DEV, versionId)).thenReturn(someVersion);
when(configAPI.getConfigByReleaseId(Env.DEV, releaseId)).thenReturn(someReleaseSnapShots);
AppConfigVO appConfigVO = configService.loadReleaseConfig(Env.DEV, appId, versionId);
assertEquals(appConfigVO.getAppId(), appId);
assertEquals(appConfigVO.getVersionId(), versionId);
assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 2);
assertEquals(2, appConfigVO.getOverrideAppConfigs().size());
assertEquals(appConfigVO.getOverrideClusterConfigs().size(), 0);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private boolean isServiceUndeployed(int environmentId, int serviceId){
Date latestDeploymentDate = getLatestDeploymentDateByServiceIdInEnvironment(environmentId, serviceId);
Date latestUpdatedDate = getLatestDeployableVersionDateByServiceId(serviceId);
if(latestDeploymentDate != null) {
long diffBetweenDatesInDays = TimeUnit.DAYS.convert(Math.abs(latestDeploymentDate.getTime() - latestUpdatedDate.getTime()), TimeUnit.MILLISECONDS);
return diffBetweenDatesInDays > MIN_DAYS_OF_UNDEPLOYED_SERVICES ? true : false;
}
if(latestUpdatedDate != null) {
Date durationSinceLatestUpdate = Date.from(LocalDate.now().minusDays((long) MIN_DAYS_OF_UNDEPLOYED_SERVICES).atStartOfDay(ZoneId.systemDefault()).toInstant());
if(latestUpdatedDate.compareTo(durationSinceLatestUpdate) < 0) {
return true;
}
}
return false;
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
private boolean isServiceUndeployed(int environmentId, int serviceId){
Date latestDeploymentDate = getLatestDeploymentDateByServiceIdInEnvironment(environmentId, serviceId);
Date latestUpdatedDate = getLatestDeployableVersionDateByServiceId(serviceId);
if(latestDeploymentDate != null) {
long diffBetweenDatesInDays = getTimeDiffInDays(latestDeploymentDate, latestUpdatedDate);
return diffBetweenDatesInDays > MAX_DAYS_OF_UNDEPLOYED_SERVICES ? true : false;
}
if(latestUpdatedDate != null) {
Date maxDateSinceLatestUpdate = getMaxDateSinceLatestUpdate();
if(latestUpdatedDate.compareTo(maxDateSinceLatestUpdate) < 0) {
return true;
}
}
return false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testLoadReleaseConfigDefaultConfigsAndOverrideCluster() {
long appId = 6666;
long versionId = 100;
long releaseId = 11111;
VersionDTO someVersion = assembleVersion(appId, "1.0", releaseId);
ReleaseSnapshotDTO[] someReleaseSnapShots = new ReleaseSnapshotDTO[2];
someReleaseSnapShots[0] = assembleReleaseSnapShot(11111, Constants.DEFAULT_CLUSTER_NAME,
"{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\"}");
someReleaseSnapShots[1] = assembleReleaseSnapShot(11112, "cluster1",
"{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\"}");
when(versionAPI.getVersionById(Env.DEV, versionId)).thenReturn(someVersion);
when(configAPI.getConfigByReleaseId(Env.DEV, releaseId)).thenReturn(someReleaseSnapShots);
AppConfigVO appConfigVO = configService.loadReleaseConfig(Env.DEV, appId, versionId);
assertEquals(appConfigVO.getAppId(), appId);
assertEquals(appConfigVO.getVersionId(), versionId);
assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 2);
assertEquals(0, appConfigVO.getOverrideAppConfigs().size());
assertEquals(1, appConfigVO.getOverrideClusterConfigs().size());
}
#location 18
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testLoadReleaseConfigDefaultConfigsAndOverrideCluster() {
long appId = 6666;
long versionId = 100;
long releaseId = 11111;
VersionDTO someVersion = assembleVersion(appId, "1.0", releaseId);
ReleaseSnapshotDTO[] someReleaseSnapShots = new ReleaseSnapshotDTO[2];
someReleaseSnapShots[0] = assembleReleaseSnapShot(11111, ConfigConsts.DEFAULT_CLUSTER_NAME,
"{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\"}");
someReleaseSnapShots[1] = assembleReleaseSnapShot(11112, "cluster1",
"{\"6666.foo\":\"demo1\", \"6666.bar\":\"demo2\"}");
when(versionAPI.getVersionById(Env.DEV, versionId)).thenReturn(someVersion);
when(configAPI.getConfigByReleaseId(Env.DEV, releaseId)).thenReturn(someReleaseSnapShots);
AppConfigVO appConfigVO = configService.loadReleaseConfig(Env.DEV, appId, versionId);
assertEquals(appConfigVO.getAppId(), appId);
assertEquals(appConfigVO.getVersionId(), versionId);
assertEquals(appConfigVO.getDefaultClusterConfigs().size(), 2);
assertEquals(0, appConfigVO.getOverrideAppConfigs().size());
assertEquals(1, appConfigVO.getOverrideClusterConfigs().size());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testBlockByAvailabilityOnAllServices() throws Exception {
ApolloTestClient apolloTestClient = Common.signupAndLogin();
ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient();
String availability = "BLOCK-ME-2";
Environment environment = ModelsGenerator.createAndSubmitEnvironment(availability, apolloTestClient);
Service service = ModelsGenerator.createAndSubmitService(apolloTestClient);
createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, null, null, availability);
DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service);
assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion)).isInstanceOf(Exception.class)
.hasMessageContaining("Deployment is currently blocked");
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testBlockByAvailabilityOnAllServices() throws Exception {
ApolloTestClient apolloTestClient = Common.signupAndLogin();
ApolloTestAdminClient apolloTestAdminClient = Common.getAndLoginApolloTestAdminClient();
String availability = "BLOCK-ME-2";
Environment blockedEnvironment = ModelsGenerator.createAndSubmitEnvironment(availability, apolloTestClient);
Environment environment = ModelsGenerator.createAndSubmitEnvironment(apolloTestClient);
Service service = ModelsGenerator.createAndSubmitService(apolloTestClient);
DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service);
ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion);
createAndSubmitBlocker(apolloTestAdminClient, "unconditional", "{}", null, null, null, availability);
assertThatThrownBy(() -> ModelsGenerator.createAndSubmitDeployment(apolloTestClient, blockedEnvironment, service, deployableVersion)).isInstanceOf(Exception.class)
.hasMessageContaining("Deployment is currently blocked");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void onWhenRequested() throws Exception {
setup("server.port=7000", "spring.cloud.config.discovery.enabled=true",
"spring.cloud.consul.discovery.port:7001",
"spring.cloud.consul.discovery.hostname:foo",
"spring.cloud.config.discovery.service-id:configserver");
assertEquals( 1, this.context
.getBeanNamesForType(ConsulConfigServerAutoConfiguration.class).length);
ConsulDiscoveryClient client = this.context.getParent().getBean(
ConsulDiscoveryClient.class);
verify(client, atLeast(2)).getInstances("configserver");
ConfigClientProperties locator = this.context
.getBean(ConfigClientProperties.class);
assertEquals("http://foo:7001/", locator.getUri()[0]);
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void onWhenRequested() throws Exception {
setup("server.port=0", "spring.cloud.config.discovery.enabled=true",
"logging.level.org.springframework.cloud.config.client=DEBUG",
"spring.cloud.consul.discovery.test.enabled:true",
"spring.application.name=discoveryclientconfigservicetest",
"spring.cloud.consul.discovery.port:7001",
"spring.cloud.consul.discovery.hostname:foo",
"spring.cloud.config.discovery.service-id:configserver");
assertEquals( 1, this.context
.getBeanNamesForType(ConsulConfigServerAutoConfiguration.class).length);
ConsulDiscoveryClient client = this.context.getParent().getBean(
ConsulDiscoveryClient.class);
verify(client, atLeast(2)).getInstances("configserver");
ConfigClientProperties locator = this.context
.getBean(ConfigClientProperties.class);
assertEquals("http://foo:7001/", locator.getUri()[0]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void propertySourcesFound() throws Exception {
String foo = this.environment.getProperty("foo");
assertThat(foo).as("foo was wrong").isEqualTo("bar-app-dev");
String myBaz = this.environment.getProperty("my.baz");
assertThat(myBaz).as("my.baz was wrong").isEqualTo("bar-app-dev");
MutablePropertySources propertySources = this.environment.getPropertySources();
PropertySource<?> bootstrapProperties = propertySources
.get("bootstrapProperties");
assertThat(bootstrapProperties).as("bootstrapProperties was null").isNotNull();
assertThat(bootstrapProperties.getClass())
.as("bootstrapProperties was wrong type")
.isInstanceOf(CompositePropertySource.class);
Collection<PropertySource<?>> consulSources = ((CompositePropertySource) bootstrapProperties)
.getPropertySources();
assertThat(consulSources).as("consulSources was wrong size").hasSize(1);
PropertySource<?> consulSource = consulSources.iterator().next();
assertThat(consulSource.getClass()).as("consulSource was wrong type")
.isInstanceOf(CompositePropertySource.class);
Collection<PropertySource<?>> fileSources = ((CompositePropertySource) consulSource)
.getPropertySources();
assertThat(fileSources).as("fileSources was wrong size").hasSize(4);
assertFileSourceNames(fileSources, APP_NAME_DEV_PROPS, APP_NAME_PROPS,
APPLICATION_DEV_YML, APPLICATION_YML);
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void propertySourcesFound() throws Exception {
String foo = this.environment.getProperty("foo");
assertThat(foo).as("foo was wrong").isEqualTo("bar-app-dev");
String myBaz = this.environment.getProperty("my.baz");
assertThat(myBaz).as("my.baz was wrong").isEqualTo("bar-app-dev");
MutablePropertySources propertySources = this.environment.getPropertySources();
PropertySource<?> bootstrapProperties = propertySources
.get("bootstrapProperties");
assertThat(bootstrapProperties).as("bootstrapProperties was null").isNotNull();
assertThat(bootstrapProperties).as("bootstrapProperties was wrong type")
.isInstanceOf(CompositePropertySource.class);
Collection<PropertySource<?>> consulSources = ((CompositePropertySource) bootstrapProperties)
.getPropertySources();
assertThat(consulSources).as("consulSources was wrong size").hasSize(1);
PropertySource<?> consulSource = consulSources.iterator().next();
assertThat(consulSource).as("consulSource was wrong type")
.isInstanceOf(CompositePropertySource.class);
Collection<PropertySource<?>> fileSources = ((CompositePropertySource) consulSource)
.getPropertySources();
assertThat(fileSources).as("fileSources was wrong size").hasSize(4);
assertFileSourceNames(fileSources, APP_NAME_DEV_PROPS, APP_NAME_PROPS,
APPLICATION_DEV_YML, APPLICATION_YML);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public <T> T get(Class<? extends T> clazz, long id) throws EntityNotFoundException
{
// The cast gets rid of "no unique maximal instance exists" compiler error
return (T)this.get(this.factory.createKey(clazz, id));
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public <T> T get(Class<? extends T> clazz, long id) throws EntityNotFoundException
{
// The cast gets rid of "no unique maximal instance exists" compiler error
return (T)this.get(new OKey<T>(clazz, id));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public <T> T get(Class<? extends T> clazz, String name) throws EntityNotFoundException
{
// The cast gets rid of "no unique maximal instance exists" compiler error
return (T)this.get(this.factory.createKey(clazz, name));
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public <T> T get(Class<? extends T> clazz, String name) throws EntityNotFoundException
{
// The cast gets rid of "no unique maximal instance exists" compiler error
return (T)this.get(new OKey<T>(clazz, name));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void tooDeeplyNestedObjects() throws IOException {
Object root = Boolean.TRUE;
for (int i = 0; i < 32; i++) {
root = singletonMap("a", root);
}
JsonReader reader = new JsonValueReader(root);
for (int i = 0; i < 31; i++) {
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
}
try {
reader.beginObject();
fail();
} catch (JsonDataException expected) {
assertThat(expected).hasMessage(
"Nesting too deep at $.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.a.");
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void tooDeeplyNestedObjects() throws IOException {
Object root = Boolean.TRUE;
for (int i = 0; i < MAX_DEPTH + 1; i++) {
root = singletonMap("a", root);
}
JsonReader reader = new JsonValueReader(root);
for (int i = 0; i < MAX_DEPTH; i++) {
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
}
try {
reader.beginObject();
fail();
} catch (JsonDataException expected) {
assertThat(expected).hasMessage("Nesting too deep at $" + repeat(".a", MAX_DEPTH) + ".");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerNullValue() throws Exception {
JsonReader reader = newReader("{\"null\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.null");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
try {
reader.nextNull();
fail();
} catch (JsonDataException e) {
assertThat(e).hasMessage("Expected null but was STRING at path $.null");
}
assertThat(reader.nextString()).isEqualTo("null");
assertThat(reader.getPath()).isEqualTo("$.null");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.null");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerNullValue() throws Exception {
JsonReader reader = factory.newReader("{\"null\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.null");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
try {
reader.nextNull();
fail();
} catch (JsonDataException e) {
assertThat(e.getMessage()).isIn(
"Expected NULL but was null, a java.lang.String, at path $.null",
"Expected null but was STRING at path $.null");
}
assertThat(reader.nextString()).isEqualTo("null");
assertThat(reader.getPath()).isEqualTo("$.null");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.null");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readingDoesNotBuffer() throws IOException {
Buffer buffer = new Buffer().writeUtf8("{}{}");
JsonReader reader1 = new JsonReader(buffer);
reader1.beginObject();
reader1.endObject();
assertThat(buffer.size()).isEqualTo(2);
JsonReader reader2 = new JsonReader(buffer);
reader2.beginObject();
reader2.endObject();
assertThat(buffer.size()).isEqualTo(0);
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readingDoesNotBuffer() throws IOException {
Buffer buffer = new Buffer().writeUtf8("{}{}");
JsonReader reader1 = JsonReader.of(buffer);
reader1.beginObject();
reader1.endObject();
assertThat(buffer.size()).isEqualTo(2);
JsonReader reader2 = JsonReader.of(buffer);
reader2.beginObject();
reader2.endObject();
assertThat(buffer.size()).isEqualTo(0);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readObjectSource() throws IOException {
Buffer buffer = new Buffer().writeUtf8("{\"a\": \"android\", \"b\": \"banana\"}");
JsonReader reader = new JsonReader(buffer);
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
assertThat(reader.nextString()).isEqualTo("android");
assertThat(reader.nextName()).isEqualTo("b");
assertThat(reader.nextString()).isEqualTo("banana");
reader.endObject();
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readObjectSource() throws IOException {
Buffer buffer = new Buffer().writeUtf8("{\"a\": \"android\", \"b\": \"banana\"}");
JsonReader reader = JsonReader.of(buffer);
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
assertThat(reader.nextString()).isEqualTo("android");
assertThat(reader.nextName()).isEqualTo("b");
assertThat(reader.nextString()).isEqualTo("banana");
reader.endObject();
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerUnusedPromotionDoesntPersist() throws Exception {
JsonReader reader = new JsonReader(new Buffer().writeUtf8("[{},{\"a\":5}]"));
reader.beginArray();
reader.beginObject();
reader.promoteNameToValue();
reader.endObject();
reader.beginObject();
try {
reader.nextString();
fail();
} catch (JsonDataException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerUnusedPromotionDoesntPersist() throws Exception {
JsonReader reader = newReader("[{},{\"a\":5}]");
reader.beginArray();
reader.beginObject();
reader.promoteNameToValue();
reader.endObject();
reader.beginObject();
try {
reader.nextString();
fail();
} catch (JsonDataException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerLongValue() throws Exception {
JsonReader reader = newReader("{\"5\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextLong()).isEqualTo(5L);
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.5");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerLongValue() throws Exception {
JsonReader reader = factory.newReader("{\"5\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextLong()).isEqualTo(5L);
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.5");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readObjectBuffer() throws IOException {
Buffer buffer = new Buffer().writeUtf8("{\"a\": \"android\", \"b\": \"banana\"}");
JsonReader reader = new JsonReader(buffer);
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
assertThat(reader.nextString()).isEqualTo("android");
assertThat(reader.nextName()).isEqualTo("b");
assertThat(reader.nextString()).isEqualTo("banana");
reader.endObject();
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readObjectBuffer() throws IOException {
Buffer buffer = new Buffer().writeUtf8("{\"a\": \"android\", \"b\": \"banana\"}");
JsonReader reader = JsonReader.of(buffer);
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
assertThat(reader.nextString()).isEqualTo("android");
assertThat(reader.nextName()).isEqualTo("b");
assertThat(reader.nextString()).isEqualTo("banana");
reader.endObject();
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerBooleanValue() throws Exception {
JsonReader reader = newReader("{\"true\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.true");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
try {
reader.nextBoolean();
fail();
} catch (JsonDataException e) {
assertThat(e).hasMessage("Expected a boolean but was STRING at path $.true");
}
assertThat(reader.getPath()).isEqualTo("$.true");
assertThat(reader.nextString()).isEqualTo("true");
assertThat(reader.getPath()).isEqualTo("$.true");
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerBooleanValue() throws Exception {
JsonReader reader = factory.newReader("{\"true\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.true");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
try {
reader.nextBoolean();
fail();
} catch (JsonDataException e) {
assertThat(e.getMessage()).isIn(
"Expected BOOLEAN but was true, a java.lang.String, at path $.true",
"Expected a boolean but was STRING at path $.true");
}
assertThat(reader.getPath()).isEqualTo("$.true");
assertThat(reader.nextString()).isEqualTo("true");
assertThat(reader.getPath()).isEqualTo("$.true");
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerUnquotedDoubleValue() throws Exception {
JsonReader reader = newReader("{5:1}");
reader.setLenient(true);
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.nextDouble()).isEqualTo(5d);
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerUnquotedDoubleValue() throws Exception {
JsonReader reader = factory.newReader("{5:1}");
reader.setLenient(true);
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.nextDouble()).isEqualTo(5d);
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerMultipleValueObject() throws Exception {
JsonReader reader = newReader("{\"a\":1,\"b\":2}");
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
assertThat(reader.nextInt()).isEqualTo(1);
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.b");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextString()).isEqualTo("b");
assertThat(reader.getPath()).isEqualTo("$.b");
assertThat(reader.nextInt()).isEqualTo(2);
assertThat(reader.getPath()).isEqualTo("$.b");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerMultipleValueObject() throws Exception {
JsonReader reader = factory.newReader("{\"a\":1,\"b\":2}");
reader.beginObject();
assertThat(reader.nextName()).isEqualTo("a");
assertThat(reader.nextInt()).isEqualTo(1);
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.b");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextString()).isEqualTo("b");
assertThat(reader.getPath()).isEqualTo("$.b");
assertThat(reader.nextInt()).isEqualTo(2);
assertThat(reader.getPath()).isEqualTo("$.b");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerUnquotedIntegerValue() throws Exception {
JsonReader reader = newReader("{5:1}");
reader.setLenient(true);
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.nextInt()).isEqualTo(5);
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerUnquotedIntegerValue() throws Exception {
JsonReader reader = factory.newReader("{5:1}");
reader.setLenient(true);
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.nextInt()).isEqualTo(5);
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerStringValue() throws Exception {
JsonReader reader = newReader("{\"a\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.a");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextString()).isEqualTo("a");
assertThat(reader.getPath()).isEqualTo("$.a");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.a");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerStringValue() throws Exception {
JsonReader reader = factory.newReader("{\"a\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.a");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextString()).isEqualTo("a");
assertThat(reader.getPath()).isEqualTo("$.a");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.a");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static JsonWriter of(BufferedSink sink) {
return new JsonUt8Writer(sink);
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public static JsonWriter of(BufferedSink sink) {
return new JsonUtf8Writer(sink);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerEmptyValueObject() throws Exception {
JsonReader reader = newReader("{}");
reader.beginObject();
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_OBJECT);
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerEmptyValueObject() throws Exception {
JsonReader reader = factory.newReader("{}");
reader.beginObject();
assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_OBJECT);
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerUnquotedLongValue() throws Exception {
JsonReader reader = newReader("{5:1}");
reader.setLenient(true);
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.nextLong()).isEqualTo(5L);
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerUnquotedLongValue() throws Exception {
JsonReader reader = factory.newReader("{5:1}");
reader.setLenient(true);
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.nextLong()).isEqualTo(5L);
assertThat(reader.nextInt()).isEqualTo(1);
reader.endObject();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerDoubleValue() throws Exception {
JsonReader reader = newReader("{\"5.5\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.5.5");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextDouble()).isEqualTo(5.5d);
assertThat(reader.getPath()).isEqualTo("$.5.5");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.5.5");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerDoubleValue() throws Exception {
JsonReader reader = factory.newReader("{\"5.5\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.5.5");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextDouble()).isEqualTo(5.5d);
assertThat(reader.getPath()).isEqualTo("$.5.5");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.5.5");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override void promoteNameToValue() throws IOException {
Map.Entry<?, ?> peeked = require(Map.Entry.class, Token.NAME);
push(peeked.getKey());
stack[stackSize - 2] = peeked.getValue();
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override void promoteNameToValue() throws IOException {
if (hasNext()) {
String name = nextName();
push(name);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static JsonWriter of(BufferedSink sink) {
return new BufferedSinkJsonWriter(sink);
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public static JsonWriter of(BufferedSink sink) {
return new JsonUt8Writer(sink);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerUnusedPromotionDoesntPersist() throws Exception {
JsonReader reader = newReader("[{},{\"a\":5}]");
reader.beginArray();
reader.beginObject();
reader.promoteNameToValue();
reader.endObject();
reader.beginObject();
try {
reader.nextString();
fail();
} catch (JsonDataException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerUnusedPromotionDoesntPersist() throws Exception {
JsonReader reader = factory.newReader("[{},{\"a\":5}]");
reader.beginArray();
reader.beginObject();
reader.promoteNameToValue();
reader.endObject();
reader.beginObject();
try {
reader.nextString();
fail();
} catch (JsonDataException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerIntegerValue() throws Exception {
JsonReader reader = newReader("{\"5\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextInt()).isEqualTo(5);
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.5");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerIntegerValue() throws Exception {
JsonReader reader = factory.newReader("{\"5\":1}");
reader.beginObject();
reader.promoteNameToValue();
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.peek()).isEqualTo(JsonReader.Token.STRING);
assertThat(reader.nextInt()).isEqualTo(5);
assertThat(reader.getPath()).isEqualTo("$.5");
assertThat(reader.nextInt()).isEqualTo(1);
assertThat(reader.getPath()).isEqualTo("$.5");
reader.endObject();
assertThat(reader.getPath()).isEqualTo("$");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static JsonReader of(BufferedSource source) {
return new BufferedSourceJsonReader(source);
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public static JsonReader of(BufferedSource source) {
return new JsonUtf8Reader(source);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void readerUnusedPromotionDoesntPersist() throws Exception {
JsonReader reader = new JsonReader(new Buffer().writeUtf8("[{},{\"a\":5}]"));
reader.beginArray();
reader.beginObject();
reader.promoteNameToValue();
reader.endObject();
reader.beginObject();
try {
reader.nextString();
fail();
} catch (JsonDataException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void readerUnusedPromotionDoesntPersist() throws Exception {
JsonReader reader = newReader("[{},{\"a\":5}]");
reader.beginArray();
reader.beginObject();
reader.promoteNameToValue();
reader.endObject();
reader.beginObject();
try {
reader.nextString();
fail();
} catch (JsonDataException expected) {
}
assertThat(reader.nextName()).isEqualTo("a");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean addOrReplace(byte[] key, V old, V value)
{
KeyBuffer keyBuffer = keySource(key);
byte[] data = value(value);
byte[] oldData = value(old);
if (maxEntrySize > 0L && CheckSegment.sizeOf(keyBuffer, data) > maxEntrySize)
{
remove(key);
putFailCount++;
return false;
}
CheckSegment segment = segment(keyBuffer.hash());
return segment.put(keyBuffer, data, false, oldData);
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
public boolean addOrReplace(byte[] key, V old, V value)
{
KeyBuffer keyBuffer = keySource(key);
byte[] data = value(value);
byte[] oldData = value(old);
CheckSegment segment = segment(keyBuffer.hash());
return segment.put(keyBuffer, data, false, oldData);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
FileChannel getWriteChannel() {
return writeChannel;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
long getWriteOffset() {
return writeOffset;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDeleteAndMerge() throws Exception {
String directory = "/tmp/HaloDBDeletionTest/testDeleteAndMerge";
HaloDBOptions options = new HaloDBOptions();
options.mergeJobIntervalInSeconds = 1;
options.maxFileSize = 10 * 1024;
options.mergeThresholdPerFile = 0.10;
HaloDB db = getTestDB(directory, options);
int noOfRecords = 10_000;
List<Record> records = TestUtils.insertRandomRecords(db, noOfRecords);
// delete records
Random random = new Random();
Set<Integer> deleted = new HashSet<>();
List<byte[]> newRecords = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
int index = random.nextInt(records.size());
db.delete(records.get(index).getKey());
deleted.add(index);
// also throw in some new records into to mix.
// size is 40 so that we create keys distinct from
// what we used before.
byte[] key = TestUtils.generateRandomByteArray(40);
db.put(key, TestUtils.generateRandomByteArray());
newRecords.add(key);
}
// update the new records to make sure the the files containing tombstones
// will be compacted.
for (byte[] key : newRecords) {
db.put(key, TestUtils.generateRandomByteArray());
}
TestUtils.waitForMergeToComplete(db);
db.close();
db = getTestDBWithoutDeletingFiles(directory, options);
for (int i = 0; i < records.size(); i++) {
byte[] actual = db.get(records.get(i).getKey());
if (deleted.contains(i)) {
Assert.assertNull(actual);
}
else {
Assert.assertEquals(records.get(i).getValue(), actual);
}
}
}
#location 41
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testDeleteAndMerge() throws Exception {
String directory = "/tmp/HaloDBDeletionTest/testDeleteAndMerge";
HaloDBOptions options = new HaloDBOptions();
options.maxFileSize = 10 * 1024;
options.mergeThresholdPerFile = 0.10;
HaloDB db = getTestDB(directory, options);
int noOfRecords = 10_000;
List<Record> records = TestUtils.insertRandomRecords(db, noOfRecords);
// delete records
Random random = new Random();
Set<Integer> deleted = new HashSet<>();
List<byte[]> newRecords = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
int index = random.nextInt(records.size());
db.delete(records.get(index).getKey());
deleted.add(index);
// also throw in some new records into to mix.
// size is 40 so that we create keys distinct from
// what we used before.
byte[] key = TestUtils.generateRandomByteArray(40);
db.put(key, TestUtils.generateRandomByteArray());
newRecords.add(key);
}
// update the new records to make sure the the files containing tombstones
// will be compacted.
for (byte[] key : newRecords) {
db.put(key, TestUtils.generateRandomByteArray());
}
TestUtils.waitForMergeToComplete(db);
db.close();
db = getTestDBWithoutDeletingFiles(directory, options);
for (int i = 0; i < records.size(); i++) {
byte[] actual = db.get(records.get(i).getKey());
if (deleted.contains(i)) {
Assert.assertNull(actual);
}
else {
Assert.assertEquals(records.get(i).getValue(), actual);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testMerge() throws Exception {
File directory = new File("/tmp/HaloDBTestWithMerge/testMerge");
TestUtils.deleteDirectory(directory);
HaloDBOptions options = new HaloDBOptions();
options.maxFileSize = recordsPerFile * recordSize;
options.mergeThresholdPerFile = 0.5;
options.mergeThresholdFileNumber = 4;
options.isMergeDisabled = false;
options.mergeJobIntervalInSeconds = 2;
options.flushDataSizeBytes = 2048;
HaloDB db = HaloDB.open(directory, options);
Record[] records = insertAndUpdateRecords(numberOfRecords, db);
// wait for the merge jobs to complete.
Thread.sleep(10000);
Map<Long, List<Path>> map = Files.list(directory.toPath())
.filter(path -> HaloDBInternal.DATA_FILE_PATTERN.matcher(path.getFileName().toString()).matches())
.collect(Collectors.groupingBy(path -> path.toFile().length()));
// 4 data files of size 10K.
Assert.assertEquals(map.get(10 * 1024l).size(), 4);
//2 merged data files of size 20K.
Assert.assertEquals(map.get(20 * 1024l).size(), 2);
int sizeOfIndexEntry = IndexFileEntry.INDEX_FILE_HEADER_SIZE + 8;
Map<Long, List<Path>> indexFileSizemap = Files.list(directory.toPath())
.filter(path -> HaloDBInternal.INDEX_FILE_PATTERN.matcher(path.getFileName().toString()).matches())
.collect(Collectors.groupingBy(path -> path.toFile().length()));
// 4 index files of size 220 bytes.
Assert.assertEquals(indexFileSizemap.get(sizeOfIndexEntry * 10l).size(), 4);
// 2 index files of size 440 bytes.
Assert.assertEquals(indexFileSizemap.get(sizeOfIndexEntry * 20l).size(), 2);
for (Record r : records) {
byte[] actual = db.get(r.getKey());
Assert.assertArrayEquals(actual, r.getValue());
}
db.close();
TestUtils.deleteDirectory(directory);
}
#location 45
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testMerge() throws Exception {
File directory = new File("/tmp/HaloDBTestWithMerge/testMerge");
TestUtils.deleteDirectory(directory);
HaloDBOptions options = new HaloDBOptions();
options.maxFileSize = recordsPerFile * recordSize;
options.mergeThresholdPerFile = 0.5;
options.mergeThresholdFileNumber = 4;
options.isMergeDisabled = false;
options.mergeJobIntervalInSeconds = 2;
options.flushDataSizeBytes = 2048;
HaloDB db = HaloDB.open(directory, options);
Record[] records = insertAndUpdateRecords(numberOfRecords, db);
// wait for the merge jobs to complete.
Thread.sleep(10000);
Map<Long, List<Path>> map = Files.list(directory.toPath())
.filter(path -> HaloDBInternal.DATA_FILE_PATTERN.matcher(path.getFileName().toString()).matches())
.collect(Collectors.groupingBy(path -> path.toFile().length()));
// 4 data files of size 10K.
Assert.assertEquals(map.get(10 * 1024l).size(), 4);
//2 merged data files of size 20K.
Assert.assertEquals(map.get(20 * 1024l).size(), 2);
int sizeOfIndexEntry = IndexFileEntry.INDEX_FILE_HEADER_SIZE + 8;
Map<Long, List<Path>> indexFileSizemap = Files.list(directory.toPath())
.filter(path -> HaloDBInternal.INDEX_FILE_PATTERN.matcher(path.getFileName().toString()).matches())
.collect(Collectors.groupingBy(path -> path.toFile().length()));
// 4 index files of size 220 bytes.
Assert.assertEquals(indexFileSizemap.get(sizeOfIndexEntry * 10l).size(), 4);
// 2 index files of size 440 bytes.
Assert.assertEquals(indexFileSizemap.get(sizeOfIndexEntry * 20l).size(), 2);
for (Record r : records) {
byte[] actual = db.get(r.getKey());
Assert.assertArrayEquals("key -> " + Utils.bytesToLong(r.getKey()), actual, r.getValue());
}
db.close();
TestUtils.deleteDirectory(directory);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean put(byte[] key, V value)
{
KeyBuffer keyBuffer = keySource(key);
byte[] data = value(value);
if (maxEntrySize > 0L && CheckSegment.sizeOf(keyBuffer, data) > maxEntrySize)
{
remove(key);
putFailCount++;
return false;
}
CheckSegment segment = segment(keyBuffer.hash());
return segment.put(keyBuffer, data, false, null);
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
public boolean put(byte[] key, V value)
{
KeyBuffer keyBuffer = keySource(key);
byte[] data = value(value);
CheckSegment segment = segment(keyBuffer.hash());
return segment.put(keyBuffer, data, false, null);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDeleteInsertCloseAndOpen() throws IOException {
String directory = "/tmp/HaloDBTest/testDeleteInsertCloseAndOpen";
HaloDBOptions options = new HaloDBOptions();
options.isMergeDisabled = true;
options.maxFileSize = 10*1024;
HaloDB db = getTestDB(directory, options);
int noOfRecords = 10_000;
List<Record> records = TestUtils.insertRandomRecords(db, noOfRecords);
List<Record> deleted = new ArrayList<>();
for (int i = 0; i < noOfRecords; i++) {
if (i % 10 == 0) deleted.add(records.get(i));
}
TestUtils.deleteRecords(db, deleted);
List<Record> deleteAndInsert = new ArrayList<>();
deleted.forEach(r -> {
try {
byte[] value = TestUtils.generateRandomByteArray();
db.put(r.getKey(), value);
deleteAndInsert.add(new Record(r.getKey(), value));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
HaloDB openAgainDB = HaloDB.open(new File(directory), options);
List<Record> remaining = new ArrayList<>();
openAgainDB.newIterator().forEachRemaining(remaining::add);
Assert.assertTrue(remaining.size() == noOfRecords);
deleteAndInsert.forEach(r -> {
try {
Assert.assertEquals(r.getValue(), db.get(r.getKey()));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
}
#location 36
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testDeleteInsertCloseAndOpen() throws IOException {
String directory = "/tmp/HaloDBTest/testDeleteInsertCloseAndOpen";
HaloDBOptions options = new HaloDBOptions();
options.isMergeDisabled = true;
options.maxFileSize = 10*1024;
HaloDB db = getTestDB(directory, options);
int noOfRecords = 10_000;
List<Record> records = TestUtils.insertRandomRecords(db, noOfRecords);
List<Record> deleted = new ArrayList<>();
for (int i = 0; i < noOfRecords; i++) {
if (i % 10 == 0) deleted.add(records.get(i));
}
TestUtils.deleteRecords(db, deleted);
// inserting deleted records again.
List<Record> deleteAndInsert = new ArrayList<>();
deleted.forEach(r -> {
try {
byte[] value = TestUtils.generateRandomByteArray();
db.put(r.getKey(), value);
deleteAndInsert.add(new Record(r.getKey(), value));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
db.close();
HaloDB openAgainDB = getTestDBWithoutDeletingFiles(directory, options);
List<Record> remaining = new ArrayList<>();
openAgainDB.newIterator().forEachRemaining(remaining::add);
Assert.assertTrue(remaining.size() == noOfRecords);
// make sure that records that were earlier deleted shows up now, since they were put back later.
deleteAndInsert.forEach(r -> {
try {
Assert.assertEquals(r.getValue(), openAgainDB.get(r.getKey()));
} catch (IOException e) {
throw new RuntimeException(e);
}
});
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void close() throws IOException {
isClosing = true;
try {
if(!compactionManager.stopCompactionThread())
setIOErrorFlag();
} catch (IOException e) {
logger.error("Error while stopping compaction thread. Setting IOError flag", e);
setIOErrorFlag();
}
if (options.isCleanUpInMemoryIndexOnClose())
inMemoryIndex.close();
if (currentWriteFile != null) {
currentWriteFile.flushToDisk();
currentWriteFile.getIndexFile().flushToDisk();
currentWriteFile.close();
}
if (currentTombstoneFile != null) {
currentTombstoneFile.flushToDisk();
currentTombstoneFile.close();
}
for (HaloDBFile file : readFileMap.values()) {
file.close();
}
DBMetaData metaData = new DBMetaData(dbDirectory);
metaData.loadFromFileIfExists();
metaData.setOpen(false);
metaData.storeToFile();
dbDirectory.close();
if (dbLock != null) {
dbLock.close();
}
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void close() throws IOException {
writeLock.lock();
try {
isClosing = true;
try {
if(!compactionManager.stopCompactionThread())
setIOErrorFlag();
} catch (IOException e) {
logger.error("Error while stopping compaction thread. Setting IOError flag", e);
setIOErrorFlag();
}
if (options.isCleanUpInMemoryIndexOnClose())
inMemoryIndex.close();
if (currentWriteFile != null) {
currentWriteFile.flushToDisk();
currentWriteFile.getIndexFile().flushToDisk();
currentWriteFile.close();
}
if (currentTombstoneFile != null) {
currentTombstoneFile.flushToDisk();
currentTombstoneFile.close();
}
for (HaloDBFile file : readFileMap.values()) {
file.close();
}
DBMetaData metaData = new DBMetaData(dbDirectory);
metaData.loadFromFileIfExists();
metaData.setOpen(false);
metaData.storeToFile();
dbDirectory.close();
if (dbLock != null) {
dbLock.close();
}
} finally {
writeLock.unlock();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean putIfAbsent(byte[] key, V v)
{
KeyBuffer keyBuffer = keySource(key);
byte[] data = value(v);
if (maxEntrySize > 0L && CheckSegment.sizeOf(keyBuffer, data) > maxEntrySize)
{
remove(key);
putFailCount++;
return false;
}
CheckSegment segment = segment(keyBuffer.hash());
return segment.put(keyBuffer, data, true, null);
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
public boolean putIfAbsent(byte[] key, V v)
{
KeyBuffer keyBuffer = keySource(key);
byte[] data = value(v);
CheckSegment segment = segment(keyBuffer.hash());
return segment.put(keyBuffer, data, true, null);
} | 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.