MaybeLocal<Object> GetLastIssuedCert(
    X509Pointer* cert,
    const SSLPointer& ssl,
    Local<Object> issuer_chain,
    Environment* const env) {
  Local<Context> context = env->isolate()->GetCurrentContext();
  while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
    X509* ca;
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get(), &ca) <= 0)
      break;

    Local<Object> ca_info;
    MaybeLocal<Object> maybe_ca_info = X509ToObject(env, ca);
    if (!maybe_ca_info.ToLocal(&ca_info))
      return MaybeLocal<Object>();

    if (!Set<Object>(context, issuer_chain, env->issuercert_string(), ca_info))
      return MaybeLocal<Object>();
    issuer_chain = ca_info;

    // Take the value of cert->get() before the call to cert->reset()
    // in order to compare it to ca after and provide a way to exit this loop
    // in case it gets stuck.
    X509* value_before_reset = cert->get();

    // Delete previous cert and continue aggregating issuers.
    cert->reset(ca);

    if (value_before_reset == ca)
      break;
  }
  return MaybeLocal<Object>(issuer_chain);
}
MaybeLocal<Object> GetLastIssuedCert(
    X509Pointer* cert,
    const SSLPointer& ssl,
    Local<Object> issuer_chain,
    Environment* const env) {
  Local<Context> context = env->isolate()->GetCurrentContext();
  while (X509_check_issued(cert->get(), cert->get()) != X509_V_OK) {
    X509* ca;
    if (SSL_CTX_get_issuer(SSL_get_SSL_CTX(ssl.get()), cert->get(), &ca) <= 0)
      break;

    Local<Object> ca_info;
    MaybeLocal<Object> maybe_ca_info = X509ToObject(env, ca);
    if (!maybe_ca_info.ToLocal(&ca_info))
      return MaybeLocal<Object>();

    if (!Set<Object>(context, issuer_chain, env->issuercert_string(), ca_info))
      return MaybeLocal<Object>();
    issuer_chain = ca_info;

     
     
     
    X509* value_before_reset = cert->get();

     
    cert->reset(ca);

    if (value_before_reset == ca)
      break;
  }
  return MaybeLocal<Object>(issuer_chain);
}