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     /**
108      * @return true if the entire preface has been written out
109      */
110     private boolean writeOutPreface(final IOSession session, final ByteBuffer preface) throws IOException  {
111         if (preface.hasRemaining()) {
112             session.write(preface);
113         }
114         if (!preface.hasRemaining()) {
115             session.clearEvent(SelectionKey.OP_WRITE);
116             final ByteBuffer data = inBuf != null ? inBuf.data() : null;
117             startProtocol(new ClientH2IOEventHandler(http2StreamHandlerFactory.create(ioSession)), data);
118             if (inBuf != null) {
119                 inBuf.clear();
120             }
121             return true;
122         }
123         return false;
124     }
125 
126     @Override
127     public void connected(final IOSession session) throws IOException {
128         if (initialized.compareAndSet(false, true)) {
129             initialize();
130         }
131     }
132 
133     @Override
134     public void outputReady(final IOSession session) throws IOException {
135         if (initialized.compareAndSet(false, true)) {
136             initialize();
137         }
138         final ByteBuffer preface = this.preface;
139         if (preface != null) {
140             if (writeOutPreface(session, preface)) {
141                 this.preface = null;
142             }
143         } else {
144             throw new ProtocolNegotiationException("Unexpected output");
145         }
146     }
147 
148     @Override
149     public void inputReady(final IOSession session, final ByteBuffer src) throws IOException {
150         if (src != null) {
151             if (inBuf == null) {
152                 inBuf = BufferedData.allocate(src.remaining());
153             }
154             inBuf.put(src);
155         }
156         final ByteBuffer preface = this.preface;
157         if (preface != null) {
158             if (writeOutPreface(session, preface)) {
159                 this.preface = null;
160             }
161         } else {
162             throw new ProtocolNegotiationException("Unexpected input");
163         }
164     }
165 
166     @Override
167     public String toString() {
168         return getClass().getName();
169     }
170 
171 }