1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.http2;
17
18 import io.netty.channel.ChannelHandlerContext;
19 import io.netty.channel.ChannelInboundHandlerAdapter;
20 import io.netty.handler.codec.http.FullHttpMessage;
21 import io.netty.handler.codec.http.HttpHeaders;
22 import io.netty.handler.codec.http.HttpScheme;
23
24 import static io.netty.handler.codec.http2.Http2Error.PROTOCOL_ERROR;
25 import static io.netty.handler.codec.http2.Http2Exception.streamError;
26
27
28
29
30 public class InboundHttpToHttp2Adapter extends ChannelInboundHandlerAdapter {
31 private final Http2Connection connection;
32 private final Http2FrameListener listener;
33
34 public InboundHttpToHttp2Adapter(Http2Connection connection, Http2FrameListener listener) {
35 this.connection = connection;
36 this.listener = listener;
37 }
38
39 private static int getStreamId(Http2Connection connection, HttpHeaders httpHeaders) {
40 return httpHeaders.getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(),
41 connection.remote().incrementAndGetNextStreamId());
42 }
43
44 @Override
45 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
46 if (msg instanceof FullHttpMessage) {
47 handle(ctx, connection, listener, (FullHttpMessage) msg);
48 } else {
49 super.channelRead(ctx, msg);
50 }
51 }
52
53
54
55
56 static void handle(ChannelHandlerContext ctx, Http2Connection connection,
57 Http2FrameListener listener, FullHttpMessage message) throws Http2Exception {
58 try {
59 int streamId = getStreamId(connection, message.headers());
60 Http2Stream stream = connection.stream(streamId);
61 if (stream == null) {
62 stream = connection.remote().createStream(streamId, false);
63 }
64 message.headers().set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), HttpScheme.HTTP.name());
65 Http2Headers messageHeaders;
66 try {
67 messageHeaders = HttpConversionUtil.toHttp2Headers(message, true);
68 } catch (IllegalArgumentException e) {
69
70
71 throw streamError(streamId, PROTOCOL_ERROR, e,
72 "Failed to convert HTTP/1.x message to HTTP/2 headers: %s", e.getMessage());
73 }
74 boolean hasContent = message.content().isReadable();
75 boolean hasTrailers = !message.trailingHeaders().isEmpty();
76 listener.onHeadersRead(
77 ctx, streamId, messageHeaders, 0, !(hasContent || hasTrailers));
78 if (hasContent) {
79 listener.onDataRead(ctx, streamId, message.content(), 0, !hasTrailers);
80 }
81 if (hasTrailers) {
82 Http2Headers headers = HttpConversionUtil.toHttp2Headers(message.trailingHeaders(), true);
83 listener.onHeadersRead(ctx, streamId, headers, 0, true);
84 }
85 stream.closeRemoteSide();
86 } finally {
87 message.release();
88 }
89 }
90 }