View Javadoc
1   /*
2    * Copyright 2013 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License, version
5    * 2.0 (the "License"); you may not use this file except in compliance with the
6    * License. You may obtain a copy of the License at:
7    *
8    * http://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 under
14   * the License.
15   */
16  package io.netty.handler.codec.http.cors;
17  
18  import io.netty.channel.ChannelDuplexHandler;
19  import io.netty.channel.ChannelFuture;
20  import io.netty.channel.ChannelFutureListener;
21  import io.netty.channel.ChannelHandlerContext;
22  import io.netty.channel.ChannelPromise;
23  import io.netty.handler.codec.http.DefaultFullHttpResponse;
24  import io.netty.handler.codec.http.HttpHeaderNames;
25  import io.netty.handler.codec.http.HttpHeaderValues;
26  import io.netty.handler.codec.http.HttpHeaders;
27  import io.netty.handler.codec.http.HttpRequest;
28  import io.netty.handler.codec.http.HttpResponse;
29  import io.netty.handler.codec.http.HttpUtil;
30  import io.netty.util.internal.logging.InternalLogger;
31  import io.netty.util.internal.logging.InternalLoggerFactory;
32  
33  import static io.netty.handler.codec.http.HttpMethod.*;
34  import static io.netty.handler.codec.http.HttpResponseStatus.*;
35  import static io.netty.util.ReferenceCountUtil.*;
36  import static io.netty.util.internal.ObjectUtil.checkNotNull;
37  
38  /**
39   * Handles <a href="http://www.w3.org/TR/cors/">Cross Origin Resource Sharing</a> (CORS) requests.
40   * <p>
41   * This handler can be configured using a {@link CorsConfig}, please
42   * refer to this class for details about the configuration options available.
43   */
44  public class CorsHandler extends ChannelDuplexHandler {
45  
46      private static final InternalLogger logger = InternalLoggerFactory.getInstance(CorsHandler.class);
47      private static final String ANY_ORIGIN = "*";
48      private static final String NULL_ORIGIN = "null";
49      private final CorsConfig config;
50  
51      private HttpRequest request;
52  
53      /**
54       * Creates a new instance with the specified {@link CorsConfig}.
55       */
56      public CorsHandler(final CorsConfig config) {
57          this.config = checkNotNull(config, "config");
58      }
59  
60      @Override
61      public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
62          if (config.isCorsSupportEnabled() && msg instanceof HttpRequest) {
63              request = (HttpRequest) msg;
64              if (isPreflightRequest(request)) {
65                  handlePreflight(ctx, request);
66                  return;
67              }
68              if (config.isShortCircuit() && !validateOrigin()) {
69                  forbidden(ctx, request);
70                  return;
71              }
72          }
73          ctx.fireChannelRead(msg);
74      }
75  
76      private void handlePreflight(final ChannelHandlerContext ctx, final HttpRequest request) {
77          final HttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), OK, true, true);
78          if (setOrigin(response)) {
79              setAllowMethods(response);
80              setAllowHeaders(response);
81              setAllowCredentials(response);
82              setMaxAge(response);
83              setPreflightHeaders(response);
84          }
85          if (!response.headers().contains(HttpHeaderNames.CONTENT_LENGTH)) {
86              response.headers().set(HttpHeaderNames.CONTENT_LENGTH, HttpHeaderValues.ZERO);
87          }
88          release(request);
89          respond(ctx, request, response);
90      }
91  
92      /**
93       * This is a non CORS specification feature which enables the setting of preflight
94       * response headers that might be required by intermediaries.
95       *
96       * @param response the HttpResponse to which the preflight response headers should be added.
97       */
98      private void setPreflightHeaders(final HttpResponse response) {
99          response.headers().add(config.preflightResponseHeaders());
100     }
101 
102     private boolean setOrigin(final HttpResponse response) {
103         final String origin = request.headers().get(HttpHeaderNames.ORIGIN);
104         if (origin != null) {
105             if (NULL_ORIGIN.equals(origin) && config.isNullOriginAllowed()) {
106                 setNullOrigin(response);
107                 return true;
108             }
109             if (config.isAnyOriginSupported()) {
110                 if (config.isCredentialsAllowed()) {
111                     echoRequestOrigin(response);
112                     setVaryHeader(response);
113                 } else {
114                     setAnyOrigin(response);
115                 }
116                 return true;
117             }
118             if (config.origins().contains(origin)) {
119                 setOrigin(response, origin);
120                 setVaryHeader(response);
121                 return true;
122             }
123             logger.debug("Request origin [{}]] was not among the configured origins [{}]", origin, config.origins());
124         }
125         return false;
126     }
127 
128     private boolean validateOrigin() {
129         if (config.isAnyOriginSupported()) {
130             return true;
131         }
132 
133         final String origin = request.headers().get(HttpHeaderNames.ORIGIN);
134         if (origin == null) {
135             // Not a CORS request so we cannot validate it. It may be a non CORS request.
136             return true;
137         }
138 
139         if ("null".equals(origin) && config.isNullOriginAllowed()) {
140             return true;
141         }
142 
143         return config.origins().contains(origin);
144     }
145 
146     private void echoRequestOrigin(final HttpResponse response) {
147         setOrigin(response, request.headers().get(HttpHeaderNames.ORIGIN));
148     }
149 
150     private static void setVaryHeader(final HttpResponse response) {
151         response.headers().set(HttpHeaderNames.VARY, HttpHeaderNames.ORIGIN);
152     }
153 
154     private static void setAnyOrigin(final HttpResponse response) {
155         setOrigin(response, ANY_ORIGIN);
156     }
157 
158     private static void setNullOrigin(final HttpResponse response) {
159         setOrigin(response, NULL_ORIGIN);
160     }
161 
162     private static void setOrigin(final HttpResponse response, final String origin) {
163         response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
164     }
165 
166     private void setAllowCredentials(final HttpResponse response) {
167         if (config.isCredentialsAllowed()
168                 && !response.headers().get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN).equals(ANY_ORIGIN)) {
169             response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
170         }
171     }
172 
173     private static boolean isPreflightRequest(final HttpRequest request) {
174         final HttpHeaders headers = request.headers();
175         return request.method().equals(OPTIONS) &&
176                 headers.contains(HttpHeaderNames.ORIGIN) &&
177                 headers.contains(HttpHeaderNames.ACCESS_CONTROL_REQUEST_METHOD);
178     }
179 
180     private void setExposeHeaders(final HttpResponse response) {
181         if (!config.exposedHeaders().isEmpty()) {
182             response.headers().set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, config.exposedHeaders());
183         }
184     }
185 
186     private void setAllowMethods(final HttpResponse response) {
187         response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, config.allowedRequestMethods());
188     }
189 
190     private void setAllowHeaders(final HttpResponse response) {
191         response.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, config.allowedRequestHeaders());
192     }
193 
194     private void setMaxAge(final HttpResponse response) {
195         response.headers().set(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE, config.maxAge());
196     }
197 
198     @Override
199     public void write(final ChannelHandlerContext ctx, final Object msg, final ChannelPromise promise)
200             throws Exception {
201         if (config.isCorsSupportEnabled() && msg instanceof HttpResponse) {
202             final HttpResponse response = (HttpResponse) msg;
203             if (setOrigin(response)) {
204                 setAllowCredentials(response);
205                 setExposeHeaders(response);
206             }
207         }
208         ctx.writeAndFlush(msg, promise);
209     }
210 
211     private static void forbidden(final ChannelHandlerContext ctx, final HttpRequest request) {
212         HttpResponse response = new DefaultFullHttpResponse(request.protocolVersion(), FORBIDDEN);
213         response.headers().set(HttpHeaderNames.CONTENT_LENGTH, HttpHeaderValues.ZERO);
214         release(request);
215         respond(ctx, request, response);
216     }
217 
218     private static void respond(
219             final ChannelHandlerContext ctx,
220             final HttpRequest request,
221             final HttpResponse response) {
222 
223         final boolean keepAlive = HttpUtil.isKeepAlive(request);
224 
225         HttpUtil.setKeepAlive(response, keepAlive);
226 
227         final ChannelFuture future = ctx.writeAndFlush(response);
228         if (!keepAlive) {
229             future.addListener(ChannelFutureListener.CLOSE);
230         }
231     }
232 }