1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.hc.core5.http2.impl.nio;
29
30 import java.io.IOException;
31 import java.nio.ByteBuffer;
32
33 import org.apache.hc.core5.annotation.Internal;
34 import org.apache.hc.core5.concurrent.FutureCallback;
35 import org.apache.hc.core5.http.ConnectionClosedException;
36 import org.apache.hc.core5.http.impl.nio.BufferedData;
37 import org.apache.hc.core5.reactor.IOSession;
38 import org.apache.hc.core5.reactor.ProtocolIOSession;
39 import org.apache.hc.core5.util.Args;
40
41
42
43
44
45
46
47 @Internal
48 public class ServerH2PrefaceHandler extends PrefaceHandlerBase {
49
50 final static byte[] PREFACE = ClientH2PrefaceHandler.PREFACE;
51
52 private final ServerH2StreamMultiplexerFactory http2StreamHandlerFactory;
53 private final BufferedData inBuf;
54
55 public ServerH2PrefaceHandler(
56 final ProtocolIOSession ioSession,
57 final ServerH2StreamMultiplexerFactory http2StreamHandlerFactory) {
58 this(ioSession, http2StreamHandlerFactory, null);
59 }
60
61 public ServerH2PrefaceHandler(
62 final ProtocolIOSession ioSession,
63 final ServerH2StreamMultiplexerFactory http2StreamHandlerFactory,
64 final FutureCallback<ProtocolIOSession> resultCallback) {
65 super(ioSession, resultCallback);
66 this.http2StreamHandlerFactory = Args.notNull(http2StreamHandlerFactory, "HTTP/2 stream handler factory");
67 this.inBuf = BufferedData.allocate(1024);
68 }
69
70 @Override
71 public void connected(final IOSession session) throws IOException {
72 }
73
74 @Override
75 public void inputReady(final IOSession session, final ByteBuffer src) throws IOException {
76 if (src != null) {
77 inBuf.put(src);
78 }
79 boolean endOfStream = false;
80 if (inBuf.length() < PREFACE.length) {
81 final int bytesRead = inBuf.readFrom(session);
82 if (bytesRead == -1) {
83 endOfStream = true;
84 }
85 }
86 final ByteBuffer data = inBuf.data();
87 if (data.remaining() >= PREFACE.length) {
88 for (int i = 0; i < PREFACE.length; i++) {
89 if (data.get() != PREFACE[i]) {
90 throw new ProtocolNegotiationException("Unexpected HTTP/2 preface");
91 }
92 }
93 startProtocol(new ServerH2IOEventHandler(http2StreamHandlerFactory.create(ioSession)), data.hasRemaining() ? data : null);
94 } else {
95 if (endOfStream) {
96 throw new ConnectionClosedException();
97 }
98 }
99 }
100
101 @Override
102 public void outputReady(final IOSession session) throws IOException {
103 }
104
105 @Override
106 public String toString() {
107 return getClass().getName();
108 }
109
110 }