View Javadoc
1   /*
2    * Copyright 2019 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.codec.http.websocketx;
17  
18  import io.netty.channel.ChannelFuture;
19  import io.netty.channel.ChannelFutureListener;
20  import io.netty.channel.ChannelHandlerContext;
21  import io.netty.channel.ChannelInboundHandlerAdapter;
22  import io.netty.channel.ChannelPromise;
23  import io.netty.handler.codec.http.DefaultFullHttpResponse;
24  import io.netty.handler.codec.http.FullHttpResponse;
25  import io.netty.handler.codec.http.HttpHeaderNames;
26  import io.netty.handler.codec.http.HttpObject;
27  import io.netty.handler.codec.http.HttpRequest;
28  import io.netty.handler.codec.http.HttpResponse;
29  import io.netty.handler.codec.http.HttpResponseStatus;
30  import io.netty.handler.codec.http.HttpVersion;
31  import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.ServerHandshakeStateEvent;
32  import io.netty.handler.ssl.SslHandler;
33  import io.netty.util.ReferenceCountUtil;
34  import io.netty.util.concurrent.Future;
35  
36  import java.util.Locale;
37  import java.util.Set;
38  import java.util.concurrent.TimeUnit;
39  
40  import static io.netty.handler.codec.http.HttpUtil.*;
41  import static io.netty.util.internal.ObjectUtil.*;
42  
43  /**
44   * Handles the HTTP handshake (the HTTP Upgrade request) for {@link WebSocketServerProtocolHandler}.
45   */
46  class WebSocketServerProtocolHandshakeHandler extends ChannelInboundHandlerAdapter {
47  
48      private final WebSocketServerProtocolConfig serverConfig;
49      private ChannelHandlerContext ctx;
50      private ChannelPromise handshakePromise;
51      private boolean isWebSocketPath;
52  
53      WebSocketServerProtocolHandshakeHandler(WebSocketServerProtocolConfig serverConfig) {
54          this.serverConfig = checkNotNull(serverConfig, "serverConfig");
55      }
56  
57      @Override
58      public void handlerAdded(ChannelHandlerContext ctx) {
59          this.ctx = ctx;
60          handshakePromise = ctx.newPromise();
61      }
62  
63      @Override
64      public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
65          final HttpObject httpObject = (HttpObject) msg;
66  
67          if (httpObject instanceof HttpRequest) {
68              final HttpRequest req = (HttpRequest) httpObject;
69              isWebSocketPath = isWebSocketPath(req);
70              if (!isWebSocketPath) {
71                  ctx.fireChannelRead(msg);
72                  return;
73              }
74  
75              try {
76                  if (!isOriginAllowed(req)) {
77                      // Do this before anything else so no upgrade response is ever written.
78                      sendForbiddenResponse(ctx);
79                      return;
80                  }
81                  final boolean isSecure = ctx.pipeline().get(SslHandler.class) != null;
82                  final String host = req.headers().get(HttpHeaderNames.HOST);
83                  final WebSocketServerHandshaker handshaker = WebSocketServerHandshakerFactory.resolveHandshaker(
84                          req, isSecure, host, serverConfig.websocketPath(),
85                          serverConfig.subprotocols(), serverConfig.decoderConfig());
86                  final ChannelPromise localHandshakePromise = handshakePromise;
87                  if (handshaker == null) {
88                      WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
89                  } else {
90                      // Ensure we set the handshaker and replace this handler before we
91                      // trigger the actual handshake. Otherwise we may receive websocket bytes in this handler
92                      // before we had a chance to replace it.
93                      //
94                      // See https://github.com/netty/netty/issues/9471.
95                      WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);
96                      ctx.pipeline().remove(this);
97  
98                      // The write via the removed handler's ctx still starts at this handler's former position.
99                      final ChannelFuture handshakeFuture = handshaker.handshake(ctx, req);
100                     handshakeFuture.addListener(future -> {
101                         if (!future.isSuccess()) {
102                             localHandshakePromise.tryFailure(future.cause());
103                             ctx.fireExceptionCaught(future.cause());
104                         } else {
105                             localHandshakePromise.trySuccess();
106                             // Kept for compatibility
107                             ctx.fireUserEventTriggered(
108                                     ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
109                             ctx.fireUserEventTriggered(
110                                     new WebSocketServerProtocolHandler.HandshakeComplete(
111                                             req.uri(), req.headers(), handshaker.selectedSubprotocol()));
112                         }
113                     });
114                     applyHandshakeTimeout();
115                 }
116             } finally {
117                 ReferenceCountUtil.release(req);
118             }
119         } else if (!isWebSocketPath) {
120             ctx.fireChannelRead(msg);
121         } else {
122             ReferenceCountUtil.release(msg);
123         }
124     }
125 
126     private boolean isOriginAllowed(HttpRequest req) {
127         Set<String> allowedOrigins = serverConfig.allowedOrigins();
128         if (allowedOrigins.isEmpty()) {
129             return true;
130         }
131         // Every Origin / Sec-WebSocket-Origin header value must be allowed, a missing header means the request did
132         // not come from a browser. Sec-WebSocket-Origin is what browsers speaking the older hybi-07 / hybi-08
133         // protocol versions send instead of Origin.
134         return areOriginsAllowed(req, HttpHeaderNames.ORIGIN, allowedOrigins) &&
135                 areOriginsAllowed(req, HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, allowedOrigins);
136     }
137 
138     private static boolean areOriginsAllowed(HttpRequest req, CharSequence headerName, Set<String> allowedOrigins) {
139         for (String origin : req.headers().getAll(headerName)) {
140             if (!allowedOrigins.contains(origin.trim().toLowerCase(Locale.ROOT))) {
141                 return false;
142             }
143         }
144         return true;
145     }
146 
147     private static void sendForbiddenResponse(ChannelHandlerContext ctx) {
148         FullHttpResponse res = new DefaultFullHttpResponse(
149                 HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN, ctx.alloc().buffer(0));
150         setContentLength(res, 0);
151         setKeepAlive(res, false);
152         ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
153     }
154 
155     private boolean isWebSocketPath(HttpRequest req) {
156         String websocketPath = serverConfig.websocketPath();
157         String uri = req.uri();
158         return serverConfig.checkStartsWith()
159                 ? uri.startsWith(websocketPath) && ("/".equals(websocketPath) || checkNextUri(uri, websocketPath))
160                 : uri.equals(websocketPath);
161     }
162 
163     private boolean checkNextUri(String uri, String websocketPath) {
164         int len = websocketPath.length();
165         if (uri.length() > len) {
166             char nextUri = uri.charAt(len);
167             return nextUri == '/' || nextUri == '?';
168         }
169         return true;
170     }
171 
172     private void applyHandshakeTimeout() {
173         final ChannelPromise localHandshakePromise = handshakePromise;
174         final long handshakeTimeoutMillis = serverConfig.handshakeTimeoutMillis();
175         if (handshakeTimeoutMillis <= 0 || localHandshakePromise.isDone()) {
176             return;
177         }
178 
179         final Future<?> timeoutFuture = ctx.executor().schedule(new Runnable() {
180             @Override
181             public void run() {
182                 if (!localHandshakePromise.isDone() &&
183                     localHandshakePromise.tryFailure(new WebSocketServerHandshakeException("handshake timed out"))) {
184                     ctx.flush()
185                        .fireUserEventTriggered(ServerHandshakeStateEvent.HANDSHAKE_TIMEOUT)
186                        .close();
187                 }
188             }
189         }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
190 
191         // Cancel the handshake timeout when handshake is finished.
192         localHandshakePromise.addListener(f -> timeoutFuture.cancel(false));
193     }
194 }