Search in sources :

Example 66 with Http2Headers

use of io.netty.handler.codec.http2.Http2Headers in project grpc-java by grpc.

the class NettyServerHandlerTest method headersWithInvalidMethodShouldFail.

@Test
public void headersWithInvalidMethodShouldFail() throws Exception {
    manualSetUp();
    Http2Headers headers = new DefaultHttp2Headers().method(HTTP_FAKE_METHOD).set(CONTENT_TYPE_HEADER, CONTENT_TYPE_GRPC).path(new AsciiString("/foo/bar"));
    ByteBuf headersFrame = headersFrame(STREAM_ID, headers);
    channelRead(headersFrame);
    Http2Headers responseHeaders = new DefaultHttp2Headers().set(InternalStatus.CODE_KEY.name(), String.valueOf(Code.INTERNAL.value())).set(InternalStatus.MESSAGE_KEY.name(), "Method 'FAKE' is not supported").status("" + 405).set(CONTENT_TYPE_HEADER, "text/plain; charset=utf-8");
    verifyWrite().writeHeaders(eq(ctx()), eq(STREAM_ID), eq(responseHeaders), eq(0), eq(false), any(ChannelPromise.class));
}
Also used : Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) AsciiString(io.netty.util.AsciiString) ChannelPromise(io.netty.channel.ChannelPromise) ByteBuf(io.netty.buffer.ByteBuf) Test(org.junit.Test)

Example 67 with Http2Headers

use of io.netty.handler.codec.http2.Http2Headers in project grpc-java by grpc.

the class NettyHandlerTestBase method headersFrame.

protected final ByteBuf headersFrame(int streamId, Http2Headers headers) {
    ChannelHandlerContext ctx = newMockContext();
    new DefaultHttp2FrameWriter().writeHeaders(ctx, streamId, headers, 0, false, newPromise());
    return captureWrite(ctx);
}
Also used : ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DefaultHttp2FrameWriter(io.netty.handler.codec.http2.DefaultHttp2FrameWriter)

Example 68 with Http2Headers

use of io.netty.handler.codec.http2.Http2Headers in project grpc-java by grpc.

the class NettyServerHandler method onHeadersRead.

private void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers) throws Http2Exception {
    try {
        // by Netty. RFC 7540 section 8.1.2.2
        if (!DISABLE_CONNECTION_HEADER_CHECK && headers.contains(CONNECTION)) {
            resetStream(ctx, streamId, Http2Error.PROTOCOL_ERROR.code(), ctx.newPromise());
            return;
        }
        if (headers.authority() == null) {
            List<CharSequence> hosts = headers.getAll(HOST);
            if (hosts.size() > 1) {
                // RFC 7230 section 5.4
                respondWithHttpError(ctx, streamId, 400, Status.Code.INTERNAL, "Multiple host headers");
                return;
            }
            if (!hosts.isEmpty()) {
                headers.add(AUTHORITY.value(), hosts.get(0));
            }
        }
        headers.remove(HOST);
        // Remove the leading slash of the path and get the fully qualified method name
        CharSequence path = headers.path();
        if (path == null) {
            respondWithHttpError(ctx, streamId, 404, Status.Code.UNIMPLEMENTED, "Expected path but is missing");
            return;
        }
        if (path.charAt(0) != '/') {
            respondWithHttpError(ctx, streamId, 404, Status.Code.UNIMPLEMENTED, String.format("Expected path to start with /: %s", path));
            return;
        }
        String method = path.subSequence(1, path.length()).toString();
        // Verify that the Content-Type is correct in the request.
        CharSequence contentType = headers.get(CONTENT_TYPE_HEADER);
        if (contentType == null) {
            respondWithHttpError(ctx, streamId, 415, Status.Code.INTERNAL, "Content-Type is missing from the request");
            return;
        }
        String contentTypeString = contentType.toString();
        if (!GrpcUtil.isGrpcContentType(contentTypeString)) {
            respondWithHttpError(ctx, streamId, 415, Status.Code.INTERNAL, String.format("Content-Type '%s' is not supported", contentTypeString));
            return;
        }
        if (!HTTP_METHOD.contentEquals(headers.method())) {
            respondWithHttpError(ctx, streamId, 405, Status.Code.INTERNAL, String.format("Method '%s' is not supported", headers.method()));
            return;
        }
        if (!teWarningLogged && !TE_TRAILERS.contentEquals(headers.get(TE_HEADER))) {
            logger.warning(String.format("Expected header TE: %s, but %s is received. This means " + "some intermediate proxy may not support trailers", TE_TRAILERS, headers.get(TE_HEADER)));
            teWarningLogged = true;
        }
        // The Http2Stream object was put by AbstractHttp2ConnectionHandler before calling this
        // method.
        Http2Stream http2Stream = requireHttp2Stream(streamId);
        Metadata metadata = Utils.convertHeaders(headers);
        StatsTraceContext statsTraceCtx = StatsTraceContext.newServerContext(streamTracerFactories, method, metadata);
        NettyServerStream.TransportState state = new NettyServerStream.TransportState(this, ctx.channel().eventLoop(), http2Stream, maxMessageSize, statsTraceCtx, transportTracer, method);
        PerfMark.startTask("NettyServerHandler.onHeadersRead", state.tag());
        try {
            String authority = getOrUpdateAuthority((AsciiString) headers.authority());
            NettyServerStream stream = new NettyServerStream(ctx.channel(), state, attributes, authority, statsTraceCtx, transportTracer);
            transportListener.streamCreated(stream, method, metadata);
            state.onStreamAllocated();
            http2Stream.setProperty(streamKey, state);
        } finally {
            PerfMark.stopTask("NettyServerHandler.onHeadersRead", state.tag());
        }
    } catch (Exception e) {
        logger.log(Level.WARNING, "Exception in onHeadersRead()", e);
        // Throw an exception that will get handled by onStreamError.
        throw newStreamException(streamId, e);
    }
}
Also used : StatsTraceContext(io.grpc.internal.StatsTraceContext) Metadata(io.grpc.Metadata) InternalMetadata(io.grpc.InternalMetadata) AsciiString(io.netty.util.AsciiString) Http2Stream(io.netty.handler.codec.http2.Http2Stream) Http2Exception(io.netty.handler.codec.http2.Http2Exception) StreamException(io.netty.handler.codec.http2.Http2Exception.StreamException)

Example 69 with Http2Headers

use of io.netty.handler.codec.http2.Http2Headers in project grpc-java by grpc.

the class NettyServerHandler method respondWithHttpError.

private void respondWithHttpError(ChannelHandlerContext ctx, int streamId, int code, Status.Code statusCode, String msg) {
    Metadata metadata = new Metadata();
    metadata.put(InternalStatus.CODE_KEY, statusCode.toStatus());
    metadata.put(InternalStatus.MESSAGE_KEY, msg);
    byte[][] serialized = InternalMetadata.serialize(metadata);
    Http2Headers headers = new DefaultHttp2Headers(true, serialized.length / 2).status("" + code).set(CONTENT_TYPE_HEADER, "text/plain; charset=utf-8");
    for (int i = 0; i < serialized.length; i += 2) {
        headers.add(new AsciiString(serialized[i], false), new AsciiString(serialized[i + 1], false));
    }
    encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
    ByteBuf msgBuf = ByteBufUtil.writeUtf8(ctx.alloc(), msg);
    encoder().writeData(ctx, streamId, msgBuf, 0, true, ctx.newPromise());
}
Also used : Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Metadata(io.grpc.Metadata) InternalMetadata(io.grpc.InternalMetadata) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) AsciiString(io.netty.util.AsciiString) ByteBuf(io.netty.buffer.ByteBuf)

Example 70 with Http2Headers

use of io.netty.handler.codec.http2.Http2Headers in project vert.x by eclipse.

the class Http2ServerTest method testResponseCompressionEnabled.

@Test
public void testResponseCompressionEnabled() throws Exception {
    waitFor(2);
    String expected = TestUtils.randomAlphaString(1000);
    server.close();
    server = vertx.createHttpServer(serverOptions.setCompressionSupported(true));
    server.requestHandler(req -> {
        req.response().end(expected);
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        request.decoder.frameListener(new Http2EventAdapter() {

            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
                vertx.runOnContext(v -> {
                    assertEquals("gzip", headers.get(HttpHeaderNames.CONTENT_ENCODING).toString());
                    complete();
                });
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
                byte[] bytes = new byte[data.readableBytes()];
                data.readBytes(bytes);
                vertx.runOnContext(v -> {
                    String decoded;
                    try {
                        GZIPInputStream in = new GZIPInputStream(new ByteArrayInputStream(bytes));
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        while (true) {
                            int i = in.read();
                            if (i == -1) {
                                break;
                            }
                            baos.write(i);
                            ;
                        }
                        decoded = baos.toString();
                    } catch (IOException e) {
                        fail(e);
                        return;
                    }
                    assertEquals(expected, decoded);
                    complete();
                });
                return super.onDataRead(ctx, streamId, data, padding, endOfStream);
            }
        });
        int id = request.nextStreamId();
        request.encoder.writeHeaders(request.context, id, GET("/").add("accept-encoding", "gzip"), 0, true, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Http1xOrH2CHandler(io.vertx.core.http.impl.Http1xOrH2CHandler) Context(io.vertx.core.Context) Utils(io.vertx.core.impl.Utils) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ReadStream(io.vertx.core.streams.ReadStream) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) HttpRequest(io.netty.handler.codec.http.HttpRequest) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Trust(io.vertx.test.tls.Trust) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) Http2Error(io.netty.handler.codec.http2.Http2Error) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) DetectFileDescriptorLeaks(io.vertx.test.core.DetectFileDescriptorLeaks) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) IOException(java.io.IOException) SSLHelper(io.vertx.core.net.impl.SSLHelper) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Bootstrap(io.netty.bootstrap.Bootstrap) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2Connection(io.netty.handler.codec.http2.Http2Connection) HttpUtils(io.vertx.core.http.impl.HttpUtils) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ByteBuf(io.netty.buffer.ByteBuf) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) Test(org.junit.Test)

Aggregations

Http2Headers (io.netty.handler.codec.http2.Http2Headers)126 DefaultHttp2Headers (io.netty.handler.codec.http2.DefaultHttp2Headers)111 ByteBuf (io.netty.buffer.ByteBuf)103 Test (org.junit.Test)97 ChannelFuture (io.netty.channel.ChannelFuture)76 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)76 AsciiString (io.netty.util.AsciiString)58 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)58 AtomicReference (java.util.concurrent.atomic.AtomicReference)56 ByteArrayOutputStream (java.io.ByteArrayOutputStream)54 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)54 Channel (io.netty.channel.Channel)53 Collections (java.util.Collections)53 ChannelInitializer (io.netty.channel.ChannelInitializer)52 ChannelPipeline (io.netty.channel.ChannelPipeline)52 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)52 HttpHeaderNames (io.netty.handler.codec.http.HttpHeaderNames)52 ApplicationProtocolNames (io.netty.handler.ssl.ApplicationProtocolNames)52 ApplicationProtocolNegotiationHandler (io.netty.handler.ssl.ApplicationProtocolNegotiationHandler)52 SslHandler (io.netty.handler.ssl.SslHandler)52