Socket connect()

in alloydb-jdbc-connector/src/main/java/com/google/cloud/alloydb/ConnectionSocket.java [84:139]


  Socket connect() throws IOException {
    SSLSocket socket =
        buildSocket(
            connectionInfo.getCaCertificate(),
            connectionInfo.getCertificateChain(),
            this.clientConnectorKeyPair.getPrivate());

    String address;
    switch (connectionConfig.getIpType()) {
      case PUBLIC:
        address = connectionInfo.getPublicIpAddress();
        break;
      case PSC:
        // DNS names always end with a period (.), so remove it.
        address = connectionInfo.getPscDnsName().replaceFirst("\\.$", "");
        break;
      default:
        address = connectionInfo.getIpAddress();
        break;
    }

    if (address == null || address.isEmpty()) {
      throw new RuntimeException(
          String.format(
              "Instance does not have an address matching type: %s", connectionConfig.getIpType()));
    }

    logger.debug(String.format("[%s] Connecting to instance.", address));

    SSLParameters sslParameters = socket.getSSLParameters();
    // Set HTTPS as the the endpoint identification algorithm
    // in order to verify the identity of the certificate as
    // suggested at https://stackoverflow.com/a/17979954/927514
    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
    sslParameters.setServerNames(Collections.singletonList(new SNIHostName(address)));

    socket.setSSLParameters(sslParameters);
    socket.setKeepAlive(true);
    socket.setTcpNoDelay(true);
    socket.connect(new InetSocketAddress(address, SERVER_SIDE_PROXY_PORT));

    try {
      socket.startHandshake();
    } catch (IOException e) {
      logger.debug("TLS handshake failed!");
      throw e;
    }

    // The metadata exchange must occur after the TLS connection is established
    // to avoid leaking sensitive information.
    metadataExchange(socket);

    logger.debug(String.format("[%s] Connected to instance successfully.", address));

    return socket;
  }