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    *   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
14   * under the License.
15   */
16  
17  package io.netty.example.http2.helloworld.server;
18  
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.SimpleChannelInboundHandler;
24  import io.netty.channel.socket.SocketChannel;
25  import io.netty.handler.codec.http.HttpMessage;
26  import io.netty.handler.codec.http.HttpObjectAggregator;
27  import io.netty.handler.codec.http.HttpServerCodec;
28  import io.netty.handler.codec.http.HttpServerUpgradeHandler;
29  import io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeCodec;
30  import io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeCodecFactory;
31  import io.netty.handler.codec.http2.CleartextHttp2ServerUpgradeHandler;
32  import io.netty.handler.codec.http2.Http2CodecUtil;
33  import io.netty.handler.codec.http2.Http2ServerUpgradeCodec;
34  import io.netty.handler.ssl.SslContext;
35  import io.netty.util.AsciiString;
36  import io.netty.util.ReferenceCountUtil;
37  
38  /**
39   * Sets up the Netty pipeline for the example server. Depending on the endpoint config, sets up the
40   * pipeline for NPN or cleartext HTTP upgrade to HTTP/2.
41   */
42  public class Http2ServerInitializer extends ChannelInitializer<SocketChannel> {
43  
44      private static final UpgradeCodecFactory upgradeCodecFactory = new UpgradeCodecFactory() {
45          @Override
46          public UpgradeCodec newUpgradeCodec(CharSequence protocol) {
47              if (AsciiString.contentEquals(Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME, protocol)) {
48                  return new Http2ServerUpgradeCodec(new HelloWorldHttp2HandlerBuilder().build());
49              } else {
50                  return null;
51              }
52          }
53      };
54  
55      private final SslContext sslCtx;
56      private final int maxHttpContentLength;
57  
58      public Http2ServerInitializer(SslContext sslCtx) {
59          this(sslCtx, 16 * 1024);
60      }
61  
62      public Http2ServerInitializer(SslContext sslCtx, int maxHttpContentLength) {
63          if (maxHttpContentLength < 0) {
64              throw new IllegalArgumentException("maxHttpContentLength (expected >= 0): " + maxHttpContentLength);
65          }
66          this.sslCtx = sslCtx;
67          this.maxHttpContentLength = maxHttpContentLength;
68      }
69  
70      @Override
71      public void initChannel(SocketChannel ch) {
72          if (sslCtx != null) {
73              configureSsl(ch);
74          } else {
75              configureClearText(ch);
76          }
77      }
78  
79      /**
80       * Configure the pipeline for TLS NPN negotiation to HTTP/2.
81       */
82      private void configureSsl(SocketChannel ch) {
83          ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new Http2OrHttpHandler());
84      }
85  
86      /**
87       * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.0
88       */
89      private void configureClearText(SocketChannel ch) {
90          final ChannelPipeline p = ch.pipeline();
91          final HttpServerCodec sourceCodec = new HttpServerCodec();
92          final HttpServerUpgradeHandler upgradeHandler = new HttpServerUpgradeHandler(sourceCodec, upgradeCodecFactory);
93          final CleartextHttp2ServerUpgradeHandler cleartextHttp2ServerUpgradeHandler =
94                  new CleartextHttp2ServerUpgradeHandler(sourceCodec, upgradeHandler,
95                                                         new HelloWorldHttp2HandlerBuilder().build());
96  
97          p.addLast(cleartextHttp2ServerUpgradeHandler);
98          p.addLast(new SimpleChannelInboundHandler<HttpMessage>() {
99              @Override
100             protected void channelRead0(ChannelHandlerContext ctx, HttpMessage msg) throws Exception {
101                 // If this handler is hit then no upgrade has been attempted and the client is just talking HTTP.
102                 System.err.println("Directly talking: " + msg.protocolVersion() + " (no upgrade was attempted)");
103                 ChannelPipeline pipeline = ctx.pipeline();
104                 ChannelHandlerContext thisCtx = pipeline.context(this);
105                 pipeline.addAfter(thisCtx.name(), null, new HelloWorldHttp1Handler("Direct. No Upgrade Attempted."));
106                 pipeline.replace(this, null, new HttpObjectAggregator(maxHttpContentLength));
107                 ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
108             }
109         });
110 
111         p.addLast(new UserEventLogger());
112     }
113 
114     /**
115      * Class that logs any User Events triggered on this channel.
116      */
117     private static class UserEventLogger extends ChannelInboundHandlerAdapter {
118         @Override
119         public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
120             System.out.println("User Event Triggered: " + evt);
121             ctx.fireUserEventTriggered(evt);
122         }
123     }
124 }