View Javadoc
1   /*
2    * Copyright 2015 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.channel.Channel;
19  import io.netty.channel.ChannelHandlerContext;
20  import io.netty.channel.ChannelInboundHandlerAdapter;
21  import io.netty.channel.ChannelInitializer;
22  import io.netty.channel.ChannelPipeline;
23  import io.netty.channel.socket.ChannelInputShutdownEvent;
24  import io.netty.handler.codec.DecoderException;
25  import io.netty.util.internal.ObjectUtil;
26  import io.netty.util.internal.RecyclableArrayList;
27  import io.netty.util.internal.logging.InternalLogger;
28  import io.netty.util.internal.logging.InternalLoggerFactory;
29  
30  import java.nio.channels.ClosedChannelException;
31  import javax.net.ssl.SSLException;
32  
33  /**
34   * Configures a {@link ChannelPipeline} depending on the application-level protocol negotiation result of
35   * {@link SslHandler}.  For example, you could configure your HTTP pipeline depending on the result of ALPN:
36   * <pre>
37   * public class MyInitializer extends {@link ChannelInitializer}&lt;{@link Channel}&gt; {
38   *     private final {@link SslContext} sslCtx;
39   *
40   *     public MyInitializer({@link SslContext} sslCtx) {
41   *         this.sslCtx = sslCtx;
42   *     }
43   *
44   *     protected void initChannel({@link Channel} ch) {
45   *         {@link ChannelPipeline} p = ch.pipeline();
46   *         p.addLast(sslCtx.newHandler(...)); // Adds {@link SslHandler}
47   *         p.addLast(new MyNegotiationHandler());
48   *     }
49   * }
50   *
51   * public class MyNegotiationHandler extends {@link ApplicationProtocolNegotiationHandler} {
52   *     public MyNegotiationHandler() {
53   *         super({@link ApplicationProtocolNames}.HTTP_1_1);
54   *     }
55   *
56   *     protected void configurePipeline({@link ChannelHandlerContext} ctx, String protocol) {
57   *         if ({@link ApplicationProtocolNames}.HTTP_2.equals(protocol) {
58   *             configureHttp2(ctx);
59   *         } else if ({@link ApplicationProtocolNames}.HTTP_1_1.equals(protocol)) {
60   *             configureHttp1(ctx);
61   *         } else {
62   *             throw new IllegalStateException("unknown protocol: " + protocol);
63   *         }
64   *     }
65   * }
66   * </pre>
67   */
68  public abstract class ApplicationProtocolNegotiationHandler extends ChannelInboundHandlerAdapter {
69  
70      private static final InternalLogger logger =
71              InternalLoggerFactory.getInstance(ApplicationProtocolNegotiationHandler.class);
72  
73      private final String fallbackProtocol;
74      private final RecyclableArrayList bufferedMessages = RecyclableArrayList.newInstance();
75      private ChannelHandlerContext ctx;
76      private boolean sslHandlerChecked;
77      private boolean handshakeFailed;
78  
79      /**
80       * Creates a new instance with the specified fallback protocol name.
81       *
82       * @param fallbackProtocol the name of the protocol to use when
83       *                         ALPN/NPN negotiation fails or the client does not support ALPN/NPN
84       */
85      protected ApplicationProtocolNegotiationHandler(String fallbackProtocol) {
86          this.fallbackProtocol = ObjectUtil.checkNotNull(fallbackProtocol, "fallbackProtocol");
87      }
88  
89      @Override
90      public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
91          this.ctx = ctx;
92          super.handlerAdded(ctx);
93      }
94  
95      @Override
96      public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
97          fireBufferedMessages();
98          bufferedMessages.recycle();
99          super.handlerRemoved(ctx);
100     }
101 
102     @Override
103     public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
104         // Let's buffer all data until this handler will be removed from the pipeline.
105         bufferedMessages.add(msg);
106         if (!sslHandlerChecked) {
107             sslHandlerChecked = true;
108             if (ctx.pipeline().get(SslHandler.class) == null) {
109                 // Just remove ourself if there is no SslHandler in the pipeline and so we would otherwise
110                 // buffer forever.
111                 removeSelfIfPresent(ctx);
112             }
113         }
114     }
115 
116     /**
117      * Process all backlog into pipeline from List.
118      */
119     private void fireBufferedMessages() {
120         if (!bufferedMessages.isEmpty()) {
121             for (int i = 0; i < bufferedMessages.size(); i++) {
122                 ctx.fireChannelRead(bufferedMessages.get(i));
123             }
124             ctx.fireChannelReadComplete();
125             bufferedMessages.clear();
126         }
127     }
128 
129     @Override
130     public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
131         if (evt instanceof SslHandshakeCompletionEvent) {
132             SslHandshakeCompletionEvent handshakeEvent = (SslHandshakeCompletionEvent) evt;
133             try {
134                 if (handshakeEvent.isSuccess()) {
135                     SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
136                     if (sslHandler == null) {
137                         throw new IllegalStateException("cannot find an SslHandler in the pipeline (required for "
138                                 + "application-level protocol negotiation)");
139                     }
140                     String protocol = sslHandler.applicationProtocol();
141                     configurePipeline(ctx, protocol != null ? protocol : fallbackProtocol);
142                 } else {
143                     // timeouts and early closes may not produce a decoder exception
144                     // preserve the existing exception and close handling for other TLS failures
145                     Throwable cause = handshakeEvent.cause();
146                     if (cause instanceof SslHandshakeTimeoutException || cause instanceof ClosedChannelException) {
147                         try {
148                             super.userEventTriggered(ctx, evt);
149                         } finally {
150                             notifyHandshakeFailure(ctx, cause);
151                         }
152 
153                         return;
154                     }
155                 }
156             } catch (Throwable cause) {
157                 exceptionCaught(ctx, cause);
158             } finally {
159                 // keep the handler after failure to consume later SSL decoder exceptions
160                 // see https://github.com/netty/netty/issues/10342
161                 if (handshakeEvent.isSuccess()) {
162                     removeSelfIfPresent(ctx);
163                 }
164             }
165         }
166 
167         if (evt instanceof ChannelInputShutdownEvent) {
168             fireBufferedMessages();
169         }
170 
171         ctx.fireUserEventTriggered(evt);
172     }
173 
174     @Override
175     public void channelInactive(ChannelHandlerContext ctx) throws Exception {
176         fireBufferedMessages();
177         super.channelInactive(ctx);
178     }
179 
180     private void removeSelfIfPresent(ChannelHandlerContext ctx) {
181         ChannelPipeline pipeline = ctx.pipeline();
182         if (!ctx.isRemoved()) {
183             pipeline.remove(this);
184         }
185     }
186 
187     /**
188      * Invoked on successful initial SSL/TLS handshake. Implement this method to configure your pipeline
189      * for the negotiated application-level protocol.
190      *
191      * @param protocol the name of the negotiated application-level protocol, or
192      *                 the fallback protocol name specified in the constructor call if negotiation failed or the client
193      *                 isn't aware of ALPN/NPN extension
194      */
195     protected abstract void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception;
196 
197     /**
198      * Invoked on failed initial SSL/TLS handshake.
199      */
200     protected void handshakeFailure(ChannelHandlerContext ctx, Throwable cause) throws Exception {
201         logger.warn("{} TLS handshake failed:", ctx.channel(), cause);
202         ctx.close();
203     }
204 
205     private void notifyHandshakeFailure(ChannelHandlerContext ctx, Throwable cause) throws Exception {
206         if (!handshakeFailed) {
207             handshakeFailed = true;
208 
209             try {
210                 handshakeFailure(ctx, cause);
211             } catch (Throwable innerCause) {
212                 exceptionCaught(ctx, innerCause);
213             }
214         }
215     }
216 
217     @Override
218     public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
219         Throwable wrapped;
220         if (cause instanceof DecoderException && ((wrapped = cause.getCause()) instanceof SSLException)) {
221             try {
222                 notifyHandshakeFailure(ctx, wrapped);
223                 return;
224             } finally {
225                 removeSelfIfPresent(ctx);
226             }
227         }
228         logger.warn("{} Failed to select the application-level protocol:", ctx.channel(), cause);
229         ctx.fireExceptionCaught(cause);
230         ctx.close();
231     }
232 }