output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public DefaultNHttpServerConnection createConnection(final IOSession iosession) { final SSLIOSession ssliosession = createSSLIOSession(iosession, this.sslcontext, this.sslHandler); return new DefaultNHttpServerConnection(ssliosession, this.cconfig.getBufferSize(), this.cconfig.getFragmentSizeHint(), this.allocator, ConnSupport.createDecoder(this.cconfig), ConnSupport.createEncoder(this.cconfig), this.cconfig.getMessageConstraints(), null, null, this.requestParserFactory, null); }
#vulnerable code public DefaultNHttpServerConnection 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 DefaultNHttpServerConnection(ssliosession, this.config.getBufferSize(), this.config.getFragmentSizeHint(), this.allocator, chardecoder, charencoder, this.config.getMessageConstraints(), null, null, this.requestParserFactory, null); } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMalformedChunkSizeDecoding() throws Exception { String s = "5\r\n01234\r\n5zz\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); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException ex) { // expected } }
#vulnerable code @Test public void testMalformedChunkSizeDecoding() throws Exception { String s = "5\r\n01234\r\n5zz\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); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException ex) { // expected } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void requestReceived(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); HttpRequest request = conn.getHttpRequest(); final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); connState.resetInput(); connState.setRequest(request); connState.setInputState(ServerConnState.REQUEST_RECEIVED); this.executor.execute(new Runnable() { public void run() { try { HttpContext context = new HttpExecutionContext(conn.getContext()); context.setAttribute(HttpExecutionContext.HTTP_CONNECTION, conn); handleRequest(connState, context); commitResponse(connState, conn); } catch (IOException ex) { shutdownConnection(conn); if (eventListener != null) { eventListener.fatalIOException(ex); } } catch (HttpException ex) { shutdownConnection(conn); if (eventListener != null) { eventListener.fatalProtocolException(ex); } } } }); }
#vulnerable code public void requestReceived(final NHttpServerConnection conn) { HttpContext context = conn.getContext(); HttpRequest request = conn.getHttpRequest(); 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; } final ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); connState.resetInput(); connState.setRequest(request); connState.setInputState(ServerConnState.REQUEST_RECEIVED); if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityReq = (HttpEntityEnclosingRequest) request; if (entityReq.expectContinue()) { try { HttpResponse ack = this.responseFactory.newHttpResponse( ver, HttpStatus.SC_CONTINUE, context); ack.getParams().setDefaults(this.params); if (this.expectationVerifier != null) { this.expectationVerifier.verify(request, ack, context); } conn.submitResponse(ack); } catch (HttpException ex) { shutdownConnection(conn); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex); } return; } } // Create a wrapper entity instead of the original one if (entityReq.getEntity() != null) { entityReq.setEntity(new BufferedContent( entityReq.getEntity(), connState.getInbuffer())); } } this.executor.execute(new Runnable() { public void run() { try { HttpContext context = new HttpExecutionContext(conn.getContext()); context.setAttribute(HttpExecutionContext.HTTP_CONNECTION, conn); handleRequest(connState, context); commitResponse(connState, conn); } catch (IOException ex) { shutdownConnection(conn); if (eventListener != null) { eventListener.fatalIOException(ex); } } catch (HttpException ex) { shutdownConnection(conn); if (eventListener != null) { eventListener.fatalProtocolException(ex); } } } }); } #location 40 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { HttpContext context = conn.getContext(); HttpRequest request = conn.getHttpRequest(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); ContentInputBuffer buffer = connState.getInbuffer(); // Update connection state connState.setInputState(ServerConnState.REQUEST_BODY_STREAM); try { buffer.consumeContent(decoder); if (decoder.isCompleted()) { // Request entity has been fully received connState.setInputState(ServerConnState.REQUEST_BODY_DONE); // Create a wrapper entity instead of the original one HttpEntityEnclosingRequest entityReq = (HttpEntityEnclosingRequest) request; if (entityReq.getEntity() != null) { entityReq.setEntity(new ContentBufferEntity( entityReq.getEntity(), connState.getInbuffer())); } conn.suspendInput(); processRequest(conn, request); } } catch (IOException ex) { shutdownConnection(conn); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { shutdownConnection(conn); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } }
#vulnerable code public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { HttpContext context = conn.getContext(); HttpRequest request = conn.getHttpRequest(); ServerConnState connState = (ServerConnState) context.getAttribute(CONN_STATE); ContentInputBuffer buffer = connState.getInbuffer(); // Update connection state connState.setInputState(ServerConnState.REQUEST_BODY_STREAM); try { buffer.consumeContent(decoder); if (decoder.isCompleted()) { // Request entity has been fully received connState.setInputState(ServerConnState.REQUEST_BODY_DONE); // Create a wrapper entity instead of the original one HttpEntityEnclosingRequest entityReq = (HttpEntityEnclosingRequest) request; if (entityReq.getEntity() != null) { entityReq.setEntity(new BufferedContent( entityReq.getEntity(), connState.getInbuffer())); } conn.suspendInput(); processRequest(conn, request); } } catch (IOException ex) { shutdownConnection(conn); if (this.eventListener != null) { this.eventListener.fatalIOException(ex, conn); } } catch (HttpException ex) { shutdownConnection(conn); if (this.eventListener != null) { this.eventListener.fatalProtocolException(ex, conn); } } } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConstructors() throws Exception { new IdentityOutputStream(new SessionOutputBufferMock()).close(); try { new IdentityOutputStream(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } }
#vulnerable code @Test public void testConstructors() throws Exception { new IdentityOutputStream(new SessionOutputBufferMock()); try { new IdentityOutputStream(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBasicDecodingFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMock( 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; } } Assert.assertEquals(testfile.length(), metrics.getBytesTransferred()); fchannel.close(); Assert.assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle)); deleteWithCheck(fileHandle); }
#vulnerable code @Test 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; } } Assert.assertEquals(testfile.length(), metrics.getBytesTransferred()); fchannel.close(); Assert.assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle)); deleteWithCheck(fileHandle); } #location 24 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testChunkedConsistence() throws IOException { String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb"; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); OutputStream out = new ChunkedOutputStream(2048, new SessionOutputBufferMock(buffer)); out.write(EncodingUtils.getBytes(input, CONTENT_CHARSET)); out.flush(); out.close(); out.close(); buffer.close(); InputStream in = new ChunkedInputStream( new SessionInputBufferMock( buffer.toByteArray())); byte[] d = new byte[10]; ByteArrayOutputStream result = new ByteArrayOutputStream(); int len = 0; while ((len = in.read(d)) > 0) { result.write(d, 0, len); } String output = EncodingUtils.getString(result.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(input, output); }
#vulnerable code @Test public void testChunkedConsistence() throws IOException { String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb"; ByteArrayOutputStream buffer = new ByteArrayOutputStream(); OutputStream out = new ChunkedOutputStream(new SessionOutputBufferMock(buffer)); out.write(EncodingUtils.getBytes(input, CONTENT_CHARSET)); out.flush(); out.close(); out.close(); buffer.close(); InputStream in = new ChunkedInputStream( new SessionInputBufferMock( buffer.toByteArray())); byte[] d = new byte[10]; ByteArrayOutputStream result = new ByteArrayOutputStream(); int len = 0; while ((len = in.read(d)) > 0) { result.write(d, 0, len); } String output = EncodingUtils.getString(result.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(input, output); } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); processTimeouts(keys); } }
#vulnerable code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); synchronized (keys) { processTimeouts(keys); } } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAvailable() throws IOException { final InputStream in = new ContentLengthInputStream( new SessionInputBufferMock(new byte[] {1, 2, 3}), 3L); Assert.assertEquals(0, in.available()); in.read(); Assert.assertEquals(2, in.available()); in.close(); }
#vulnerable code @Test public void testAvailable() throws IOException { final InputStream in = new ContentLengthInputStream( new SessionInputBufferMock(new byte[] {1, 2, 3}), 10L); Assert.assertEquals(0, in.available()); in.read(); Assert.assertEquals(2, in.available()); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCorruptChunkedInputStreamInvalidSize() throws IOException { final String s = "whatever\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) { } }
#vulnerable code @Test public void testCorruptChunkedInputStreamInvalidSize() throws IOException { final String s = "whatever\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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testRequestExpectContinueGenerated() throws Exception { HttpContext context = new BasicHttpContext(null); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); String s = "whatever"; StringEntity entity = new StringEntity(s, "US-ASCII"); request.setEntity(entity); request.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); RequestExpectContinue interceptor = new RequestExpectContinue(); interceptor.process(request, context); Header header = request.getFirstHeader(HTTP.EXPECT_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.EXPECT_CONTINUE, header.getValue()); }
#vulnerable code @Test public void testRequestExpectContinueGenerated() throws Exception { HttpContext context = new BasicHttpContext(null); BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/"); String s = "whatever"; StringEntity entity = new StringEntity(s, "US-ASCII"); request.setEntity(entity); request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); RequestExpectContinue interceptor = new RequestExpectContinue(); interceptor.process(request, context); Header header = request.getFirstHeader(HTTP.EXPECT_DIRECTIVE); Assert.assertNotNull(header); Assert.assertEquals(HTTP.EXPECT_CONTINUE, header.getValue()); } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testSimpleHttpPostsHTTP10() 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, HttpVersion.HTTP_1_0); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; executeStandardTest(new RequestHandler(), requestExecutionHandler); }
#vulnerable code public void testSimpleHttpPostsHTTP10() 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, HttpVersion.HTTP_1_0); NStringEntity entity = null; try { entity = new NStringEntity(testjob.getExpected(), "US-ASCII"); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; executeStandardTest(new TestRequestHandler(), requestExecutionHandler); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBasicWrite() throws Exception { final SessionOutputBufferMock transmitter = new SessionOutputBufferMock(); final IdentityOutputStream outstream = new IdentityOutputStream(transmitter); outstream.write(new byte[] {'a', 'b'}, 0, 2); outstream.write('c'); outstream.flush(); final byte[] input = transmitter.getData(); Assert.assertNotNull(input); final byte[] expected = new byte[] {'a', 'b', 'c'}; Assert.assertEquals(expected.length, input.length); for (int i = 0; i < expected.length; i++) { Assert.assertEquals(expected[i], input[i]); } outstream.close(); }
#vulnerable code @Test public void testBasicWrite() throws Exception { final SessionOutputBufferMock transmitter = new SessionOutputBufferMock(); final IdentityOutputStream outstream = new IdentityOutputStream(transmitter); outstream.write(new byte[] {'a', 'b'}, 0, 2); outstream.write('c'); outstream.flush(); final byte[] input = transmitter.getData(); Assert.assertNotNull(input); final byte[] expected = new byte[] {'a', 'b', 'c'}; Assert.assertEquals(expected.length, input.length); for (int i = 0; i < expected.length; i++) { Assert.assertEquals(expected[i], input[i]); } } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Future<BasicNIOPoolEntry> lease( final HttpHost route, final Object state, final FutureCallback<BasicNIOPoolEntry> callback) { return super.lease(route, state, this.connectTimeout, this.tunit, callback); }
#vulnerable code @Override public Future<BasicNIOPoolEntry> lease( final HttpHost route, final Object state, final FutureCallback<BasicNIOPoolEntry> callback) { int connectTimeout = Config.getInt(params, CoreConnectionPNames.CONNECTION_TIMEOUT, 0); return super.lease(route, state, connectTimeout, TimeUnit.MILLISECONDS, callback); } #location 6 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEndOfStreamConditionReadingFooters() throws Exception { String s = "10\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\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); 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()); }
#vulnerable code @Test public void testEndOfStreamConditionReadingFooters() throws Exception { String s = "10\r\n1234567890123456\r\n" + "5\r\n12345\r\n5\r\n12345\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); 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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testSimpleHttpPostsChunked() 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(true); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; executeStandardTest(new RequestHandler(), requestExecutionHandler); }
#vulnerable code public void testSimpleHttpPostsChunked() 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(true); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); return r; } }; executeStandardTest(new TestRequestHandler(), requestExecutionHandler); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; }
#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 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testIncompleteChunkDecoding() throws Exception { String[] chunks = { "10;", "key=\"value\"\r", "\n123456789012345", "6\r\n5\r\n12", "345\r\n6\r", "\nabcdef\r", "\n0\r\nFoot", "er1: abcde\r\nFooter2: f", "ghij\r\n\r\n" }; ReadableByteChannel channel = new ReadableByteChannelMock( chunks, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ByteBuffer dst = ByteBuffer.allocate(1024); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { int i = decoder.read(dst); if (i > 0) { bytesRead += i; } } Assert.assertEquals(27, bytesRead); Assert.assertEquals("123456789012345612345abcdef", convert(dst)); Assert.assertTrue(decoder.isCompleted()); 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()); }
#vulnerable code @Test public void testIncompleteChunkDecoding() throws Exception { String[] chunks = { "10;", "key=\"value\"\r", "\n123456789012345", "6\r\n5\r\n12", "345\r\n6\r", "\nabcdef\r", "\n0\r\nFoot", "er1: abcde\r\nFooter2: f", "ghij\r\n\r\n" }; ReadableByteChannel channel = new ReadableByteChannelMockup( chunks, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); ByteBuffer dst = ByteBuffer.allocate(1024); ChunkDecoder decoder = new ChunkDecoder(channel, inbuf, metrics); int bytesRead = 0; while (dst.hasRemaining() && !decoder.isCompleted()) { int i = decoder.read(dst); if (i > 0) { bytesRead += i; } } Assert.assertEquals(27, bytesRead); Assert.assertEquals("123456789012345612345abcdef", convert(dst)); Assert.assertTrue(decoder.isCompleted()); 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 34 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } }
#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 61 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; }
#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 6 #vulnerability type INTERFACE_NOT_THREAD_SAFE
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void processResponse( final NHttpClientConnection conn, final ClientConnState connState) throws IOException, HttpException { HttpContext context = conn.getContext(); HttpResponse response = connState.getResponse(); if (response.getEntity() != null) { response.setEntity(new ContentBufferEntity( response.getEntity(), connState.getInbuffer())); } context.setAttribute(HttpExecutionContext.HTTP_RESPONSE, response); this.httpProcessor.process(response, context); this.execHandler.handleResponse(response, context); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { // Ready for another request connState.resetInput(); conn.requestOutput(); } }
#vulnerable code private void processResponse( final NHttpClientConnection conn, final ClientConnState connState) throws IOException, HttpException { HttpContext context = conn.getContext(); HttpResponse response = connState.getResponse(); if (response.getEntity() != null) { response.setEntity(new BufferedContent( response.getEntity(), connState.getInbuffer())); } context.setAttribute(HttpExecutionContext.HTTP_RESPONSE, response); this.httpProcessor.process(response, context); this.execHandler.handleResponse(response, context); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } else { // Ready for another request connState.resetInput(); conn.requestOutput(); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMalformedChunkEndingDecoding() throws Exception { String s = "5\r\n01234\r\n5\r\n56789\n\r6\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); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException ex) { // expected } }
#vulnerable code @Test public void testMalformedChunkEndingDecoding() throws Exception { String s = "5\r\n01234\r\n5\r\n56789\n\r6\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); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException ex) { // expected } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testZeroLengthDecoding() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {"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, 0); ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(0, metrics.getBytesTransferred()); }
#vulnerable code @Test public void testZeroLengthDecoding() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {"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, 0); ByteBuffer dst = ByteBuffer.allocate(1024); int bytesRead = decoder.read(dst); Assert.assertEquals(-1, bytesRead); Assert.assertTrue(decoder.isCompleted()); Assert.assertEquals(0, metrics.getBytesTransferred()); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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()); 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(); }
#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 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 31 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConstructors() throws Exception { final ContentLengthOutputStream in = new ContentLengthOutputStream( new SessionOutputBufferMock(), 10L); in.close(); try { new ContentLengthOutputStream(null, 10L); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new ContentLengthOutputStream(new SessionOutputBufferMock(), -10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } }
#vulnerable code @Test public void testConstructors() throws Exception { new ContentLengthOutputStream(new SessionOutputBufferMock(), 10L); try { new ContentLengthOutputStream(null, 10L); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } try { new ContentLengthOutputStream(new SessionOutputBufferMock(), -10); Assert.fail("IllegalArgumentException should have been thrown"); } catch (final IllegalArgumentException ex) { // expected } } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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 25 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testHttpPostsWithExpectContinue() 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"); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); return r; } }; executeStandardTest(new RequestHandler(), requestExecutionHandler); }
#vulnerable code public void testHttpPostsWithExpectContinue() 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"); } catch (UnsupportedEncodingException ignore) { } r.setEntity(entity); r.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, true); return r; } }; executeStandardTest(new TestRequestHandler(), requestExecutionHandler); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); processTimeouts(keys); } }
#vulnerable code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); synchronized (keys) { processTimeouts(keys); } } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } } }
#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 80 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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(); IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); 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); }
#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(); IdentityDecoder decoder = new IdentityDecoder( channel, inbuf, metrics); 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 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); createTempFile(); RandomAccessFile testfile = new RandomAccessFile(this.tmpfile, "rw"); try { FileChannel fchannel = testfile.getChannel(); Assert.assertEquals(0, testfile.length()); try { decoder.transfer(fchannel, 5, 10); Assert.fail("IOException should have been thrown"); } catch(IOException expected) { } } finally { testfile.close(); } }
#vulnerable 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); } #location 25 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBasicDecodingFile() throws Exception { ReadableByteChannel channel = new ReadableByteChannelMock( 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; } } Assert.assertEquals(testfile.length(), metrics.getBytesTransferred()); fchannel.close(); Assert.assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle)); deleteWithCheck(fileHandle); }
#vulnerable code @Test 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; } } Assert.assertEquals(testfile.length(), metrics.getBytesTransferred()); fchannel.close(); Assert.assertEquals("stuff; more stuff; a lot more stuff!", readFromFile(fileHandle)); deleteWithCheck(fileHandle); } #location 25 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMalformedChunkTruncatedChunk() throws Exception { String s = "3\r\n12"; 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); Assert.assertEquals(2, decoder.read(dst)); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException ex) { // expected } }
#vulnerable code @Test public void testMalformedChunkTruncatedChunk() throws Exception { String s = "3\r\n12"; 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); Assert.assertEquals(2, decoder.read(dst)); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (MalformedChunkCodingException ex) { // expected } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testResponseContentNoEntity() throws Exception { HttpContext context = new BasicHttpContext(null); HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); Header header = response.getFirstHeader(HTTP.CONTENT_LEN); assertNotNull(header); assertEquals("0", header.getValue()); }
#vulnerable code public void testResponseContentNoEntity() throws Exception { HttpContext context = new HttpExecutionContext(null); HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); ResponseContent interceptor = new ResponseContent(); interceptor.process(response, context); Header header = response.getFirstHeader(HTTP.CONTENT_LEN); assertNotNull(header); assertEquals("0", header.getValue()); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } }
#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 39 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testAvailable() throws IOException { final String s = "5\r\n12345\r\n0\r\n"; final ChunkedInputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); Assert.assertEquals(0, in.available()); in.read(); Assert.assertEquals(4, in.available()); in.close(); }
#vulnerable code @Test public void testAvailable() throws IOException { final String s = "5\r\n12345\r\n0\r\n"; final ChunkedInputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(s, CONTENT_CHARSET))); Assert.assertEquals(0, in.available()); in.read(); Assert.assertEquals(4, in.available()); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testEmptyChunkedInputStream() throws IOException { final String input = "0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(input, CONTENT_CHARSET))); 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(); }
#vulnerable code @Test public void testEmptyChunkedInputStream() throws IOException { final String input = "0\r\n"; final InputStream in = new ChunkedInputStream( new SessionInputBufferMock( EncodingUtils.getBytes(input, CONTENT_CHARSET))); 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 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testInvalidInput() throws Exception { String s = "stuff"; ReadableByteChannel channel = new ReadableByteChannelMock( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); IdentityDecoder decoder = new IdentityDecoder(channel, inbuf, metrics); try { decoder.read(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException ex) { // expected } }
#vulnerable code @Test public void testInvalidInput() throws Exception { String s = "stuff"; ReadableByteChannel channel = new ReadableByteChannelMockup( new String[] {s}, "US-ASCII"); HttpParams params = new BasicHttpParams(); SessionInputBuffer inbuf = new SessionInputBufferImpl(1024, 256, params); HttpTransportMetricsImpl metrics = new HttpTransportMetricsImpl(); IdentityDecoder decoder = new IdentityDecoder(channel, inbuf, metrics); try { decoder.read(null); Assert.fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException ex) { // expected } } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } } }
#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 127 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCorruptChunkedInputStreamMissingLF() throws IOException { final String s = "5\r01234\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 */ } in.close(); }
#vulnerable code @Test public void testCorruptChunkedInputStreamMissingLF() throws IOException { final String s = "5\r01234\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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } }
#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 65 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMalformedFooters() 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); ByteBuffer dst = ByteBuffer.allocate(1024); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (IOException ex) { // expected } }
#vulnerable code @Test public void testMalformedFooters() 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); ByteBuffer dst = ByteBuffer.allocate(1024); try { decoder.read(dst); Assert.fail("MalformedChunkCodingException should have been thrown"); } catch (IOException ex) { // expected } } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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 25 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); processTimeouts(keys); } }
#vulnerable code @Override protected void processEvents(int readyCount) throws IOReactorException { processSessionRequests(); if (readyCount > 0) { Set<SelectionKey> selectedKeys = this.selector.selectedKeys(); for (Iterator<SelectionKey> it = selectedKeys.iterator(); it.hasNext(); ) { SelectionKey key = it.next(); processEvent(key); } selectedKeys.clear(); } long currentTime = System.currentTimeMillis(); if ((currentTime - this.lastTimeoutCheck) >= this.selectTimeout) { this.lastTimeoutCheck = currentTime; Set<SelectionKey> keys = this.selector.keys(); synchronized (keys) { processTimeouts(keys); } } } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBasics() throws IOException { final String correct = "1234567890123456"; final InputStream in = new ContentLengthInputStream(new SessionInputBufferMock( EncodingUtils.getBytes(correct, CONTENT_CHARSET)), 10L); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final byte[] buffer = new byte[50]; int len = in.read(buffer, 0, 2); out.write(buffer, 0, len); len = in.read(buffer); out.write(buffer, 0, len); final String result = EncodingUtils.getString(out.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(result, "1234567890"); in.close(); }
#vulnerable code @Test public void testBasics() throws IOException { final String correct = "1234567890123456"; final InputStream in = new ContentLengthInputStream(new SessionInputBufferMock( EncodingUtils.getBytes(correct, CONTENT_CHARSET)), 10L); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final byte[] buffer = new byte[50]; int len = in.read(buffer, 0, 2); out.write(buffer, 0, len); len = in.read(buffer); out.write(buffer, 0, len); final String result = EncodingUtils.getString(out.toByteArray(), CONTENT_CHARSET); Assert.assertEquals(result, "1234567890"); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testSimpleHttpGets() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new RequestExecutionHandler() { @Override protected HttpRequest generateRequest(Job testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); return new BasicHttpRequest("GET", s); } }; executeStandardTest(new RequestHandler(), requestExecutionHandler); }
#vulnerable code public void testSimpleHttpGets() throws Exception { HttpRequestExecutionHandler requestExecutionHandler = new TestRequestExecutionHandler() { @Override protected HttpRequest generateRequest(TestJob testjob) { String s = testjob.getPattern() + "x" + testjob.getCount(); return new BasicHttpRequest("GET", s); } }; executeStandardTest(new TestRequestHandler(), requestExecutionHandler); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBasicRead() throws Exception { final byte[] input = new byte[] {'a', 'b', 'c'}; final SessionInputBufferMock receiver = new SessionInputBufferMock(input); final IdentityInputStream instream = new IdentityInputStream(receiver); final byte[] tmp = new byte[2]; Assert.assertEquals(2, instream.read(tmp, 0, tmp.length)); Assert.assertEquals('a', tmp[0]); Assert.assertEquals('b', tmp[1]); Assert.assertEquals('c', instream.read()); Assert.assertEquals(-1, instream.read(tmp, 0, tmp.length)); Assert.assertEquals(-1, instream.read()); Assert.assertEquals(-1, instream.read(tmp, 0, tmp.length)); Assert.assertEquals(-1, instream.read()); instream.close(); }
#vulnerable code @Test public void testBasicRead() throws Exception { final byte[] input = new byte[] {'a', 'b', 'c'}; final SessionInputBufferMock receiver = new SessionInputBufferMock(input); final IdentityInputStream instream = new IdentityInputStream(receiver); final byte[] tmp = new byte[2]; Assert.assertEquals(2, instream.read(tmp, 0, tmp.length)); Assert.assertEquals('a', tmp[0]); Assert.assertEquals('b', tmp[1]); Assert.assertEquals('c', instream.read()); Assert.assertEquals(-1, instream.read(tmp, 0, tmp.length)); Assert.assertEquals(-1, instream.read()); Assert.assertEquals(-1, instream.read(tmp, 0, tmp.length)); Assert.assertEquals(-1, instream.read()); } #location 12 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(expected = MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamInvalidSize() throws IOException { final String s = "whatever\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(); }
#vulnerable code @Test(expected = MalformedChunkCodingException.class) public void testCorruptChunkedInputStreamInvalidSize() throws IOException { final String s = "whatever\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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void onResponseReceived(final HttpResponse response) throws IOException { this.response = response; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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 } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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 } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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) { } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void onRequestReceived(final HttpRequest request) throws IOException { this.request = request; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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 } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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 } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void onRequestReceived(final HttpRequest request) throws IOException { this.request = request; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.