View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.http2.impl.nio;
29  
30  import java.io.IOException;
31  import java.nio.ByteBuffer;
32  import java.nio.channels.SelectionKey;
33  import java.util.concurrent.atomic.AtomicBoolean;
34  
35  import org.apache.hc.core5.annotation.Internal;
36  import org.apache.hc.core5.concurrent.FutureCallback;
37  import org.apache.hc.core5.http.impl.nio.BufferedData;
38  import org.apache.hc.core5.http2.ssl.ApplicationProtocol;
39  import org.apache.hc.core5.reactor.IOSession;
40  import org.apache.hc.core5.reactor.ProtocolIOSession;
41  import org.apache.hc.core5.reactor.ssl.TlsDetails;
42  import org.apache.hc.core5.util.Args;
43  import org.apache.hc.core5.util.TextUtils;
44  
45  /**
46   * I/O event handler for events fired by {@link ProtocolIOSession} that implements
47   * client side of the HTTP/2 protocol negotiation handshake always forcing the choice
48   * of HTTP/2.
49   *
50   * @since 5.2
51   */
52  @Internal
53  public class ClientH2PrefaceHandler extends PrefaceHandlerBase {
54  
55      // PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n
56      final static byte[] PREFACE = new byte[] {
57              0x50, 0x52, 0x49, 0x20, 0x2a, 0x20, 0x48, 0x54, 0x54, 0x50,
58              0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a, 0x0d, 0x0a, 0x53, 0x4d,
59              0x0d, 0x0a, 0x0d, 0x0a};
60  
61      private final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory;
62      private final boolean strictALPNHandshake;
63      private final AtomicBoolean initialized;
64  
65      private volatile ByteBuffer preface;
66      private volatile BufferedData inBuf;
67  
68      public ClientH2PrefaceHandler(
69              final ProtocolIOSession ioSession,
70              final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory,
71              final boolean strictALPNHandshake) {
72          this(ioSession, http2StreamHandlerFactory, strictALPNHandshake, null);
73      }
74  
75      /**
76       * @since 5.1
77       */
78      public ClientH2PrefaceHandler(
79              final ProtocolIOSession ioSession,
80              final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory,
81              final boolean strictALPNHandshake,
82              final FutureCallback<ProtocolIOSession> resultCallback) {
83          super(ioSession, resultCallback);
84          this.http2StreamHandlerFactory = Args.notNull(http2StreamHandlerFactory, "HTTP/2 stream handler factory");
85          this.strictALPNHandshake = strictALPNHandshake;
86          this.initialized = new AtomicBoolean();
87      }
88  
89      private void initialize() throws IOException {
90          final TlsDetails tlsDetails = ioSession.getTlsDetails();
91          if (tlsDetails != null) {
92              final String applicationProtocol = tlsDetails.getApplicationProtocol();
93              if (TextUtils.isEmpty(applicationProtocol)) {
94                  if (strictALPNHandshake) {
95                      throw new ProtocolNegotiationException("ALPN: missing application protocol");
96                  }
97              } else {
98                  if (!ApplicationProtocol.HTTP_2.id.equals(applicationProtocol)) {
99                      throw new ProtocolNegotiationException("ALPN: unexpected application protocol '" + applicationProtocol + "'");
100                 }
101             }
102         }
103         this.preface = ByteBuffer.wrap(PREFACE);
104         ioSession.setEvent(SelectionKey.OP_WRITE);
105     }
106 
107     private void writeOutPreface(final IOSession session) throws IOException  {
108         if (preface.hasRemaining()) {
109             session.write(preface);
110         }
111         if (!preface.hasRemaining()) {
112             session.clearEvent(SelectionKey.OP_WRITE);
113             final ByteBuffer data = inBuf != null ? inBuf.data() : null;
114             startProtocol(new ClientH2IOEventHandler(http2StreamHandlerFactory.create(ioSession)), data);
115             if (inBuf != null) {
116                 inBuf.clear();
117             }
118             preface = null;
119         }
120     }
121 
122     @Override
123     public void connected(final IOSession session) throws IOException {
124         if (initialized.compareAndSet(false, true)) {
125             initialize();
126         }
127     }
128 
129     @Override
130     public void outputReady(final IOSession session) throws IOException {
131         if (initialized.compareAndSet(false, true)) {
132             initialize();
133         }
134         if (preface != null) {
135             writeOutPreface(session);
136         } else {
137             throw new ProtocolNegotiationException("Unexpected output");
138         }
139     }
140 
141     @Override
142     public void inputReady(final IOSession session, final ByteBuffer src) throws IOException {
143         if (src != null) {
144             if (inBuf == null) {
145                 inBuf = BufferedData.allocate(src.remaining());
146             }
147             inBuf.put(src);
148         }
149         if (preface != null) {
150             writeOutPreface(session);
151         } else {
152             throw new ProtocolNegotiationException("Unexpected input");
153         }
154     }
155 
156     @Override
157     public String toString() {
158         return getClass().getName();
159     }
160 
161 }