Commit Graph

51 Commits

Author SHA1 Message Date
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
Oleksii Kachaiev
d0beb8dea1 Carefully manage Keep-Alive/Close connection headers in all examples (#8966)
Motivation:

"Connection: close" header should be specified each time we're going
to close an underlying TCP connection when sending HTTP/1.1 reply.

Modifications:

Introduces changes made in #8914 for the following examples:

* WebSocket index page and WebSocket server handler
* HelloWorld server
* SPDY server handler
* HTTP/1.1 server handler from HTTP/2 HelloWorld example
* HTTP/1.1 server handler from tiles example

Result:

Keep-Alive connections management conforms with RFCs.
2019-04-02 21:11:39 +02:00
Oleksii Kachaiev
902cdaae56 Carefully manage Keep-Alive connections in HttpStaticFileServer (#8914)
Motivation:

Simple rules:

* close the connection when sending any error
* specify "Connection: close" header when closing the connection
* successful responses should keep the connection intact when otherwise is not requested by the client

Modifications:

* "send response and cleanup the connection" logic moved to a helper
* for all successful responses set "Content-Lenght" header
* do not specify "Connection: Keep-Alive" header as far it's a default for HTTP/1.1
* set "Connection: close" header when necessary

Result:

Keep-Alive connections management is inlined with RFCs.
2019-03-06 15:52:32 +01:00
Dmitriy Dumanskiy
b7ceeb1797 Compare HttpMethod by reference (#8815)
Motivation:

In most cases, HttpMethod instance is built from the factory method and the same instance is taken for known Http Methods. So we can implement fast path for equals().

Modification:

Replace == checks with HttpMethod.equals;
Use this == o within HttpMethod.equals;
Replaced known new HttpMethod with HttpMethod.valueOf;
Result:

Comparisons should be a bit faster in some cases.
2019-01-30 21:17:24 +01:00
kennylbj
00bf06e97b Fix spelling mistake of HttpStaticFileServerHandler.java 2017-04-03 10:59:25 -07:00
Tomer Cohen
fa6b0e262e Support Unicode filenames and spaces in directory listing
Motivation:

The HTTP Static File Server seems to ignore filenames that doesn't contains only latin characters, but these days people wish to serve files in other languages, or even include some emojis in the filename. Although these files are not displayed on the directory listing, they are accessible by HTTP requests. This fix will make such files more visible.

Modifications:

I've changed the ALLOWED_FILE_NAME pattern to disallow only files that starts with underline, minus or a dot (such as .htaccess), and hide other "unsafe" filenames that may be used to trigger some security issues. Other filenames, including the space character are allowed.

I've also added charset encoding to the directory listing, because the browser default MAY be configured for ISO-8859-1 instead of UTF-8.

Result:

Directory listing will work for files that contains the space character, as well as other Unicode characters.
2016-08-16 09:18:18 +02:00
Tomer Cohen
15222c084d Never expose user.dir to the web on directory listing
Motivation:

When Netty HTTP Static File Server does directory listing, it does expose the user.dir environment variable to the user. Although it doesn't a security issue, it is a bad practice to show it, and the user does expect to see the server virtual root instead, which is the absolute path as mentioned in the RFC.

Modifications:

the sendListing method receives a third argument, which is the requested URI, and this is what should be displayed on the page instead of the filesystem path.

Result:

The directory listing pages will show the virtual path as described in the URI and not the real filesystem path.

Removed fallback method
2016-08-16 09:14:53 +02:00
Scott Mitchell
b6a4f5de9d Refactor of HttpUtil and HttpHeaderUtil
Motivation:
There currently exists http.HttpUtil, http2.HttpUtil, and http.HttpHeaderUtil. Having 2 HttpUtil methods can be confusing and the utilty methods in the http package could be consolidated.

Modifications:
- Rename http2.HttpUtil to http2.HttpConversionUtil
- Move http.HttpHeaderUtil methods into http.HttpUtil

Result:
Consolidated utilities whose names don't overlap.
Fixes https://github.com/netty/netty/issues/4120
2015-08-27 08:49:58 -07:00
Norman Maurer
1e8a2e69db [#3592] Flush when writing HttpChunkedInput
Motivation:

We missed to flush the channel when using HttpChunkedInput (this is done when using SSL). This will result in a stale.

Modifications:

Replace ctx.write(...) with ctx.writeAndFlush(...)

Result:

Correctly working example.
2015-04-10 21:19:25 +02:00
Trustin Lee
338b60821d Do not write LastHttpContent twice in HttpStaticFileServer example
Related: #3122

Motivation:

The HttpStaticFileServer example writes the LastHttpContent twice at the
end of the transfer.  HttpChunkedInput already produces a
LastHttpContent at the end of the stream, so there's no reason to write
another.

Modifications:

Do not write LastHttpContent in HttpStaticFileServerHandler when
HttpChunkedInput is used to transfer a file.

Result:

HttpStaticFileServer does not violates the protocol anymore.
2014-11-21 11:43:32 +09:00
Idel Pivnitskiy
35db3c6710 Small performance improvements
Motivation:

Found performance issues via FindBugs and PMD.

Modifications:

- Removed unnecessary boxing/unboxing operations in DefaultTextHeaders.convertToInt(CharSequence) and DefaultTextHeaders.convertToLong(CharSequence). A boxed primitive is created from a string, just to extract the unboxed primitive value.
- Added a static modifier for DefaultHttp2Connection.ParentChangedEvent class. This class is an inner class, but does not use its embedded reference to the object which created it. This reference makes the instances of the class larger, and may keep the reference to the creator object alive longer than necessary.
- Added a static compiled Pattern to avoid compile it each time it is used when we need to replace some part of authority.
- Improved using of StringBuilders.

Result:

Performance improvements.
2014-11-20 00:10:06 -05:00
Trustin Lee
4ce994dd4f Fix backward compatibility from the previous backport
Motivation:

The commit 50e06442c3 changed the type of
the constants in HttpHeaders.Names and HttpHeaders.Values, making 4.1
backward-incompatible with 4.0.

It also introduces newer utility classes such as HttpHeaderUtil, which
deprecates most static methods in HttpHeaders.  To ease the migration
between 4.1 and 5.0, we should deprecate all static methods that are
non-existent in 5.0, and provide proper counterpart.

Modification:

- Revert the changes in HttpHeaders.Names and Values
- Deprecate all static methods in HttpHeaders in favor of:
  - HttpHeaderUtil
  - the member methods of HttpHeaders
  - AsciiString
- Add integer and date access methods to HttpHeaders for easier future
  migration to 5.0
- Add HttpHeaderNames and HttpHeaderValues which provide standard HTTP
  constants in AsciiString
  - Deprecate HttpHeaders.Names and Values
  - Make HttpHeaderValues.WEBSOCKET lowercased because it's actually
    lowercased in all WebSocket versions but the oldest one
- Add RtspHeaderNames and RtspHeaderValues which provide standard RTSP
  constants in AsciiString
  - Deprecate RtspHeaders.*
- Do not use AsciiString.equalsIgnoreCase(CharSeq, CharSeq) if one of
  the parameters are AsciiString
- Avoid using AsciiString.toString() repetitively
  - Change the parameter type of some methods from String to
    CharSequence

Result:

Backward compatibility is recovered.  New classes and methods will make
the migration to 5.0 easier, once (Http|Rtsp)Header(Names|Values) are
ported to master.
2014-11-01 01:00:25 +09:00
Scott Mitchell
50e06442c3 Backport header improvements from 5.0
Motivation:
The header class hierarchy and algorithm was improved on the master branch for versions 5.x. These improvments should be backported to the 4.1 baseline.

Modifications:
- cherry-pick the following commits from the master branch: 2374e17, 36b4157, 222d258

Result:
Header improvements in master branch are available in 4.1 branch.
2014-11-01 00:59:57 +09:00
Trustin Lee
d0912f2709 Fix most inspector warnings
Motivation:

It's good to minimize potentially broken windows.

Modifications:

Fix most inspector warnings from our profile
Update IntObjectHashMap

Result:

Cleaner code
2014-07-02 19:55:07 +09:00
Trustin Lee
41d44a8161 Remove 'get' prefix from all HTTP/SPDY messages
Motivation:

Persuit for the consistency in method naming

Modifications:

- Remove the 'get' prefix from all HTTP/SPDY message classes
- Fix some inspector warnings

Result:

Consistency
2014-06-24 18:03:33 +09:00
Norman Maurer
4036eda048 Make use of HttpChunkedInput as this will also work when compression is used 2014-06-23 09:38:48 +02:00
Trustin Lee
8b0a0f9a8f Introduce MessageAggregator and DecoderResultProvider
Motivation:

We have different message aggregator implementations for different
protocols, but they are very similar with each other.  They all stems
from HttpObjectAggregator.  If we provide an abstract class that provide
generic message aggregation functionality, we will remove their code
duplication.

Modifications:

- Add MessageAggregator which provides generic message aggregation
- Reimplement all existing aggregators using MessageAggregator
- Add DecoderResultProvider interface and extend it wherever possible so
  that MessageAggregator respects the state of the decoded message

Result:

Less code duplication
2014-06-05 16:51:14 +09:00
Trustin Lee
223efc5f99 Clean up the examples
Motivation:

The examples have not been updated since long time ago, showing various
issues fixed in this commit.

Modifications:

- Overall simplification to reduce LoC
  - Use system properties to get options instead of parsing args.
  - Minimize option validation
  - Just use System.out/err instead of Logger
  - Do not pass config as parameters - just access it directly
  - Move the main logic to main(String[]) instead of creating a new
    instance meaninglessly
    - Update netty-build-21 to make checkstyle not complain
  - Remove 'throws Exception' clause if possible
- Line wrap at 120 (previously at 80)
- Add an option to enable SSL for most examples
- Use ChannelFuture.sync() instead of await()
- Use System.out for the actual result. Use System.err otherwise.
- Delete examples that are not very useful:
  - applet
  - websocket/html5
  - websocketx/sslserver
  - localecho/multithreaded
- Add run-example.sh which simplifies launching an example from command
  line
- Rewrite FileServer example

Result:

Shorter and simpler examples.  A user can focus more on what it actually
does than miscellaneous stuff.  A user can launch an example very
easily.
2014-05-23 17:13:09 +09:00
Norman Maurer
88481131be [#2353] Use a privileged block to get ClassLoader and System property if needed
Motivation:
When using System.getProperty(...) and various methods to get a ClassLoader it will fail when a SecurityManager is in place.

Modifications:
Use a priveled block if needed. This work is based in the PR #2353 done by @anilsaldhana .

Result:
Code works also when SecurityManager is present
2014-04-08 14:12:25 +02:00
Trustin Lee
762adfcb69 Update HttpStaticFileServer example / Fix bugs related with progress notification
- Fix a bug in DefaultProgressivePromise.tryProgress() where the notification is dropped
 - Fix a bug in AbstractChannel.calculateMessageSize() where FileRegion is not counted
 - HttpStaticFileServer example now uses zero copy file transfer if possible.
2013-07-19 13:21:32 +09:00
Trustin Lee
f96a8e5951 Implement ProgressivePromise notification in NIO byte channels and ChunkedWriteHandler
- Refine the contract of GenericProgressiveFutureListener.
- Negative 'total' now means 'unknown', which is useful for ChunkedWriteHandler.
2013-07-19 12:53:23 +09:00
Norman Maurer
ecb215c12f Fix buffer leaks 2013-07-14 22:50:53 +02:00
Norman Maurer
b57d9f307f Allow per-write promises and disallow promises on flush()
- write() now accepts a ChannelPromise and returns ChannelFuture as most
  users expected.  It makes the user's life much easier because it is
  now much easier to get notified when a specific message has been
  written.
- flush() does not create a ChannelPromise nor returns ChannelFuture.
  It is now similar to what read() looks like.
2013-07-11 00:49:48 +09:00
Trustin Lee
26e9d70457 Remove channelReadSuspended / Rename messageReceived(Last) to channelRead(Complete)
- Remove channelReadSuspended because it's actually same with messageReceivedLast
- Rename messageReceived to channelRead
- Rename messageReceivedLast to channelReadComplete

We renamed messageReceivedLast to channelReadComplete because it
reflects what it really is for.  Also, we renamed messageReceived to
channelRead for consistency in method names.
2013-07-09 23:58:51 +09:00
Trustin Lee
cbd8817905 Remove MessageList from public API and change ChannelInbound/OutboundHandler accordingly
I must admit MesageList was pain in the ass.  Instead of forcing a
handler always loop over the list of messages, this commit splits
messageReceived(ctx, list) into two event handlers:

- messageReceived(ctx, msg)
- mmessageReceivedLast(ctx)

When Netty reads one or more messages, messageReceived(ctx, msg) event
is triggered for each message.  Once the current read operation is
finished, messageReceivedLast() is triggered to tell the handler that
the last messageReceived() was the last message in the current batch.

Similarly, for outbound, write(ctx, list) has been split into two:

- write(ctx, msg)
- flush(ctx, promise)

Instead of writing a list of message with a promise, a user is now
supposed to call write(msg) multiple times and then call flush() to
actually flush the buffered messages.

Please note that write() doesn't have a promise with it.  You must call
flush() to get notified on completion. (or you can use writeAndFlush())

Other changes:

- Because MessageList is completely hidden, codec framework uses
  List<Object> instead of MessageList as an output parameter.
2013-07-09 23:51:48 +09:00
Trustin Lee
a969613540 Merge ChannelInboundConsumingHandler into SimpleChannelInboundHandler
- SimpleChannelInboundHandler now has a constructor parameter to let a
  user decide to enable automatic message release. (the default is to
  enable), which makes ChannelInboundConsumingHandler of less value.
2013-06-25 11:07:14 +09:00
Norman Maurer
bfc9c6d80d Add ChannelInboundConsumingHandler
..which is useful when the handler is placed at the last position of the
pipeline because it releases the received messages automatically.
2013-06-25 11:07:14 +09:00
Trustin Lee
14158070bf Revamp the core API to reduce memory footprint and consumption
The API changes made so far turned out to increase the memory footprint
and consumption while our intention was actually decreasing them.

Memory consumption issue:

When there are many connections which does not exchange data frequently,
the old Netty 4 API spent a lot more memory than 3 because it always
allocates per-handler buffer for each connection unless otherwise
explicitly stated by a user.  In a usual real world load, a client
doesn't always send requests without pausing, so the idea of having a
buffer whose life cycle if bound to the life cycle of a connection
didn't work as expected.

Memory footprint issue:

The old Netty 4 API decreased overall memory footprint by a great deal
in many cases.  It was mainly because the old Netty 4 API did not
allocate a new buffer and event object for each read.  Instead, it
created a new buffer for each handler in a pipeline.  This works pretty
well as long as the number of handlers in a pipeline is only a few.
However, for a highly modular application with many handlers which
handles connections which lasts for relatively short period, it actually
makes the memory footprint issue much worse.

Changes:

All in all, this is about retaining all the good changes we made in 4 so
far such as better thread model and going back to the way how we dealt
with message events in 3.

To fix the memory consumption/footprint issue mentioned above, we made a
hard decision to break the backward compatibility again with the
following changes:

- Remove MessageBuf
- Merge Buf into ByteBuf
- Merge ChannelInboundByte/MessageHandler and ChannelStateHandler into ChannelInboundHandler
  - Similar changes were made to the adapter classes
- Merge ChannelOutboundByte/MessageHandler and ChannelOperationHandler into ChannelOutboundHandler
  - Similar changes were made to the adapter classes
- Introduce MessageList which is similar to `MessageEvent` in Netty 3
- Replace inboundBufferUpdated(ctx) with messageReceived(ctx, MessageList)
- Replace flush(ctx, promise) with write(ctx, MessageList, promise)
- Remove ByteToByteEncoder/Decoder/Codec
  - Replaced by MessageToByteEncoder<ByteBuf>, ByteToMessageDecoder<ByteBuf>, and ByteMessageCodec<ByteBuf>
- Merge EmbeddedByteChannel and EmbeddedMessageChannel into EmbeddedChannel
- Add SimpleChannelInboundHandler which is sometimes more useful than
  ChannelInboundHandlerAdapter
- Bring back Channel.isWritable() from Netty 3
- Add ChannelInboundHandler.channelWritabilityChanges() event
- Add RecvByteBufAllocator configuration property
  - Similar to ReceiveBufferSizePredictor in Netty 3
  - Some existing configuration properties such as
    DatagramChannelConfig.receivePacketSize is gone now.
- Remove suspend/resumeIntermediaryDeallocation() in ByteBuf

This change would have been impossible without @normanmaurer's help. He
fixed, ported, and improved many parts of the changes.
2013-06-10 16:10:39 +09:00
Trustin Lee
1e0c83db23 Introduce AddressedEnvelope message type for generic representation of an addressed message
- Fixes #1282 (not perfectly, but to the extent it's possible with the current API)
- Add AddressedEnvelope and DefaultAddressedEnvelope
- Make DatagramPacket extend DefaultAddressedEnvelope<ByteBuf, InetSocketAddress>
- Rename ByteBufHolder.data() to content() so that a message can implement both AddressedEnvelope and ByteBufHolder (DatagramPacket does) without introducing two getter methods for the content
- Datagram channel implementations now understand ByteBuf and ByteBufHolder as a message with unspecified remote address.
2013-05-01 17:04:43 +09:00
Norman Maurer
641db5cdfe Only write the header as it should be 2013-01-30 20:40:06 +01:00
Norman Maurer
238e03f75b Add setters and getters back to Http Objects
* This is done because we noticed that the previous change limit the usage more then it gave us any benefit. Now it is possible
  again to rewrite the url on the fly or reuse the objects when writing a proxy and so limit the GC pressure.
* Fixes also #979
2013-01-30 07:42:18 +01:00
Trustin Lee
34820511ff Second HTTP overhaul
- Rename message types for clarity
  - HttpMessage -> FullHttpMessage
  - HttpHeader -> HttpMessage
  - HttpRequest -> FullHttpRequest
  - HttpResponse -> FulllHttpResponse
  - HttpRequestHeader -> HttpRequest
  - HttpResponseHeader -> HttpResponse
- HttpContent now extends ByteBufHolder; no more content() method
- Make HttpHeaders abstract, make its header access methods public, and
  add DefaultHttpHeaders
- Header accessor methods in HttpMessage and LastHttpContent are
  replaced with HttpMessage.headers() and
  LastHttpContent.trailingHeaders(). Both methods return HttpHeaders.
- Remove setters wherever possible and remove 'get' prefix
- Instead of calling setContent(), a user can either specify the content
  when constructing a message or write content into the buffer.
  (e.g. m.content().writeBytes(...))
- Overall cleanup & fixes
2013-01-16 23:46:02 +09:00
Trustin Lee
ea4a0e3535 Prefer {@code ...} to <code>...</code> / Fix deprecation warnings 2012-11-12 11:51:23 +09:00
Trustin Lee
b4f796c5e3 Use 'x' over "x" wherever possible / String.equals("") -> isEmpty() 2012-11-10 08:03:52 +09:00
Trustin Lee
58ba0de659 Remove unnecessarily qualified static access 2012-11-10 01:32:21 +09:00
Trustin Lee
e21dc5925d Replace dynamic regular expressions with precompiled Patterns or new StringUtil.split() 2012-11-10 00:41:22 +09:00
Trustin Lee
ce35386805 Prevent cross-site scripting 2012-09-29 17:18:18 +09:00
Trustin Lee
9f6505192c Simplify if 2012-09-28 16:59:51 +09:00
Trustin Lee
eae7b2d662 [#532] HttpStaticFileServer should generate an index page
* Add index page listing and directory redirection
2012-09-28 16:58:26 +09:00
Trustin Lee
045b621b3f [#441] Update HTTP examples so that they understand DecoderResult 2012-09-28 15:42:38 +09:00
Trustin Lee
876847fd20 Merge MessageBufs and ByteBufs into Unpooled
- e.g. Unpooled.messageBuffer()
- It will make much more sense once we introduce pooling:
  - i.e. Pooled.buffer()
2012-06-11 17:02:29 +09:00
Trustin Lee
a849d11877 ChannelBuffers -> ByteBufs / Add MessageBuf & ChannelBuf
- Add MessageBuf which replaces java.util.Queue
- Add ChannelBuf which is common type of ByteBuf and ChannelBuf
- ChannelBuffers was renamed to ByteBufs
- Add MessageBufs
- All these changes are going to replace ChannelBufferHolder.
2012-06-10 11:31:39 +09:00
Trustin Lee
468a3228a4 Fit every line into 120 columns 2012-06-08 19:28:12 +09:00
Trustin Lee
5e93d206ff Overhaul - Split ChannelHandler & Merge ChannelHandlerContext
- Extracted some handler methods from ChannelInboundHandler into
  ChannelStateHandler
- Extracted some handler methods from ChannelOutboundHandler into
  ChannelOperationHandler
- Moved exceptionCaught and userEventTriggered are now in
  ChannelHandler
  
- Channel(Inbound|Outbound)HandlerContext is merged into
  ChannelHandlerContext
- ChannelHandlerContext adds direct access methods for inboud and
  outbound buffers
  - The use of ChannelBufferHolder is minimal now.
    - Before: inbound().byteBuffer()
    - After: inboundByteBuffer()
    - Simpler and better performance
    
- Bypass buffer types were removed because it just does not work at all
  with the thread model.
  - All handlers that uses a bypass buffer are broken.  Will fix soon.

- CombinedHandlerAdapter does not make sense anymore either because
  there are four handler interfaces to consider and often the two
  handlers will implement the same handler interface such as
  ChannelStateHandler.  Thinking of better ways to provide this feature
2012-06-07 14:52:33 +09:00
Trustin Lee
1eced1e9e3 Update license headers 2012-06-04 13:31:44 -07:00
Trustin Lee
8237afff64 Ported most examples
- Renamed ChannelBootstrap to Bootstrap
- Renamed ServerChannelBootstrap to ServerBootstrap
- Moved bootstrap classes to io.netty.bootstrap as before
- Moved unfoldAndAdd() to a separate utility class
- Fixed a bug in unfoldAndAdd() where it did not handle ChannelBuffer
  correctly
2012-05-29 16:41:26 -07:00
Trustin Lee
92a688e5b2 Retrofit the codec framework with the new API (in progress)
- Replaced FrameDecoder and OneToOne(Encoder|Decoder) with:
  - (Stream|Message)To(String|Message)(Encoder|Decoder)
- Moved the classes in 'codec.frame' up to 'codec'
- Fixed some bugs found while running unit tests
2012-05-16 23:02:06 +09:00
Trustin Lee
368156f5d0 Another round of the new API design
- Channel now creates a ChannelPipeline by itself

  I find no reason to allow a user to use one's own pipeline
  implementation since I saw nobody does except for the cases where a
  user wants to add a user attribute to a channel, which is now covered
  by AttributeMap.

- Removed ChannelEvent and its subtypes because they are replaced by
  direct method invocation.
- Replaced ChannelSink with Channel.unsafe()
- Various getter renaming (e.g. Channel.getId() -> Channel.id())
- Added ChannelHandlerInvoker interface
- Implemented AbstractChannel and AbstractServerChannel
- Some other changes I don't remember
2012-05-01 17:19:41 +09:00
vibul
64f5299452 Unless the Connection: keep-alive header is present in the HTTP response, apache benchmark (ab) hangs on keep alive connections.
This is as per HTTP 1.1 spec:  http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection
2012-03-28 15:50:17 +11:00
Trustin Lee
ebfc4513e0 Apply checkstyle to the build
Please note that the build will fail at the moment due to various checkstyle
violations which should be fixed soon
2012-01-11 20:16:14 +09:00