Java Code Examples for io.netty.handler.codec.http2.Http2Headers#set()

The following examples show how to use io.netty.handler.codec.http2.Http2Headers#set() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: H2ToStH1Utils.java    From servicetalk with Apache License 2.0 6 votes vote down vote up
/**
 * Combine the cookie values into 1 header entry as required by
 * <a href="https://tools.ietf.org/html/rfc7540#section-8.1.2.5">RFC 7540, 8.1.2.5</a>.
 *
 * @param h2Headers The headers which may contain cookies.
 */
static void h2HeadersCompressCookieCrumbs(Http2Headers h2Headers) {
    // Netty's value iterator doesn't return elements in insertion order, this is not strictly compliant with the
    // RFC and may result in reversed order cookies.
    Iterator<? extends CharSequence> cookieItr = h2Headers.valueIterator(HttpHeaderNames.COOKIE);
    if (cookieItr.hasNext()) {
        CharSequence prevCookItr = cookieItr.next();
        if (cookieItr.hasNext()) {
            CharSequence cookieHeader = cookieItr.next();
            // *2 gives some space for an extra cookie.
            StringBuilder sb = new StringBuilder(prevCookItr.length() * 2 + cookieHeader.length() + 2);
            sb.append(prevCookItr).append("; ").append(cookieHeader);
            while (cookieItr.hasNext()) {
                cookieHeader = cookieItr.next();
                sb.append("; ").append(cookieHeader);
            }
            h2Headers.set(HttpHeaderNames.COOKIE, sb.toString());
        }
    }
}
 
Example 2
Source File: Http2ServerTask.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private void sendHttp2Response0(HttpResponseStatus status, boolean error, ByteBuf data) {
    Http2Headers headers = new DefaultHttp2Headers().status(status.codeAsText());

    if (request.getSerializeType() > 0) {
        String serialization = SerializerFactory.getAliasByCode(request.getSerializeType());
        headers.set(RemotingConstants.HEAD_SERIALIZE_TYPE, serialization);
    } else {
        headers.set(CONTENT_TYPE, "text/plain; charset=" + RpcConstants.DEFAULT_CHARSET.displayName());
    }
    if (error) {
        headers.set(RemotingConstants.HEAD_RESPONSE_ERROR, "true");
    }
    if (data != null) {
        encoder.writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
        encoder.writeData(ctx, streamId, data, 0, true, ctx.newPromise());
    } else {
        encoder.writeHeaders(ctx, streamId, headers, 0, true, ctx.newPromise());
    }
}
 
Example 3
Source File: Http2Handler.java    From xrpc with Apache License 2.0 6 votes vote down vote up
/**
 * Writes the given response body as "text/plain" to the given stream. Marks the response status
 * metric. Closes the stream after writing the response.
 */
private void writeResponse(
    ChannelHandlerContext ctx, int streamId, HttpResponseStatus status, ByteBuf body) {

  Preconditions.checkArgument(body != null, "body must not be null");

  markResponseStatus(ctx, status);

  Http2Headers headers = new DefaultHttp2Headers(true);
  // TODO(jkinkead): This should honor accept headers; we shouldn't send text/plain if the client
  // doesn't want it.
  headers.set(CONTENT_TYPE, "text/plain");
  headers.setInt(CONTENT_LENGTH, body.readableBytes());
  headers.status(status.codeAsText());

  writeResponse(ctx, streamId, headers, Optional.of(body));
}
 
Example 4
Source File: NettyClientStreamTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidInboundHeadersCancelStream() throws Exception {
  stream().transportState().setId(STREAM_ID);
  Http2Headers headers = grpcResponseHeaders();
  headers.set("random", "4");
  headers.remove(CONTENT_TYPE_HEADER);
  // Remove once b/16290036 is fixed.
  headers.status(new AsciiString("500"));
  stream().transportState().transportHeadersReceived(headers, false);
  verify(listener, never()).closed(any(Status.class), any(Metadata.class));

  // We are now waiting for 100 bytes of error context on the stream, cancel has not yet been
  // sent
  verify(channel, never()).writeAndFlush(any(CancelClientStreamCommand.class));
  stream().transportState().transportDataReceived(Unpooled.buffer(100).writeZero(100), false);
  verify(channel, never()).writeAndFlush(any(CancelClientStreamCommand.class));
  stream().transportState().transportDataReceived(Unpooled.buffer(1000).writeZero(1000), false);

  // Now verify that cancel is sent and an error is reported to the listener
  verify(writeQueue).enqueue(isA(CancelClientStreamCommand.class), eq(true));
  ArgumentCaptor<Status> captor = ArgumentCaptor.forClass(Status.class);
  ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
  verify(listener).closed(captor.capture(), same(PROCESSED), metadataCaptor.capture());
  assertEquals(Status.UNKNOWN.getCode(), captor.getValue().getCode());
  assertEquals("4", metadataCaptor.getValue()
      .get(Metadata.Key.of("random", Metadata.ASCII_STRING_MARSHALLER)));

}
 
Example 5
Source File: H2ToStH1ServerDuplexHandler.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private void fireFullRequest(ChannelHandlerContext ctx, final Http2Headers h2Headers,
                             HttpRequestMethod httpMethod, String path) {
    if (shouldAddZeroContentLength(httpMethod)) {
        h2Headers.set(CONTENT_LENGTH, ZERO);
    }
    StreamingHttpRequest request = newRequest(httpMethod, path, HTTP_2_0,
            h2HeadersToH1HeadersServer(h2Headers, httpMethod), allocator, headersFactory);
    ctx.fireChannelRead(request);
    ctx.fireChannelRead(headersFactory.newEmptyTrailers());
}
 
Example 6
Source File: H2ToStH1ServerDuplexHandler.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
private NettyH2HeadersToHttpHeaders h2HeadersToH1HeadersServer(Http2Headers h2Headers,
                                                               @Nullable HttpRequestMethod httpMethod) {
    CharSequence value = h2Headers.getAndRemove(AUTHORITY.value());
    if (value != null) {
        h2Headers.set(HOST, value);
    }
    h2Headers.remove(Http2Headers.PseudoHeaderName.SCHEME.value());
    h2HeadersSanitizeForH1(h2Headers);
    if (httpMethod != null && !h2Headers.contains(HttpHeaderNames.CONTENT_LENGTH) &&
            clientMaySendPayloadBodyFor(httpMethod)) {
        h2Headers.add(HttpHeaderNames.TRANSFER_ENCODING, HttpHeaderValues.CHUNKED);
    }
    return new NettyH2HeadersToHttpHeaders(h2Headers, headersFactory.validateCookies());
}
 
Example 7
Source File: Http2ServerChannelHandler.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
protected void sendHttp2Response(ChannelHandlerContext ctx, int streamId, HttpResponseStatus status, String result) {
    // Send a frame for the response status
    Http2Headers headers = new DefaultHttp2Headers().status(status.codeAsText());
    if (!HttpResponseStatus.OK.equals(status)) {
        headers.set(RemotingConstants.HEAD_RESPONSE_ERROR, "true");
    }
    if (StringUtils.isNotBlank(result)) {
        ByteBuf data = ctx.alloc().buffer();
        data.writeBytes(result.getBytes(RpcConstants.DEFAULT_CHARSET));
        encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
        encoder().writeData(ctx, streamId, data, 0, true, ctx.newPromise());
    } else {
        encoder().writeHeaders(ctx, streamId, headers, 0, true, ctx.newPromise());
    }
}
 
Example 8
Source File: Http2CorsHandler.java    From xrpc with Apache License 2.0 5 votes vote down vote up
private Http2Headers preflightHeaders(HttpMethod requestMethod) {
  final Http2Headers responseHeaders = new DefaultHttp2Headers(true);

  responseHeaders.set(HttpHeaderNames.CONTENT_LENGTH, HttpHeaderValues.ZERO);

  if (!setAccessAllowOriginHeader(responseHeaders)) {
    return responseHeaders;
  }

  if (config.allowedRequestMethods().contains(requestMethod)) {
    responseHeaders.add(HttpHeaderNames.ACCESS_CONTROL_ALLOW_METHODS, requestMethod.toString());
  }

  if (config.isCredentialsAllowed()
      && !responseHeaders.get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN).equals(ANY_ORIGIN)) {
    responseHeaders.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
  }

  if (!config.exposedHeaders().isEmpty()) {
    responseHeaders.set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, config.exposedHeaders());
  }

  responseHeaders.set(HttpHeaderNames.ACCESS_CONTROL_MAX_AGE, String.valueOf(config.maxAge()));
  responseHeaders.set(
      HttpHeaderNames.ACCESS_CONTROL_ALLOW_HEADERS, config.allowedRequestHeaders());

  return responseHeaders;
}
 
Example 9
Source File: Http2CorsHandler.java    From xrpc with Apache License 2.0 5 votes vote down vote up
/**
 * Applies appropriate CORS Headers to outbound response headers.
 *
 * @param responseHeaders outbound response headers
 */
protected void outbound(final Http2Headers responseHeaders) {
  if (!config.isCorsSupportEnabled() || !setAccessAllowOriginHeader(responseHeaders)) {
    return;
  }

  if (config.isCredentialsAllowed()
      && !responseHeaders.get(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN).equals(ANY_ORIGIN)) {
    responseHeaders.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
  }

  if (!config.exposedHeaders().isEmpty()) {
    responseHeaders.set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, config.exposedHeaders());
  }
}
 
Example 10
Source File: Http2CorsHandler.java    From xrpc with Apache License 2.0 5 votes vote down vote up
/**
 * If the origin is allowed, sets the outbound access-allow-origin header to be the request origin
 * and returns true.
 *
 * @param headers for the response.
 * @return true if the request origin is allowed by the CORS configuration.
 */
private boolean setAccessAllowOriginHeader(final Http2Headers headers) {

  if (requestOrigin != null) {
    if (NULL_ORIGIN.equals(requestOrigin) && config.isNullOriginAllowed()) {
      headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, NULL_ORIGIN);
      return true;
    }

    if (config.isAnyOriginSupported()) {
      if (config.isCredentialsAllowed()) {
        headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, requestOrigin);
        headers.set(HttpHeaderNames.VARY, HttpHeaderNames.ORIGIN);
      } else {
        headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, ANY_ORIGIN);
      }
      return true;
    }

    if (config.origins().contains(requestOrigin)) {
      headers.set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, requestOrigin);
      headers.set(HttpHeaderNames.VARY, HttpHeaderNames.ORIGIN);
      return true;
    }
    log.debug(
        "Request origin [{}]] was not among the configured origins [{}]",
        requestOrigin,
        config.origins());
  }
  return false;
}
 
Example 11
Source File: Http2HeadersWrapperUnitTest.java    From xio with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetHeaders() {
  Http2Headers other = new DefaultHttp2Headers();
  other.set("header", "value");
  headers.set(other);
  assertEquals(other, headers.delegate());
  assertEquals("value", headers.delegate().get("header"));
  other.set("header", "value2");
  headers.set(other);
  assertEquals(other, headers.delegate());
  assertEquals("value2", headers.delegate().get("header"));
}
 
Example 12
Source File: Http2HeadersWrapperUnitTest.java    From xio with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetAll() {
  Http2Headers other = new DefaultHttp2Headers();
  other.set("header", "value");
  headers.setAll(other);
  assertEquals(other, headers.delegate());
  assertEquals("value", headers.delegate().get("header"));
  other.set("header", "value2");
  headers.setAll(other);
  assertEquals(other, headers.delegate());
  assertEquals("value2", headers.delegate().get("header"));
}
 
Example 13
Source File: NettyClientStreamTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void invalidInboundHeadersCancelStream() throws Exception {
  stream().transportState().setId(STREAM_ID);
  Http2Headers headers = grpcResponseHeaders();
  headers.set("random", "4");
  headers.remove(CONTENT_TYPE_HEADER);
  // Remove once b/16290036 is fixed.
  headers.status(new AsciiString("500"));
  stream().transportState().transportHeadersReceived(headers, false);
  verify(listener, never()).closed(any(Status.class), any(Metadata.class));

  // We are now waiting for 100 bytes of error context on the stream, cancel has not yet been
  // sent
  verify(channel, never()).writeAndFlush(any(CancelClientStreamCommand.class));
  stream().transportState().transportDataReceived(Unpooled.buffer(100).writeZero(100), false);
  verify(channel, never()).writeAndFlush(any(CancelClientStreamCommand.class));
  stream().transportState().transportDataReceived(Unpooled.buffer(1000).writeZero(1000), false);

  // Now verify that cancel is sent and an error is reported to the listener
  verify(writeQueue).enqueue(isA(CancelClientStreamCommand.class), eq(true));
  ArgumentCaptor<Status> captor = ArgumentCaptor.forClass(Status.class);
  ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
  verify(listener).closed(captor.capture(), same(PROCESSED), metadataCaptor.capture());
  assertEquals(Status.UNKNOWN.getCode(), captor.getValue().getCode());
  assertEquals("4", metadataCaptor.getValue()
      .get(Metadata.Key.of("random", Metadata.ASCII_STRING_MARSHALLER)));

}