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.ChannelPipeline;
23  import io.netty.channel.ChannelPromise;
24  import io.netty.handler.codec.http.DefaultFullHttpResponse;
25  import io.netty.handler.codec.http.FullHttpResponse;
26  import io.netty.handler.codec.http.HttpHeaderNames;
27  import io.netty.handler.codec.http.HttpObject;
28  import io.netty.handler.codec.http.HttpRequest;
29  import io.netty.handler.codec.http.HttpResponse;
30  import io.netty.handler.codec.http.HttpResponseStatus;
31  import io.netty.handler.codec.http.HttpVersion;
32  import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler.ServerHandshakeStateEvent;
33  import io.netty.handler.ssl.SslHandler;
34  import io.netty.util.ReferenceCountUtil;
35  import io.netty.util.concurrent.Future;
36  import io.netty.util.concurrent.FutureListener;
37  
38  import java.util.Locale;
39  import java.util.Set;
40  import java.util.concurrent.TimeUnit;
41  
42  import static io.netty.handler.codec.http.HttpUtil.*;
43  import static io.netty.util.internal.ObjectUtil.*;
44  
45  /**
46   * Handles the HTTP handshake (the HTTP Upgrade request) for {@link WebSocketServerProtocolHandler}.
47   */
48  class WebSocketServerProtocolHandshakeHandler extends ChannelInboundHandlerAdapter {
49  
50      private final WebSocketServerProtocolConfig serverConfig;
51      private ChannelHandlerContext ctx;
52      private ChannelPromise handshakePromise;
53      private boolean isWebSocketPath;
54  
55      WebSocketServerProtocolHandshakeHandler(WebSocketServerProtocolConfig serverConfig) {
56          this.serverConfig = checkNotNull(serverConfig, "serverConfig");
57      }
58  
59      @Override
60      public void handlerAdded(ChannelHandlerContext ctx) {
61          this.ctx = ctx;
62          handshakePromise = ctx.newPromise();
63      }
64  
65      @Override
66      public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
67          final HttpObject httpObject = (HttpObject) msg;
68  
69          if (httpObject instanceof HttpRequest) {
70              final HttpRequest req = (HttpRequest) httpObject;
71              isWebSocketPath = isWebSocketPath(req);
72              if (!isWebSocketPath) {
73                  ctx.fireChannelRead(msg);
74                  return;
75              }
76  
77              try {
78                  if (!isOriginAllowed(req)) {
79                      // Do this before anything else so no upgrade response is ever written.
80                      sendForbiddenResponse(ctx);
81                      return;
82                  }
83                  final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
84                          getWebSocketLocation(ctx.pipeline(), req, serverConfig.websocketPath()),
85                          serverConfig.subprotocols(), serverConfig.decoderConfig());
86                  final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
87                  final ChannelPromise localHandshakePromise = handshakePromise;
88                  if (handshaker == null) {
89                      WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
90                  } else {
91                      // Ensure we set the handshaker and replace this handler before we
92                      // trigger the actual handshake. Otherwise we may receive websocket bytes in this handler
93                      // before we had a chance to replace it.
94                      //
95                      // See https://github.com/netty/netty/issues/9471.
96                      WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);
97                      ctx.pipeline().remove(this);
98  
99                      final ChannelFuture handshakeFuture = handshaker.handshake(ctx, req);
100                     handshakeFuture.addListener(new ChannelFutureListener() {
101                         @Override
102                         public void operationComplete(ChannelFuture future) {
103                             if (!future.isSuccess()) {
104                                 localHandshakePromise.tryFailure(future.cause());
105                                 ctx.fireExceptionCaught(future.cause());
106                             } else {
107                                 localHandshakePromise.trySuccess();
108                                 // Kept for compatibility
109                                 ctx.fireUserEventTriggered(
110                                         WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
111                                 ctx.fireUserEventTriggered(
112                                         new WebSocketServerProtocolHandler.HandshakeComplete(
113                                                 req.uri(), req.headers(), handshaker.selectedSubprotocol()));
114                             }
115                         }
116                     });
117                     applyHandshakeTimeout();
118                 }
119             } finally {
120                 ReferenceCountUtil.release(req);
121             }
122         } else if (!isWebSocketPath) {
123             ctx.fireChannelRead(msg);
124         } else {
125             ReferenceCountUtil.release(msg);
126         }
127     }
128 
129     private boolean isOriginAllowed(HttpRequest req) {
130         Set<String> allowedOrigins = serverConfig.allowedOrigins();
131         if (allowedOrigins.isEmpty()) {
132             return true;
133         }
134         // Every Origin / Sec-WebSocket-Origin header value must be allowed, a missing header means the request did
135         // not come from a browser. Sec-WebSocket-Origin is what browsers speaking the older hybi-07 / hybi-08
136         // protocol versions send instead of Origin.
137         return areOriginsAllowed(req, HttpHeaderNames.ORIGIN, allowedOrigins) &&
138                 areOriginsAllowed(req, HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, allowedOrigins);
139     }
140 
141     private static boolean areOriginsAllowed(HttpRequest req, CharSequence headerName, Set<String> allowedOrigins) {
142         for (String origin : req.headers().getAll(headerName)) {
143             if (!allowedOrigins.contains(origin.trim().toLowerCase(Locale.ROOT))) {
144                 return false;
145             }
146         }
147         return true;
148     }
149 
150     private static void sendForbiddenResponse(ChannelHandlerContext ctx) {
151         FullHttpResponse res = new DefaultFullHttpResponse(
152                 HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN, ctx.alloc().buffer(0));
153         setContentLength(res, 0);
154         setKeepAlive(res, false);
155         ctx.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
156     }
157 
158     private boolean isWebSocketPath(HttpRequest req) {
159         String websocketPath = serverConfig.websocketPath();
160         String uri = req.uri();
161         return serverConfig.checkStartsWith()
162                 ? uri.startsWith(websocketPath) && ("/".equals(websocketPath) || checkNextUri(uri, websocketPath))
163                 : uri.equals(websocketPath);
164     }
165 
166     private boolean checkNextUri(String uri, String websocketPath) {
167         int len = websocketPath.length();
168         if (uri.length() > len) {
169             char nextUri = uri.charAt(len);
170             return nextUri == '/' || nextUri == '?';
171         }
172         return true;
173     }
174 
175     private static void sendHttpResponse(ChannelHandlerContext ctx, HttpRequest req, HttpResponse res) {
176         ChannelFuture f = ctx.writeAndFlush(res);
177         if (!isKeepAlive(req) || res.status().code() != 200) {
178             f.addListener(ChannelFutureListener.CLOSE);
179         }
180     }
181 
182     private static String getWebSocketLocation(ChannelPipeline cp, HttpRequest req, String path) {
183         String protocol = "ws";
184         if (cp.get(SslHandler.class) != null) {
185             // SSL in use so use Secure WebSockets
186             protocol = "wss";
187         }
188         String host = req.headers().get(HttpHeaderNames.HOST);
189         return protocol + "://" + host + path;
190     }
191 
192     private void applyHandshakeTimeout() {
193         final ChannelPromise localHandshakePromise = handshakePromise;
194         final long handshakeTimeoutMillis = serverConfig.handshakeTimeoutMillis();
195         if (handshakeTimeoutMillis <= 0 || localHandshakePromise.isDone()) {
196             return;
197         }
198 
199         final Future<?> timeoutFuture = ctx.executor().schedule(new Runnable() {
200             @Override
201             public void run() {
202                 if (!localHandshakePromise.isDone() &&
203                     localHandshakePromise.tryFailure(new WebSocketServerHandshakeException("handshake timed out"))) {
204                     ctx.flush()
205                        .fireUserEventTriggered(ServerHandshakeStateEvent.HANDSHAKE_TIMEOUT)
206                        .close();
207                 }
208             }
209         }, handshakeTimeoutMillis, TimeUnit.MILLISECONDS);
210 
211         // Cancel the handshake timeout when handshake is finished.
212         localHandshakePromise.addListener(new FutureListener<Void>() {
213             @Override
214             public void operationComplete(Future<Void> f) {
215                 timeoutFuture.cancel(false);
216             }
217         });
218     }
219 }