View Javadoc
1   /*
2    * Copyright 2014 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.ssl;
17  
18  import io.netty.buffer.ByteBufAllocator;
19  import io.netty.channel.ChannelHandlerContext;
20  import io.netty.handler.codec.DecoderException;
21  import io.netty.util.AsyncMapping;
22  import io.netty.util.DomainNameMapping;
23  import io.netty.util.Mapping;
24  import io.netty.util.ReferenceCountUtil;
25  import io.netty.util.concurrent.Future;
26  import io.netty.util.concurrent.Promise;
27  import io.netty.util.internal.ObjectUtil;
28  import io.netty.util.internal.PlatformDependent;
29  
30  /**
31   * <p>Enables <a href="https://tools.ietf.org/html/rfc3546#section-3.1">SNI
32   * (Server Name Indication)</a> extension for server side SSL. For clients
33   * support SNI, the server could have multiple host name bound on a single IP.
34   * The client will send host name in the handshake data so server could decide
35   * which certificate to choose for the host name.</p>
36   */
37  public class SniHandler extends AbstractSniHandler<SslContext> {
38      private static final Selection EMPTY_SELECTION = new Selection(null, null);
39  
40      protected final AsyncMapping<String, SslContext> mapping;
41  
42      private volatile Selection selection = EMPTY_SELECTION;
43  
44      /**
45       * Creates a SNI detection handler with configured {@link SslContext}
46       * maintained by {@link Mapping}
47       *
48       * @param mapping the mapping of domain name to {@link SslContext}
49       */
50      public SniHandler(Mapping<? super String, ? extends SslContext> mapping) {
51          this(new AsyncMappingAdapter(mapping));
52      }
53  
54      /**
55       * Creates a SNI detection handler with configured {@link SslContext}
56       * maintained by {@link DomainNameMapping}
57       *
58       * @param mapping the mapping of domain name to {@link SslContext}
59       */
60      public SniHandler(DomainNameMapping<? extends SslContext> mapping) {
61          this((Mapping<String, ? extends SslContext>) mapping);
62      }
63  
64      /**
65       * Creates a SNI detection handler with configured {@link SslContext}
66       * maintained by {@link AsyncMapping}
67       *
68       * @param mapping the mapping of domain name to {@link SslContext}
69       */
70      @SuppressWarnings("unchecked")
71      public SniHandler(AsyncMapping<? super String, ? extends SslContext> mapping) {
72          this.mapping = (AsyncMapping<String, SslContext>) ObjectUtil.checkNotNull(mapping, "mapping");
73      }
74  
75      /**
76       * @return the selected hostname
77       */
78      public String hostname() {
79          return selection.hostname;
80      }
81  
82      /**
83       * @return the selected {@link SslContext}
84       */
85      public SslContext sslContext() {
86          return selection.context;
87      }
88  
89      /**
90       * The default implementation will simply call {@link AsyncMapping#map(Object, Promise)} but
91       * users can override this method to implement custom behavior.
92       *
93       * @see AsyncMapping#map(Object, Promise)
94       */
95      @Override
96      protected Future<SslContext> lookup(ChannelHandlerContext ctx, String hostname) throws Exception {
97          return mapping.map(hostname, ctx.executor().<SslContext>newPromise());
98      }
99  
100     @Override
101     protected final void onLookupComplete(ChannelHandlerContext ctx,
102                                           String hostname, Future<SslContext> future) throws Exception {
103         if (!future.isSuccess()) {
104             final Throwable cause = future.cause();
105             if (cause instanceof Error) {
106                 throw (Error) cause;
107             }
108             throw new DecoderException("failed to get the SslContext for " + hostname, cause);
109         }
110 
111         SslContext sslContext = future.getNow();
112         selection = new Selection(sslContext, hostname);
113         try {
114             replaceHandler(ctx, hostname, sslContext);
115         } catch (Throwable cause) {
116             selection = EMPTY_SELECTION;
117             PlatformDependent.throwException(cause);
118         }
119     }
120 
121     /**
122      * The default implementation of this method will simply replace {@code this} {@link SniHandler}
123      * instance with a {@link SslHandler}. Users may override this method to implement custom behavior.
124      *
125      * Please be aware that this method may get called after a client has already disconnected and
126      * custom implementations must take it into consideration when overriding this method.
127      *
128      * It's also possible for the hostname argument to be {@code null}.
129      */
130     protected void replaceHandler(ChannelHandlerContext ctx, String hostname, SslContext sslContext) throws Exception {
131         SslHandler sslHandler = null;
132         try {
133             sslHandler = newSslHandler(sslContext, ctx.alloc());
134             ctx.pipeline().replace(this, SslHandler.class.getName(), sslHandler);
135             sslHandler = null;
136         } finally {
137             // Since the SslHandler was not inserted into the pipeline the ownership of the SSLEngine was not
138             // transferred to the SslHandler.
139             // See https://github.com/netty/netty/issues/5678
140             if (sslHandler != null) {
141                 ReferenceCountUtil.safeRelease(sslHandler.engine());
142             }
143         }
144     }
145 
146     /**
147      * Returns a new {@link SslHandler} using the given {@link SslContext} and {@link ByteBufAllocator}.
148      * Users may override this method to implement custom behavior.
149      */
150     protected SslHandler newSslHandler(SslContext context, ByteBufAllocator allocator) {
151         return context.newHandler(allocator);
152     }
153 
154     private static final class AsyncMappingAdapter implements AsyncMapping<String, SslContext> {
155         private final Mapping<? super String, ? extends SslContext> mapping;
156 
157         private AsyncMappingAdapter(Mapping<? super String, ? extends SslContext> mapping) {
158             this.mapping = ObjectUtil.checkNotNull(mapping, "mapping");
159         }
160 
161         @Override
162         public Future<SslContext> map(String input, Promise<SslContext> promise) {
163             final SslContext context;
164             try {
165                 context = mapping.map(input);
166             } catch (Throwable cause) {
167                 return promise.setFailure(cause);
168             }
169             return promise.setSuccess(context);
170         }
171     }
172 
173     private static final class Selection {
174         final SslContext context;
175         final String hostname;
176 
177         Selection(SslContext context, String hostname) {
178             this.context = context;
179             this.hostname = hostname;
180         }
181     }
182 }