All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.netty.netty4pingcap.handler.codec.http2.Http2StreamFrameToHttpObjectCodec Maven / Gradle / Ivy

There is a newer version: 3.2.3
Show newest version
/*
 * Copyright 2016 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */

package io.netty.netty4pingcap.handler.codec.http2;

import io.netty.netty4pingcap.buffer.ByteBufAllocator;
import io.netty.netty4pingcap.buffer.Unpooled;
import io.netty.netty4pingcap.channel.Channel;
import io.netty.netty4pingcap.channel.ChannelHandler;
import io.netty.netty4pingcap.channel.ChannelHandlerContext;
import io.netty.netty4pingcap.handler.codec.MessageToMessageCodec;
import io.netty.netty4pingcap.handler.codec.http.DefaultHttpContent;
import io.netty.netty4pingcap.handler.codec.http.DefaultLastHttpContent;
import io.netty.netty4pingcap.handler.codec.http.FullHttpMessage;
import io.netty.netty4pingcap.handler.codec.http.HttpContent;
import io.netty.netty4pingcap.handler.codec.http.HttpHeaderNames;
import io.netty.netty4pingcap.handler.codec.http.HttpHeaderValues;
import io.netty.netty4pingcap.handler.codec.http.HttpMessage;
import io.netty.netty4pingcap.handler.codec.http.HttpObject;
import io.netty.netty4pingcap.handler.codec.http.HttpRequest;
import io.netty.netty4pingcap.handler.codec.http.HttpScheme;
import io.netty.netty4pingcap.handler.codec.http.HttpUtil;
import io.netty.netty4pingcap.handler.codec.http.HttpVersion;
import io.netty.netty4pingcap.handler.codec.http.LastHttpContent;
import io.netty.netty4pingcap.handler.ssl.SslHandler;
import io.netty.netty4pingcap.util.ReferenceCountUtil;
import io.netty.netty4pingcap.util.internal.UnstableApi;

import java.util.List;

/**
 * This handler converts from {@link Http2StreamFrame} to {@link HttpObject},
 * and back. It can be used as an adapter in conjunction with {@link
 * Http2MultiplexCodec} to make http/2 connections backward-compatible with
 * {@link ChannelHandler}s expecting {@link HttpObject}
 *
 * For simplicity, it converts to chunked encoding unless the entire stream
 * is a single header.
 */
@UnstableApi
public class Http2StreamFrameToHttpObjectCodec extends MessageToMessageCodec {
    private final boolean isServer;
    private final boolean validateHeaders;

    private HttpScheme scheme;

    public Http2StreamFrameToHttpObjectCodec(final boolean isServer,
                                             final boolean validateHeaders) {
        this.isServer = isServer;
        this.validateHeaders = validateHeaders;
        scheme = HttpScheme.HTTP;
    }

    public Http2StreamFrameToHttpObjectCodec(final boolean isServer) {
        this(isServer, true);
    }

    @Override
    public boolean acceptInboundMessage(Object msg) throws Exception {
        return (msg instanceof Http2HeadersFrame) || (msg instanceof Http2DataFrame);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, Http2StreamFrame frame, List out) throws Exception {
        if (frame instanceof Http2HeadersFrame) {
            int id = 0; // not really the id
            Http2HeadersFrame headersFrame = (Http2HeadersFrame) frame;
            Http2Headers headers = headersFrame.headers();

            if (headersFrame.isEndStream()) {
                if (headers.method() == null && headers.status() == null) {
                    LastHttpContent last = new DefaultLastHttpContent(Unpooled.EMPTY_BUFFER, validateHeaders);
                    HttpConversionUtil.addHttp2ToHttpHeaders(id, headers, last.trailingHeaders(),
                                                             HttpVersion.HTTP_1_1, true, true);
                    out.add(last);
                } else {
                    FullHttpMessage full = newFullMessage(id, headers, ctx.alloc());
                    out.add(full);
                }
            } else {
                HttpMessage req = newMessage(id, headers);
                if (!HttpUtil.isContentLengthSet(req)) {
                    req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
                }
                out.add(req);
            }
        } else if (frame instanceof Http2DataFrame) {
            Http2DataFrame dataFrame = (Http2DataFrame) frame;
            if (dataFrame.isEndStream()) {
                out.add(new DefaultLastHttpContent(dataFrame.content().retain(), validateHeaders));
            } else {
                out.add(new DefaultHttpContent(dataFrame.content().retain()));
            }
        }
    }

    private void encodeLastContent(LastHttpContent last, List out) {
        boolean needFiller = !(last instanceof FullHttpMessage) && last.trailingHeaders().isEmpty();
        if (last.content().isReadable() || needFiller) {
            out.add(new DefaultHttp2DataFrame(last.content().retain(), last.trailingHeaders().isEmpty()));
        }
        if (!last.trailingHeaders().isEmpty()) {
            Http2Headers headers = HttpConversionUtil.toHttp2Headers(last.trailingHeaders(), validateHeaders);
            out.add(new DefaultHttp2HeadersFrame(headers, true));
        }
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, HttpObject obj, List out) throws Exception {
        if (obj instanceof HttpMessage) {
            Http2Headers headers = toHttp2Headers((HttpMessage) obj);
            boolean noMoreFrames = false;
            if (obj instanceof FullHttpMessage) {
                FullHttpMessage full = (FullHttpMessage) obj;
                noMoreFrames = !full.content().isReadable() && full.trailingHeaders().isEmpty();
            }

            out.add(new DefaultHttp2HeadersFrame(headers, noMoreFrames));
        }

        if (obj instanceof LastHttpContent) {
            LastHttpContent last = (LastHttpContent) obj;
            encodeLastContent(last, out);
        } else if (obj instanceof HttpContent) {
            HttpContent cont = (HttpContent) obj;
            out.add(new DefaultHttp2DataFrame(cont.content().retain(), false));
        }
    }

    private Http2Headers toHttp2Headers(final HttpMessage msg) {
        if (msg instanceof HttpRequest) {
            msg.headers().set(
                    HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(),
                    scheme.name());
        }

        return HttpConversionUtil.toHttp2Headers(msg, validateHeaders);
    }

    private HttpMessage newMessage(final int id,
                                   final Http2Headers headers) throws Http2Exception {
        return isServer ?
                HttpConversionUtil.toHttpRequest(id, headers, validateHeaders) :
                HttpConversionUtil.toHttpResponse(id, headers, validateHeaders);
    }

    private FullHttpMessage newFullMessage(final int id,
                                           final Http2Headers headers,
                                           final ByteBufAllocator alloc) throws Http2Exception {
        return isServer ?
                HttpConversionUtil.toFullHttpRequest(id, headers, alloc, validateHeaders) :
                HttpConversionUtil.toFullHttpResponse(id, headers, alloc, validateHeaders);
    }

    @Override
    public void handlerAdded(final ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);

        // this handler is typically used on an Http2StreamChannel. at this
        // stage, ssl handshake should've been established. checking for the
        // presence of SslHandler in the parent's channel pipeline to
        // determine the HTTP scheme should suffice, even for the case where
        // SniHandler is used.
        scheme = isSsl(ctx) ? HttpScheme.HTTPS : HttpScheme.HTTP;
    }

    protected boolean isSsl(final ChannelHandlerContext ctx) {
        final Channel ch = ctx.channel();
        final Channel connChannel = (ch instanceof Http2StreamChannel) ? ch.parent() : ch;
        return null != connChannel.pipeline().get(SslHandler.class);
    }
}