Skip to content

Commit

Permalink
fix: Avoid IPv6 in system DNS queries by default (zio#2280)
Browse files Browse the repository at this point in the history
Currently, there are cases where users cannot use IPv6 due to their network
infrastructure not supporting it. Therefore, we should not resolve hostnames to
IPv6 addresses unless told otherwise.

This commit defaults DNS queries to IPv4-only. It also allows users to resolve
IPv6 addresses by setting the system property `java.net.preferIPv6Addresses`.

/claim zio#2280

Reference: https://docs.oracle.com/javase/8/docs/technotes/guides/net/ipv6_guide/
  • Loading branch information
lackhoa committed Oct 1, 2023
1 parent 5906d30 commit 7c923d0
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions zio-http/src/main/scala/zio/http/DnsResolver.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,9 @@

package zio.http

import java.net.{InetAddress, UnknownHostException}
import java.net.{InetAddress, Inet6Address, UnknownHostException}
import java.time.Instant
import java.lang.{System => JSystem}

import zio._
import zio.stacktracer.TracingImplicits.disableAutoTrace
Expand All @@ -27,15 +28,23 @@ trait DnsResolver {
}

object DnsResolver {
// NOTE: This system property is the only way for users to opt-in to IPv6.
// Even if the flag is set, we use both IPv4 and IPv6 and don't "prefer" IPv6
// in any way.
private final val useIPv6 = JSystem.getProperty("java.net.preferIPv6Addresses") == "true"

def resolve(host: String)(implicit trace: Trace): ZIO[DnsResolver, UnknownHostException, Chunk[InetAddress]] =
ZIO.serviceWithZIO(_.resolve(host))

private final case class SystemResolver() extends DnsResolver {
override def resolve(host: String)(implicit trace: Trace): ZIO[Any, UnknownHostException, Chunk[InetAddress]] =
ZIO
.attemptBlocking(InetAddress.getAllByName(host))
.refineToOrDie[UnknownHostException]
.map(Chunk.fromArray)
override def resolve(host: String)(implicit trace: Trace): ZIO[Any, UnknownHostException, Chunk[InetAddress]] = {
for {
allHosts <- ZIO
.attemptBlocking(InetAddress.getAllByName(host))
.refineToOrDie[UnknownHostException]
.map(Chunk.fromArray)
} yield if (useIPv6) allHosts else allHosts.filter(!_.isInstanceOf[Inet6Address])
}
}

private[http] final case class CacheEntry(
Expand Down

0 comments on commit 7c923d0

Please sign in to comment.