Skip to content

Commit

Permalink
Release requests in cors handle (#32410) (#32505)
Browse files Browse the repository at this point in the history
There are two scenarios where a http request could terminate in the cors
handler. If that occurs, the requests need to be released. This commit
releases those requests.
  • Loading branch information
Tim-Brooks authored Jul 31, 2018
1 parent c3fb8fe commit 26b83a5
Showing 1 changed file with 22 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
Expand All @@ -48,7 +49,7 @@ public class Netty4CorsHandler extends ChannelDuplexHandler {
private static Pattern SCHEME_PATTERN = Pattern.compile("^https?://");

private final Netty4CorsConfig config;
private HttpRequest request;
private FullHttpRequest request;

/**
* Creates a new instance with the specified {@link Netty4CorsConfig}.
Expand All @@ -62,15 +63,24 @@ public Netty4CorsHandler(final Netty4CorsConfig config) {

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (config.isCorsSupportEnabled() && msg instanceof HttpRequest) {
request = (HttpRequest) msg;
assert msg instanceof FullHttpRequest : "Invalid message type: " + msg.getClass();
if (config.isCorsSupportEnabled()) {
request = (FullHttpRequest) msg;
if (isPreflightRequest(request)) {
handlePreflight(ctx, request);
return;
try {
handlePreflight(ctx, request);
return;
} finally {
releaseRequest();
}
}
if (config.isShortCircuit() && !validateOrigin()) {
forbidden(ctx, request);
return;
try {
forbidden(ctx, request);
return;
} finally {
releaseRequest();
}
}
}
ctx.fireChannelRead(msg);
Expand Down Expand Up @@ -113,6 +123,11 @@ private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest
}
}

private void releaseRequest() {
request.release();
request = null;
}

private static void forbidden(final ChannelHandlerContext ctx, final HttpRequest request) {
ctx.writeAndFlush(new DefaultFullHttpResponse(request.protocolVersion(), HttpResponseStatus.FORBIDDEN))
.addListener(ChannelFutureListener.CLOSE);
Expand Down

0 comments on commit 26b83a5

Please sign in to comment.