1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty.handler.codec.http2;
18
19 import io.netty.buffer.ByteBufAllocator;
20 import io.netty.buffer.Unpooled;
21 import io.netty.channel.Channel;
22 import io.netty.channel.ChannelHandler;
23 import io.netty.channel.ChannelHandler.Sharable;
24 import io.netty.channel.ChannelHandlerContext;
25 import io.netty.handler.codec.EncoderException;
26 import io.netty.handler.codec.MessageToMessageCodec;
27 import io.netty.handler.codec.http.DefaultHttpContent;
28 import io.netty.handler.codec.http.DefaultLastHttpContent;
29 import io.netty.handler.codec.http.FullHttpMessage;
30 import io.netty.handler.codec.http.FullHttpResponse;
31 import io.netty.handler.codec.http.HttpContent;
32 import io.netty.handler.codec.http.HttpHeaderNames;
33 import io.netty.handler.codec.http.HttpHeaderValues;
34 import io.netty.handler.codec.http.HttpMessage;
35 import io.netty.handler.codec.http.HttpObject;
36 import io.netty.handler.codec.http.HttpRequest;
37 import io.netty.handler.codec.http.HttpResponse;
38 import io.netty.handler.codec.http.HttpResponseStatus;
39 import io.netty.handler.codec.http.HttpScheme;
40 import io.netty.handler.codec.http.HttpStatusClass;
41 import io.netty.handler.codec.http.HttpUtil;
42 import io.netty.handler.codec.http.HttpVersion;
43 import io.netty.handler.codec.http.LastHttpContent;
44 import io.netty.handler.ssl.SslHandler;
45 import io.netty.util.Attribute;
46 import io.netty.util.AttributeKey;
47
48 import java.util.List;
49
50
51
52
53
54
55
56
57
58
59 @Sharable
60 public class Http2StreamFrameToHttpObjectCodec extends MessageToMessageCodec<Http2StreamFrame, HttpObject> {
61
62 private static final AttributeKey<HttpScheme> SCHEME_ATTR_KEY =
63 AttributeKey.valueOf(HttpScheme.class, "STREAMFRAMECODEC_SCHEME");
64
65 private final boolean isServer;
66 private final boolean validateHeaders;
67
68 public Http2StreamFrameToHttpObjectCodec(final boolean isServer,
69 final boolean validateHeaders) {
70 super(Http2StreamFrame.class, HttpObject.class);
71 this.isServer = isServer;
72 this.validateHeaders = validateHeaders;
73 }
74
75 public Http2StreamFrameToHttpObjectCodec(final boolean isServer) {
76 this(isServer, true);
77 }
78
79 @Override
80 public boolean acceptInboundMessage(Object msg) throws Exception {
81 return msg instanceof Http2HeadersFrame || msg instanceof Http2DataFrame;
82 }
83
84 @Override
85 protected void decode(ChannelHandlerContext ctx, Http2StreamFrame frame, List<Object> out) throws Exception {
86 if (frame instanceof Http2HeadersFrame) {
87 Http2HeadersFrame headersFrame = (Http2HeadersFrame) frame;
88 Http2Headers headers = headersFrame.headers();
89 Http2FrameStream stream = headersFrame.stream();
90 int id = stream == null ? 0 : stream.id();
91
92 final CharSequence status = headers.status();
93
94
95
96 if (null != status && isInformationalResponseHeaderFrame(status)) {
97 final FullHttpMessage fullMsg = newFullMessage(id, headers, ctx.alloc());
98 out.add(fullMsg);
99 return;
100 }
101
102 if (headersFrame.isEndStream()) {
103 if (headers.method() == null && status == null) {
104 LastHttpContent last = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER, validateHeaders);
105 HttpConversionUtil.addHttp2ToHttpHeaders(id, headers, last.trailingHeaders(),
106 HttpVersion.HTTP_1_1, true, true);
107 out.add(last);
108 } else {
109 FullHttpMessage full = newFullMessage(id, headers, ctx.alloc());
110 out.add(full);
111 }
112 } else {
113 HttpMessage req = newMessage(id, headers);
114 if ((status == null || !isContentAlwaysEmpty(status)) && !HttpUtil.isContentLengthSet(req)) {
115 req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
116 }
117 out.add(req);
118 }
119 } else if (frame instanceof Http2DataFrame) {
120 Http2DataFrame dataFrame = (Http2DataFrame) frame;
121 if (dataFrame.isEndStream()) {
122 out.add(new DefaultLastHttpContent(dataFrame.content().retain(), validateHeaders));
123 } else {
124 out.add(new DefaultHttpContent(dataFrame.content().retain()));
125 }
126 }
127 }
128
129 private void encodeLastContent(LastHttpContent last, List<Object> out) {
130 boolean needFiller = !(last instanceof FullHttpMessage) && last.trailingHeaders().isEmpty();
131 if (last.content().isReadable() || needFiller) {
132 out.add(new DefaultHttp2DataFrame(last.content().retain(), last.trailingHeaders().isEmpty()));
133 }
134 if (!last.trailingHeaders().isEmpty()) {
135 Http2Headers headers = HttpConversionUtil.toHttp2Headers(last.trailingHeaders(), validateHeaders);
136 out.add(new DefaultHttp2HeadersFrame(headers, true));
137 }
138 }
139
140
141
142
143
144
145
146
147
148
149
150
151
152 @Override
153 protected void encode(ChannelHandlerContext ctx, HttpObject obj, List<Object> out) throws Exception {
154
155
156 if (obj instanceof HttpResponse) {
157 final HttpResponse res = (HttpResponse) obj;
158 final HttpResponseStatus status = res.status();
159 final int code = status.code();
160 final HttpStatusClass statusClass = status.codeClass();
161
162
163 if (statusClass == HttpStatusClass.INFORMATIONAL && code != 101) {
164 if (res instanceof FullHttpResponse) {
165 final Http2Headers headers = toHttp2Headers(ctx, res);
166 out.add(new DefaultHttp2HeadersFrame(headers, false));
167 return;
168 } else {
169 throw new EncoderException(status + " must be a FullHttpResponse");
170 }
171 }
172 }
173
174 if (obj instanceof HttpMessage) {
175 Http2Headers headers = toHttp2Headers(ctx, (HttpMessage) obj);
176 boolean noMoreFrames = false;
177 if (obj instanceof FullHttpMessage) {
178 FullHttpMessage full = (FullHttpMessage) obj;
179 noMoreFrames = !full.content().isReadable() && full.trailingHeaders().isEmpty();
180 }
181
182 out.add(new DefaultHttp2HeadersFrame(headers, noMoreFrames));
183 }
184
185 if (obj instanceof LastHttpContent) {
186 LastHttpContent last = (LastHttpContent) obj;
187 encodeLastContent(last, out);
188 } else if (obj instanceof HttpContent) {
189 HttpContent cont = (HttpContent) obj;
190 out.add(new DefaultHttp2DataFrame(cont.content().retain(), false));
191 }
192 }
193
194 private Http2Headers toHttp2Headers(final ChannelHandlerContext ctx, final HttpMessage msg) {
195 if (msg instanceof HttpRequest) {
196 msg.headers().set(
197 HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(),
198 connectionScheme(ctx));
199 }
200
201 return HttpConversionUtil.toHttp2Headers(msg, validateHeaders);
202 }
203
204 private HttpMessage newMessage(final int id,
205 final Http2Headers headers) throws Http2Exception {
206 return isServer ?
207 HttpConversionUtil.toHttpRequest(id, headers, validateHeaders) :
208 HttpConversionUtil.toHttpResponse(id, headers, validateHeaders);
209 }
210
211 private FullHttpMessage newFullMessage(final int id,
212 final Http2Headers headers,
213 final ByteBufAllocator alloc) throws Http2Exception {
214 return isServer ?
215 HttpConversionUtil.toFullHttpRequest(id, headers, alloc, validateHeaders) :
216 HttpConversionUtil.toFullHttpResponse(id, headers, alloc, validateHeaders);
217 }
218
219 @Override
220 public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
221 super.handlerAdded(ctx);
222
223
224
225
226
227
228 final Attribute<HttpScheme> schemeAttribute = connectionSchemeAttribute(ctx);
229 if (schemeAttribute.get() == null) {
230 final HttpScheme scheme = isSsl(ctx) ? HttpScheme.HTTPS : HttpScheme.HTTP;
231 schemeAttribute.set(scheme);
232 }
233 }
234
235 protected boolean isSsl(final ChannelHandlerContext ctx) {
236 final Channel connChannel = connectionChannel(ctx);
237 return null != connChannel.pipeline().get(SslHandler.class);
238 }
239
240 private static HttpScheme connectionScheme(ChannelHandlerContext ctx) {
241 final HttpScheme scheme = connectionSchemeAttribute(ctx).get();
242 return scheme == null ? HttpScheme.HTTP : scheme;
243 }
244
245 private static Attribute<HttpScheme> connectionSchemeAttribute(ChannelHandlerContext ctx) {
246 final Channel ch = connectionChannel(ctx);
247 return ch.attr(SCHEME_ATTR_KEY);
248 }
249
250 private static Channel connectionChannel(ChannelHandlerContext ctx) {
251 final Channel ch = ctx.channel();
252 return ch instanceof Http2StreamChannel ? ch.parent() : ch;
253 }
254
255
256
257
258
259 private static boolean isInformationalResponseHeaderFrame(CharSequence status) {
260 if (status.length() == 3) {
261 char char0 = status.charAt(0);
262 char char1 = status.charAt(1);
263 char char2 = status.charAt(2);
264 return char0 == '1'
265 && char1 >= '0' && char1 <= '9'
266 && char2 >= '0' && char2 <= '9' && char2 != '1';
267 }
268 return false;
269 }
270
271
272
273
274
275 private static boolean isContentAlwaysEmpty(CharSequence status) {
276 if (status.length() == 3) {
277 char char0 = status.charAt(0);
278 char char1 = status.charAt(1);
279 char char2 = status.charAt(2);
280 return (char0 == '2' || char0 == '3')
281 && char1 == '0'
282 && char2 == '4';
283 }
284 return false;
285 }
286 }