io.grpc.okhttp.internal.Platform Java Examples

The following examples show how to use io.grpc.okhttp.internal.Platform. 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: OkHttpProtocolNegotiator.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Override {@link Platform}'s configureTlsExtensions for Android older than 5.0, since OkHttp
 * (2.3+) only support such function for Android 5.0+.
 */
@Override
protected void configureTlsExtensions(
    SSLSocket sslSocket, String hostname, List<Protocol> protocols) {
  // Enable SNI and session tickets.
  if (hostname != null) {
    SET_USE_SESSION_TICKETS.invokeOptionalWithoutCheckedException(sslSocket, true);
    SET_HOSTNAME.invokeOptionalWithoutCheckedException(sslSocket, hostname);
  }

  Object[] parameters = {Platform.concatLengthPrefixed(protocols)};
  if (platform.getTlsExtensionType() == TlsExtensionType.ALPN_AND_NPN) {
    SET_ALPN_PROTOCOLS.invokeWithoutCheckedException(sslSocket, parameters);
  }

  if (platform.getTlsExtensionType() != TlsExtensionType.NONE) {
    SET_NPN_PROTOCOLS.invokeWithoutCheckedException(sslSocket, parameters);
  } else {
    throw new RuntimeException("We can not do TLS handshake on this Android version, please"
        + " install the Google Play Services Dynamic Security Provider to use TLS");
  }
}
 
Example #2
Source File: Http2OkHttpTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private OkHttpChannelBuilder createChannelBuilder() {
  OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("localhost", getPort())
      .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
      .connectionSpec(new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
          .cipherSuites(TestUtils.preferredTestCiphers().toArray(new String[0]))
          .build())
      .overrideAuthority(GrpcUtil.authorityFromHostAndPort(
          TestUtils.TEST_SERVER_HOST, getPort()));
  io.grpc.internal.TestingAccessor.setStatsImplementation(
      builder, createClientCensusStatsModule());
  try {
    builder.sslSocketFactory(TestUtils.newSslSocketFactoryForCa(Platform.get().getProvider(),
        TestUtils.loadCert("ca.pem")));
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  return builder;
}
 
Example #3
Source File: Utils.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private static OkHttpChannelBuilder newOkHttpClientChannel(
    SocketAddress address, boolean tls, boolean testca) {
  InetSocketAddress addr = (InetSocketAddress) address;
  OkHttpChannelBuilder builder =
      OkHttpChannelBuilder.forAddress(addr.getHostName(), addr.getPort());
  if (!tls) {
    builder.usePlaintext();
  } else if (testca) {
    try {
      builder.sslSocketFactory(TestUtils.newSslSocketFactoryForCa(
          Platform.get().getProvider(),
          TestUtils.loadCert("ca.pem")));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  return builder;
}
 
Example #4
Source File: ArmeriaGrpcServerInteropTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected ManagedChannel createChannel() {
    try {
        final int port = server.httpsPort();
        return OkHttpChannelBuilder
                .forAddress("localhost", port)
                .useTransportSecurity()
                .maxInboundMessageSize(16 * 1024 * 1024)
                .connectionSpec(ConnectionSpec.MODERN_TLS)
                .overrideAuthority("example.com:" + port)
                .sslSocketFactory(TestUtils.newSslSocketFactoryForCa(
                        Platform.get().getProvider(), ssc.certificateFile()))
                .build();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example #5
Source File: OkHttpChannelBuilder.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
@Nullable
SSLSocketFactory createSslSocketFactory() {
  switch (negotiationType) {
    case TLS:
      try {
        if (sslSocketFactory == null) {
          SSLContext sslContext = SSLContext.getInstance("Default", Platform.get().getProvider());
          sslSocketFactory = sslContext.getSocketFactory();
        }
        return sslSocketFactory;
      } catch (GeneralSecurityException gse) {
        throw new RuntimeException("TLS Provider failure", gse);
      }
    case PLAINTEXT:
      return null;
    default:
      throw new RuntimeException("Unknown negotiation type: " + negotiationType);
  }
}
 
Example #6
Source File: Http2OkHttpTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private OkHttpChannelBuilder createChannelBuilder() {
  int port = ((InetSocketAddress) getListenAddress()).getPort();
  OkHttpChannelBuilder builder = OkHttpChannelBuilder.forAddress("localhost", port)
      .maxInboundMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE)
      .connectionSpec(new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
          .cipherSuites(TestUtils.preferredTestCiphers().toArray(new String[0]))
          .build())
      .overrideAuthority(GrpcUtil.authorityFromHostAndPort(
          TestUtils.TEST_SERVER_HOST, port));
  try {
    builder.sslSocketFactory(TestUtils.newSslSocketFactoryForCa(Platform.get().getProvider(),
        TestUtils.loadCert("ca.pem")));
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
  // Disable the default census stats interceptor, use testing interceptor instead.
  io.grpc.internal.TestingAccessor.setStatsEnabled(builder, false);
  return builder.intercept(createCensusStatsClientInterceptor());
}
 
Example #7
Source File: Utils.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private static OkHttpChannelBuilder newOkHttpClientChannel(
    SocketAddress address, boolean tls, boolean testca) {
  InetSocketAddress addr = (InetSocketAddress) address;
  OkHttpChannelBuilder builder =
      OkHttpChannelBuilder.forAddress(addr.getHostName(), addr.getPort());
  if (!tls) {
    builder.usePlaintext();
  } else if (testca) {
    try {
      builder.sslSocketFactory(TestUtils.newSslSocketFactoryForCa(
          Platform.get().getProvider(),
          TestUtils.loadCert("ca.pem")));
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  return builder;
}
 
Example #8
Source File: OkHttpChannelBuilder.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
@Nullable
SSLSocketFactory createSocketFactory() {
  switch (negotiationType) {
    case TLS:
      try {
        if (sslSocketFactory == null) {
          SSLContext sslContext;
          if (GrpcUtil.IS_RESTRICTED_APPENGINE) {
            // The following auth code circumvents the following AccessControlException:
            // access denied ("java.util.PropertyPermission" "javax.net.ssl.keyStore" "read")
            // Conscrypt will attempt to load the default KeyStore if a trust manager is not
            // provided, which is forbidden on AppEngine
            sslContext = SSLContext.getInstance("TLS", Platform.get().getProvider());
            TrustManagerFactory trustManagerFactory =
                TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init((KeyStore) null);
            sslContext.init(
                null,
                trustManagerFactory.getTrustManagers(),
                // Use an algorithm that doesn't need /dev/urandom
                SecureRandom.getInstance("SHA1PRNG", Platform.get().getProvider()));

          } else {
            sslContext = SSLContext.getInstance("Default", Platform.get().getProvider());
          }
          sslSocketFactory = sslContext.getSocketFactory();
        }
        return sslSocketFactory;
      } catch (GeneralSecurityException gse) {
        throw new RuntimeException("TLS Provider failure", gse);
      }
    case PLAINTEXT:
      return null;
    default:
      throw new RuntimeException("Unknown negotiation type: " + negotiationType);
  }
}
 
Example #9
Source File: OkHttpProtocolNegotiatorTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void negotiate_noSelectedProtocol() throws Exception {
  Platform platform = mock(Platform.class);

  OkHttpProtocolNegotiator negotiator = new OkHttpProtocolNegotiator(platform);

  thrown.expect(RuntimeException.class);
  thrown.expectMessage("TLS ALPN negotiation failed");

  negotiator.negotiate(sock, "hostname", ImmutableList.of(Protocol.HTTP_2));
}
 
Example #10
Source File: OkHttpProtocolNegotiatorTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void negotiate_noSelectedProtocol() throws Exception {
  Platform platform = mock(Platform.class);

  OkHttpProtocolNegotiator negotiator = new OkHttpProtocolNegotiator(platform);

  thrown.expect(RuntimeException.class);
  thrown.expectMessage("TLS ALPN negotiation failed");

  negotiator.negotiate(sock, "hostname", ImmutableList.of(Protocol.HTTP_2));
}
 
Example #11
Source File: OkHttpProtocolNegotiator.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
OkHttpProtocolNegotiator(Platform platform) {
  this.platform = checkNotNull(platform, "platform");
}
 
Example #12
Source File: OkHttpProtocolNegotiator.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
AndroidNegotiator(Platform platform) {
  super(platform);
}
 
Example #13
Source File: TestServiceClient.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Override
protected ManagedChannel createChannel() {
  if (customCredentialsType != null
      && customCredentialsType.equals("google_default_credentials")) {
    return GoogleDefaultChannelBuilder.forAddress(serverHost, serverPort).build();
  }
  if (useAlts) {
    return AltsChannelBuilder.forAddress(serverHost, serverPort).build();
  }
  AbstractManagedChannelImplBuilder<?> builder;
  if (!useOkHttp) {
    SslContext sslContext = null;
    if (useTestCa) {
      try {
        sslContext = GrpcSslContexts.forClient().trustManager(
                TestUtils.loadCert("ca.pem")).build();
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
    }
    NettyChannelBuilder nettyBuilder =
        NettyChannelBuilder.forAddress(serverHost, serverPort)
            .flowControlWindow(65 * 1024)
            .negotiationType(useTls ? NegotiationType.TLS : NegotiationType.PLAINTEXT)
            .sslContext(sslContext);
    if (serverHostOverride != null) {
      nettyBuilder.overrideAuthority(serverHostOverride);
    }
    if (fullStreamDecompression) {
      nettyBuilder.enableFullStreamDecompression();
    }
    builder = nettyBuilder;
  } else {
    OkHttpChannelBuilder okBuilder = OkHttpChannelBuilder.forAddress(serverHost, serverPort);
    if (serverHostOverride != null) {
      // Force the hostname to match the cert the server uses.
      okBuilder.overrideAuthority(
          GrpcUtil.authorityFromHostAndPort(serverHostOverride, serverPort));
    }
    if (useTls) {
      try {
        SSLSocketFactory factory = useTestCa
            ? TestUtils.newSslSocketFactoryForCa(Platform.get().getProvider(),
                TestUtils.loadCert("ca.pem"))
            : (SSLSocketFactory) SSLSocketFactory.getDefault();
        okBuilder.sslSocketFactory(factory);
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    } else {
      okBuilder.usePlaintext();
    }
    if (fullStreamDecompression) {
      okBuilder.enableFullStreamDecompression();
    }
    builder = okBuilder;
  }
  io.grpc.internal.TestingAccessor.setStatsImplementation(
      builder, createClientCensusStatsModule());
  return builder.build();
}
 
Example #14
Source File: OkHttpProtocolNegotiator.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
OkHttpProtocolNegotiator(Platform platform) {
  this.platform = checkNotNull(platform, "platform");
}
 
Example #15
Source File: OkHttpProtocolNegotiator.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
AndroidNegotiator(Platform platform) {
  super(platform);
}
 
Example #16
Source File: TestServiceClient.java    From grpc-java with Apache License 2.0 4 votes vote down vote up
@Override
protected ManagedChannel createChannel() {
  if (customCredentialsType != null
      && customCredentialsType.equals("google_default_credentials")) {
    return GoogleDefaultChannelBuilder.forAddress(serverHost, serverPort).build();
  }
  if (customCredentialsType != null
      && customCredentialsType.equals("compute_engine_channel_creds")) {
    return ComputeEngineChannelBuilder.forAddress(serverHost, serverPort).build();
  }
  if (useAlts) {
    return AltsChannelBuilder.forAddress(serverHost, serverPort).build();
  }
  AbstractManagedChannelImplBuilder<?> builder;
  if (!useOkHttp) {
    SslContext sslContext = null;
    if (useTestCa) {
      try {
        sslContext = GrpcSslContexts.forClient().trustManager(
                TestUtils.loadCert("ca.pem")).build();
      } catch (Exception ex) {
        throw new RuntimeException(ex);
      }
    }
    NettyChannelBuilder nettyBuilder =
        NettyChannelBuilder.forAddress(serverHost, serverPort)
            .flowControlWindow(65 * 1024)
            .negotiationType(useTls ? NegotiationType.TLS :
              (useH2cUpgrade ? NegotiationType.PLAINTEXT_UPGRADE : NegotiationType.PLAINTEXT))
            .sslContext(sslContext);
    if (serverHostOverride != null) {
      nettyBuilder.overrideAuthority(serverHostOverride);
    }
    if (fullStreamDecompression) {
      nettyBuilder.enableFullStreamDecompression();
    }
    builder = nettyBuilder;
  } else {
    OkHttpChannelBuilder okBuilder = OkHttpChannelBuilder.forAddress(serverHost, serverPort);
    if (serverHostOverride != null) {
      // Force the hostname to match the cert the server uses.
      okBuilder.overrideAuthority(
          GrpcUtil.authorityFromHostAndPort(serverHostOverride, serverPort));
    }
    if (useTls) {
      if (useTestCa) {
        try {
          SSLSocketFactory factory = TestUtils.newSslSocketFactoryForCa(
              Platform.get().getProvider(), TestUtils.loadCert("ca.pem"));
          okBuilder.sslSocketFactory(factory);
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      }
    } else {
      okBuilder.usePlaintext();
    }
    if (fullStreamDecompression) {
      okBuilder.enableFullStreamDecompression();
    }
    builder = okBuilder;
  }
  // Disable the default census stats interceptor, use testing interceptor instead.
  io.grpc.internal.TestingAccessor.setStatsEnabled(builder, false);
  return builder.intercept(createCensusStatsClientInterceptor()).build();
}