Commit Graph

1308 Commits

Author SHA1 Message Date
Andrey Mizurov
b17371c198 Fix indexOutOfBoundsException when multipart/form-data is incorrect value (#9688)
Motivation:

HttpPostRequestDecoder.splitHeaderContentType() throws a StringIndexOutOfBoundsException when it parses a Content-Type header that starts with a semicolon ;. We should skip the execution for incorrect multipart form data.


Modification:

Avoid invocation of HttpPostRequestDecoder#splitHeaderContentType(...) for incorrect multipart form data content-type.

Result:

Fixes #8554
2019-10-23 09:03:40 +02:00
Jonathan Leitschuh
cde6a6d7d1 [DOC] Add CWE-113 warning to DefaultHttpHeaders constructor (#9646)
### Motivation:

I've now found two libraries that use Netty to be vulnerable to [CWE-113: Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Response Splitting')](https://cwe.mitre.org/data/definitions/113.html) due to using `new DefaultHttpHeaders(false)`.

Some part of me hopes that this warning will help dissuade library authors from disabling this important security check.

### Modification:

Add documentation to `DefaultHttpHeaders(boolean)` to warn about the implications of `false`.

### Result:

This improves the documentation on `DefaultHttpHeaders`.
2019-10-10 20:47:50 +02:00
康智冬
1c69448e2e Fix typos in javadocs (#9527)
Motivation:

We should have correct docs without typos

Modification:

Fix typos and spelling

Result:

More correct docs
2019-10-09 15:25:41 +02:00
liyixin
f81d02bdc7 Fix incorrect comment (#9598)
Motivation:

The comment is incorrect and so missleading

Modification:

Correct the comment

Result:

Correct comment in code
2019-09-24 10:01:20 +02:00
liyixin
5c19c3e6ce Optimize the QueryStringEncoder performance (#9568)
Motivation:

Optimize the QueryStringEncoder for lower memory overhead and higher encode speed.

Modification:

Encode the space to + directly, and reuse the uriStringBuilder rather then create a new one.

Result:

Improved performance
2019-09-20 21:11:07 +02:00
Norman Maurer
017a9658c9 Correctly handle whitespaces in HTTP header names as defined by RFC7230#section-3.2.4 (#9585)
Motivation:

When parsing HTTP headers special care needs to be taken when a whitespace is detected in the header name.

Modifications:

- Ignore whitespace when decoding response (just like before)
- Throw exception when whitespace is detected during parsing
- Add unit tests

Result:

Fixes https://github.com/netty/netty/issues/9571
2019-09-20 21:03:16 +02:00
Andrey Mizurov
f26840478a Fix HttpContentEncoder does not handle multiple Accept-Encoding (#9557)
Motivation:
At the current moment HttpContentEncoder handle only first value of multiple accept-encoding headers.

Modification:

Join multiple accept-encoding headers to one separated by comma.

Result:

Fixes #9553
2019-09-11 08:50:43 +02:00
Norman Maurer
48634f1466
Protect ChannelHandler from reentrancee issues (#9358)
Motivation:

At the moment it is quite easy to hit reentrance issues when you have multiple handlers in the pipeline and each of the handlers does not correctly protect against these. To make it easier for the user we should try to protect from these. The issue is usually if and inbound event will trigger and outbound event and this outbound event then against triggeres an inbound event. This may result in having methods in a ChannelHandler re-enter some method and so state can be corrupted or messages be re-ordered.

Modifications:

- Keep track of inbound / outbound operations in DefaultChannelHandlerContext and if reentrancy is detected break it by scheduling the action on the EventLoop. This will then be picked up once the method returns and so the reentrancy is broken up.
- Adjust tests which made strange assumptions about execution order

Result:

No more reentrancy of handlers possible.
2019-09-03 10:28:08 +02:00
Norman Maurer
64eb392d70 HttpPostStandardRequestDecoder leaks memory when constructor throws ErrorDataDecoderException. (#9517)
Motivation:

Currently when HttpPostStandardRequestDecoder throws a ErrorDataDecoderException during construction we leak memory. We need to ensure all is released correctly.

Modifications:

- Call destroy() if parseBody() throws and rethrow the ErrorDataDecoderException
- Add unit test

Result:

Fixes https://github.com/netty/netty/issues/9513.
2019-08-28 10:33:44 +02:00
Andrey Mizurov
88e247ee45 Fix sending an empty String like "" causes an error #9429 (#9512)
Motivation:

Handle https://tools.ietf.org/html/rfc7692#section-7.2.3.6

Result:

The empty buffer is correctly handled in deflate  encoder/decoder.

 Fixes #9429 .
2019-08-28 08:22:18 +02:00
hengyunabc
13575be12f Correctly pass all parameters in WebSocketServerProtocolHandler constructor (#9506)
Motivation:

We did not correctly pass all supplied parameters to the called constructor and so did not apply the timeout.

Modification:

Correctly pass on the parameters.

Result:

Use timeout
2019-08-27 09:01:13 +02:00
Idel Pivnitskiy
05bbecff49 Update links to the latest HTTP/2 specifications (#9493)
Motivation:

Some of the links in javadoc point to the obsolete drafts of HTTP/2
specifications. We should point them to the latest RFC 7540 or 7541.

Modifications:

Update links from `draft-ietf-httpbis-*` to the `rfc7540` and `rfc7541`.

Result:

Correct links in javadoc.
2019-08-22 13:59:44 +02:00
Idel Pivnitskiy
dd07caec6b Use AppendableCharSequence.charAtUnsafe(int) in HttpObjectDecoder (#9492)
Motivation:

`HttpObjectDecoder` pre-checks that it doesn't request characters
outside of the `AppendableCharSequence`'s length. `0` is always allowed
because the minimal length of `AppendableCharSequence` is `1`. We can
legally skip index check by using
`AppendableCharSequence.charAtUnsafe(int)` in all existing cases in
`HttpObjectDecoder`.

Modifications:

- Use `AppendableCharSequence.charAtUnsafe(int)` instead of
`AppendableCharSequence.charAt(int)` in `HttpObjectDecoder`.

Result:

No unnecessary index checks in `HttpObjectDecoder`.
2019-08-22 13:58:41 +02:00
Norman Maurer
2abaf50570 Fix compile error introduced by 67b851209f 2019-08-21 10:40:36 +02:00
Sergey S. Sergeev
6af0ecc795 Fix unexpected IllegalReferenceCountException on decode multipart request. (#8575)
Motivation:

Http post request may be encoded as 'multipart/form-data' without any files and consist mixed attributes only.

Modifications:

- Do not double release attributes
- Add unit test

Result:

Code does not throw an IllegalReferenceCountException.
2019-08-19 15:10:13 +02:00
Norman Maurer
67b851209f Ensure we replace WebSocketServerProtocolHandshakeHandler before doing the handshake (#9472)
Motivation:

We need to ensure we replace WebSocketServerProtocolHandshakeHandler before doing the actual handshake as the handshake itself may complete directly and so forward pending bytes through the pipeline.

Modifications:

Replace the handler before doing the actual handshake.

Result:

Fixes https://github.com/netty/netty/issues/9471.
2019-08-17 10:00:14 +02:00
Norman Maurer
6f616bb3cf Avoid creating FileInputStream and FileOutputStream for obtaining Fil… (#8110)
Motivation:

If all we need is the FileChannel we should better use RandomAccessFile as FileInputStream and FileOutputStream use a finalizer.

Modifications:

Replace FileInputStream and FileOutputStream with RandomAccessFile when possible.

Result:

Fixes https://github.com/netty/netty/issues/8078.
2019-08-17 09:52:16 +02:00
Norman Maurer
fc33d6ae99 Fix compile error in test introduced by 96f92929ab 2019-08-16 10:11:03 +02:00
Norman Maurer
96f92929ab Fix possible NPE when using HttpClientCodec (#9465)
Motivation:

It was possible to produce a NPE when we for examples received more responses as requests as we did not check if the queue did not contain a method before trying to compare method names.

Modifications:

- Add extra null check
- Add unit tet

Result:

Fixes https://github.com/netty/netty/issues/9459
2019-08-16 08:17:33 +02:00
Norman Maurer
cdb92c5b0f Correctly respect mask parameters in all WebSocketClientHandshakerFactory#newHandshaker(...) methods (#9464)
Motivation:

We did not correctly pass the mask parameters in all cases.

Modifications:

Correctly pass on parameters

Result:

Fixes https://github.com/netty/netty/issues/9463.
2019-08-15 08:33:54 +02:00
Andrey Mizurov
4340f6c116 Set the ORIGIN header from a custom headers if present (#9435)
Motivation:

Allow to set the ORIGIN header value from custom headers in WebSocketClientHandshaker

Modification:

Only override header if not present already

Result:

More flexible handshaker usage
2019-08-11 08:22:31 +02:00
noSim
e8c2986cf1 Fix HttpUtil.getCharset to not throw illegal charset exception (#9439)
Motivation:

If the HttpUtil.getCharset method is called with an illegal charset like
"charset=!illegal!" it throws an IllegalCharsetNameException. But the javadoc
states, that defaultCharset is returned if incorrect header value. Since the
client sending the request sets the header value this should not crash.

Modification:

HttpUtil.getCharset catches the IllegalCharsetNameException and returns the
defualt value.

Result:

HttpUtil.getCharset does not throw IllegalCharsetNameException any more.
2019-08-10 19:16:12 +02:00
Dmitriy Dumanskiy
10ee697557 Allow to turn off Utf8FrameValidator creation for websocket with Bina… (#9417)
…ryWebSocketFrames

Motivation:

`Utf8FrameValidator` is always created and added to the pipeline in `WebSocketServerProtocolHandler.handlerAdded` method. However, for websocket connection with only `BinaryWebSocketFrame`'s UTF8 validator is unnecessary overhead. Adding of `Utf8FrameValidator` could be easily avoided by extending of `WebSocketDecoderConfig` with additional property.

Specification requires UTF-8 validation only for `TextWebSocketFrame`.

Modification:

Added `boolean WebSocketDecoderConfig.withUTF8Validator` that allows to avoid adding of `Utf8FrameValidator` during pipeline initialization.

Result:

Less overhead when using only `BinaryWebSocketFrame`within web socket.
2019-08-03 10:36:54 +00:00
Dmitriy Dumanskiy
aea6c67cfb Decrease the level of logging in WebSocketFrameEncoder/Decoder (#9415)
Motivation:

Our QA servers are spammed with this messages:

13:57:51.560 DEBUG- Decoding WebSocket Frame opCode=1
13:57:51.560 DEBUG- Decoding WebSocket Frame length=4
I think this is too much info for debug level. It is better to move it to trace level.

Modification:

logger.debug changed to logger.trace for WebSocketFrameEncoder/Decoder

Result:

Less messages in Debug mode.
2019-08-03 10:17:52 +00:00
Norman Maurer
e4995be33c Use allocator when constructing ByteBufHolder sub-types or use Unpool… (#9377)
Motivation:

In many places Netty uses Unpooled.buffer(0) while should use EMPTY_BUFFER. We can't change this due to back compatibility in the constructors but can use Unpooled.EMPTY_BUFFER in some cases to ensure we not allocate at all. In others we can directly use the allocator either from the Channel / ChannelHandlerContext or the request / response.

Modification:

- Use Unpooled.EMPTY_BUFFER where possible
- Use allocator where possible

Result:

Fixes #9345 for websockets and http package
2019-07-18 10:36:03 +02:00
Norman Maurer
2ef4b16138 Add websocket encoder / decoder in correct order to the pipeline when HttpServerCodec is used (#9386)
Motivation:

We need to ensure we place the encoder before the decoder when doing the websockets upgrade as the decoder may produce a close frame when protocol violations are detected.

Modifications:

- Correctly place encoder before decoder
- Add unit test

Result:

Fixes https://github.com/netty/netty/issues/9300
2019-07-18 10:19:33 +02:00
Emily Littleworth
0f8685ae9b Return null in HttpPostRequestEncoder (#9352)
Motivation:

If the encoded value of a form element happens to exactly hit
the chunk limit (8096 bytes), the post request encoder will
throw a NullPointerException.

Modifications:

Catch the null case and return.

Result:

No NPE.
2019-07-16 13:30:07 +02:00
Dmitriy Dumanskiy
ef24732640 Cleanup in websockets, throw exception before allocating response if possible (#9361)
Motivation:

While fixing #9359 found few places that could be patched / improved separately.

Modification:

On handshake response generation - throw exception before allocating response objects if request is invalid.

Result:

No more leaks when exception is thrown.
2019-07-16 13:21:16 +02:00
Andrey Mizurov
e9fec0a710 Fixed incorrect Sec-WebSocket-Origin header for v13, see #9134 (#9312)
Motivation:

Based on https://tools.ietf.org/html/rfc6455#section-1.3 - for non-browser
clients, Origin header field may be sent if it makes sense in the context of those clients.

Modification:

Replace Sec-WebSocket-Origin to Origin

Result:

Fixes #9134 .
2019-07-12 12:06:11 +02:00
jingene
af614e4d6e Change the netty.io homepage scheme(http -> https) (#9344)
Motivation:

Netty homepage(netty.io) serves both "http" and "https".
It's recommended to use https than http.
Modification:

I changed from "http://netty.io" to "https://netty.io"
Result:

No effects.
2019-07-09 21:10:14 +02:00
jimin
d54678d645 Remove unnecessary code (#9303)
Motivation:

There are is some unnecessary code (like toString() calls) which can be cleaned up.

Modifications:

- Remove not needed toString() calls
- Simplify subString(...) calls
- Remove some explicit casts when not needed.

Result:

Cleaner code
2019-07-04 09:02:24 +02:00
jimin
3e836bd3fe Call to ‘asList’ with only one argument could be replaced with ‘singletonList’ (#9288)
Motivation:

asList should only be used if there are multiple elements.

Modification:

Call to asList with only one argument could be replaced with singletonList

Result:

Cleaner code and a bit of memory savings
2019-06-26 21:07:11 +02:00
Julien Viet
2d72a7c561 Preserve the original filename when encoding a multipart/form in mixed mode. (#9270)
Motivation:

The HttpPostRequestEncoder overwrites the original filename of file uploads sharing the same name encoded in mixed mode when it rewrites the multipart body header of the previous file. The original filename should be preserved instead.

Modifications:

Change the HttpPostRequestEncoder to reuse the correct filename when the encoder switches to mixed mode. The original test is incorrect and has been modified too, in addition it tests with an extra file upload since the current test was not testing the continuation of a mixed mode.

Result:

The HttpPostRequestEncoder will preserve the original filename of the first fileupload when switching to mixed mode
2019-06-24 10:40:39 +02:00
ursa
a05adceae8 Bugfix #9257: WebSocketProtocolHandler does NOT support autoRead=false (#9258)
Motivation:

I need to control WebSockets inbound flow manually, when autoRead=false

Modification:

Add missed ctx.read() call into WebSocketProtocolHandler, where read request has been swallowed.

Result:

Fixes #9257
2019-06-24 09:08:30 +02:00
ursa
d9db218291 WebSocket is closed without an error on protocol violations (#9116)
Motivation:

Incorrect WebSockets closure affects our production system.
Enforced 'close socket on any protocol violation' prevents our custom termination sequence from execution.
Huge number of parameters is a nightmare both in usage and in support (decoders configuration).

Modification:

- Fix violations handling - send proper response codes.
- Fix for messages leak.
- Introduce decoder's option to disable default behavior (send close frame) on protocol violations.
- Encapsulate WebSocket response codes - WebSocketCloseStatus.
- Encapsulate decoder's configuration into a separate class - WebSocketDecoderConfig.

Result:

Fixes #8295.
2019-06-18 10:13:05 +02:00
Stephane Landelle
576b1768f4 Introduce WebSocketClientHandshaker::absoluteUpgradeUrl, close #9205 (#9206)
Motivation:

When connecting through an HTTP proxy over clear HTTP, user agents must send requests with an absolute url. This hold true for WebSocket Upgrade request.

WebSocketClientHandshaker and subclasses currently always send requests with a relative url, which causes proxies to crash as request is malformed.

Modification:

Introduce a new parameter `absoluteUpgradeUrl` and expose it in constructors and WebSocketClientHandshakerFactory.

Result:

It's now possible to configure WebSocketClientHandshaker so it works properly with HTTP proxies over clear HTTP.
2019-06-07 16:01:49 -07:00
yipulash
68f2242ac4 delete Other "Content-" MIME Header Fields exception (#9122)
delete Other "Content-" MIME Header Fields exception

Motivation:

RFC7578 4.8. Other "Content-" Header Fields

The multipart/form-data media type does not support any MIME header
fields in parts other than Content-Type, Content-Disposition, and (in
limited circumstances) Content-Transfer-Encoding. Other header
fields MUST NOT be included and MUST be ignored.

Modification:

Ignore other Content types.

Result: 

Other "Content-" Header Fields should be ignored no exception
2019-06-07 13:51:50 -07:00
Norman Maurer
5694dc3e2b Do not use static exceptions for websocket handshake timeout (#9174)
Motivation:

f17bfd0f64 removed the usage of static exception instances to reduce the risk of OOME due addSupressed calls. We should do the same for exceptions used to signal handshake timeouts.

Modifications:

Do not use static instances

Result:

No risk of OOME due addSuppressed calls
2019-05-23 08:36:37 +02:00
Vojin Jovanovic
f7a8a6f1ae Remove deprecated GraalVM native-image flags (#9118)
Motivation:

The first final version of GraalVM was released which deprecated some flags. We should use the new ones.

Modifications:

Removes the use of deprecated GraalVM native-image flags
Adds a flag to initialize netty at build time.

Result:

Do not use deprecated flags
2019-05-22 19:22:03 +02:00
秦世成
1465e3ce06 Support handshake timeout in websocket handlers (#8856)
Motivation:

Support handshake timeout option in websocket handlers. It makes sense to limit the time we need to move from `HANDSHAKE_ISSUED` to `HANDSHAKE_COMPLETE` states when upgrading to WebSockets

Modification:

- Add `handshakeTimeoutMillis` option in `WebSocketClientProtocolHandshakeHandler`  and `WebSocketServerProtocolHandshakeHandler`.
- Schedule a timeout task, the task will trigger user event `HANDSHAKE_TIMEOUT` if the handshake timed out.

Result:

Fixes issue https://github.com/netty/netty/issues/8841
2019-05-22 13:56:36 +02:00
Nick Hill
23554e6997 Ensure "full" ownership of msgs passed to EmbeddedChannel.writeInbound() (#9058)
Motivation

Pipeline handlers are free to "take control" of input buffers if they have singular refcount - in particular to mutate their raw data if non-readonly via discarding of read bytes, etc.

However there are various places (primarily unit tests) where a wrapped byte-array buffer is passed in and the wrapped array is assumed not to change (used after the wrapped buffer is passed to EmbeddedChannel.writeInbound()). This invalid assumption could result in unexpected errors, such as those exposed by #8931.

Modifications

Anywhere that the data passed to writeInbound() might be used again, ensure that either:
- A copy is used rather than wrapping a shared byte array, or
- The buffer is otherwise protected from modification by making it read-only

For the tests, copying is preferred since it still allows the "mutating" optimizations to be exercised.

Results

Avoid possible errors when pipeline assumes it has full control of input buffer.
2019-05-22 12:35:03 +02:00
秦世成
a9159d28fb Format code to align unaligned code. (#9062)
Motivation:
Format code to align unaligned code.

Modification:
Reformat the code

Result:

Cleaner code
2019-05-20 12:07:45 +02:00
Norman Maurer
ed61e5f543 Only use static Exception instances when we can ensure addSuppressed … (#9152)
Motivation:

OOME is occurred by increasing suppressedExceptions because other libraries call Throwable#addSuppressed. As we have no control over what other libraries do we need to ensure this can not lead to OOME.

Modifications:

Only use static instances of the Exceptions if we can either dissable addSuppressed or we run on java6.

Result:

Not possible to OOME because of addSuppressed. Fixes https://github.com/netty/netty/issues/9151.
2019-05-17 22:42:53 +02:00
Paulo Lopes
f5c0d2eb56 Add SVM metadata and minimal substitutions to build graalvm native image applications. (#8963)
Motivation:

GraalVM native images are a new way to deliver java applications. Netty is one of the most popular libraries however there are a few limitations that make it impossible to use with native images out of the box. Adding a few metadata (in specific modules will allow the compilation to success and produce working binaries)

Modification:

Added properties files in `META-INF` and substitutions classes (under `internal.svm`) will solve the compilation issues. The substitutions classes are not visible and do not have a public constructor so they are not visible to end users.

Result:

Fixes #8959

This fix is very conservative as it applies the minimum config required to build:

* pure netty servers
* vert.x applications
* grpc applications

The build is having trouble due to checkstyle which does not seem to be able to find the copyright notice on property files.
2019-04-29 09:12:09 +02:00
Oleksii Kachaiev
a57f73e1fe WebSocket client handshaker to support "force close" after timeout (#8896)
Motivation:

RFC 6455 defines that, generally, a WebSocket client should not close a TCP
connection as far as a server is the one who's responsible for doing that.
In practice tho', it's not always possible to control the server. Server's
misbehavior may lead to connections being leaked (if the server does not
comply with the RFC).

RFC 6455 #7.1.1 says

> In abnormal cases (such as not having received a TCP Close from the server
after a reasonable amount of time) a client MAY initiate the TCP Close.

Modifications:

* WebSocket client handshaker additional param `forceCloseAfterMillis`

* Use 10 seconds as default

Result:

WebSocket client handshaker to comply with RFC. Fixes #8883.
2019-04-10 15:48:24 +02:00
Norman Maurer
66f30874e3 Do not manually reset HttpObjectDecoder in HttpObjectAggregator.handleOversizedMessage(...) (#9017)
Motivation:

We did manually call HttpObjectDecoder.reset() in HttpObjectAggregator.handleOversizedMessage(...) which is incorrect and will prevent correct parsing of the next message.

Modifications:

- Remove call to HttpObjectDecoder.reset()
- Add unit test

Result:

Verify that we can correctly parse the next request after we rejected a request.
2019-04-08 21:11:23 +02:00
Norman Maurer
077b1fc4d9 Correctly discard messages after oversized message is detected. (#9015)
Motivation:

32563bfcc1 introduced a regression in which we did now not longer discard the messages after we handled an oversized message.

Modifications:

- Do not set aggregating to false after handleOversizedMessage is called
- Adjust unit tests to verify the behaviour is correct again.

Result:

Fixes https://github.com/netty/netty/issues/9007.
2019-04-08 21:09:30 +02:00
Norman Maurer
0f34345347
Merge ChannelInboundHandler and ChannelOutboundHandler into ChannelHa… (#8957)
Motivation:

In 42742e233f we already added default methods to Channel*Handler and deprecated the Adapter classes to simplify the class hierarchy. With this change we go even further and merge everything into just ChannelHandler. This simplifies things even more in terms of class-hierarchy.

Modifications:

- Merge ChannelInboundHandler | ChannelOutboundHandler into ChannelHandler
- Adjust code to just use ChannelHandler
- Deprecate old interfaces.

Result:

Cleaner and simpler code in terms of class-hierarchy.
2019-03-28 09:28:27 +00:00
Andrey Mizurov
d3906d862e Add user possibility to skip the evaluation of a certain websocket ex… (#8910)
Motivation:

Add user possibility to skip the evaluation of certain web socket extension,
for example we can skip compression extension for messages that already compressed or very small and etc.

Modification:

This pull request is related with #5669

Result:

User can set to WebSocketClientExtensionHandshaker or WebSocketServerExtensionHandshaker a filter to skip the evaluation of certain extension.
2019-03-22 15:02:54 +01:00
violetagg
a44c33136f Fix HttpUtil.isKeepAlive to behave correctly when Connection is a comma separated list (#8924)
Motivation:

According to the specification, the "Connection" header's syntax is:

"
The Connection header field's value has the following grammar:

     Connection        = 1#connection-option
     connection-option = token

Connection options are case-insensitive.
"
https://tools.ietf.org/html/rfc7230#section-6.1

This means that Connection's value can have at least one element or
a comma separated list with elements
When calculating whether the connection can remain open,
HttpUtil.isKeepAlive(HttpMessage) should take this into account.

Modifications:

- Check for "close" and "keep-alive" in a comma separated list
- Add unit test

Result:

HttpUtil.isKeepAlive(HttpMessage) works correctly when "Connection: Upgrade, close"
2019-03-13 14:30:46 +01:00