1
0
mirror of https://github.com/square/okhttp.git synced 2025-08-08 23:42:08 +03:00

Reformat with Spotless (#8180)

* Enable spotless

* Run spotlessApply

* Fixup trimMargin

* Re-run spotlessApply
This commit is contained in:
Jesse Wilson
2024-01-07 20:13:22 -05:00
committed by GitHub
parent 0e312d7804
commit a228fd64cc
442 changed files with 24992 additions and 18542 deletions

View File

@@ -26,13 +26,13 @@ import okhttp3.Dns
*/
internal class BootstrapDns(
private val dnsHostname: String,
private val dnsServers: List<InetAddress>
private val dnsServers: List<InetAddress>,
) : Dns {
@Throws(UnknownHostException::class)
override fun lookup(hostname: String): List<InetAddress> {
if (this.dnsHostname != hostname) {
throw UnknownHostException(
"BootstrapDns called for $hostname instead of $dnsHostname"
"BootstrapDns called for $hostname instead of $dnsHostname",
)
}

View File

@@ -51,7 +51,7 @@ class DnsOverHttps internal constructor(
@get:JvmName("includeIPv6") val includeIPv6: Boolean,
@get:JvmName("post") val post: Boolean,
@get:JvmName("resolvePrivateAddresses") val resolvePrivateAddresses: Boolean,
@get:JvmName("resolvePublicAddresses") val resolvePublicAddresses: Boolean
@get:JvmName("resolvePublicAddresses") val resolvePublicAddresses: Boolean,
) : Dns {
@Throws(UnknownHostException::class)
override fun lookup(hostname: String): List<InetAddress> {
@@ -94,37 +94,46 @@ class DnsOverHttps internal constructor(
networkRequests: MutableList<Call>,
results: MutableList<InetAddress>,
failures: MutableList<Exception>,
type: Int
type: Int,
) {
val request = buildRequest(hostname, type)
val response = getCacheOnlyResponse(request)
response?.let { processResponse(it, hostname, results, failures) } ?: networkRequests.add(
client.newCall(request))
client.newCall(request),
)
}
private fun executeRequests(
hostname: String,
networkRequests: List<Call>,
responses: MutableList<InetAddress>,
failures: MutableList<Exception>
failures: MutableList<Exception>,
) {
val latch = CountDownLatch(networkRequests.size)
for (call in networkRequests) {
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
synchronized(failures) {
failures.add(e)
call.enqueue(
object : Callback {
override fun onFailure(
call: Call,
e: IOException,
) {
synchronized(failures) {
failures.add(e)
}
latch.countDown()
}
latch.countDown()
}
override fun onResponse(call: Call, response: Response) {
processResponse(response, hostname, responses, failures)
latch.countDown()
}
})
override fun onResponse(
call: Call,
response: Response,
) {
processResponse(response, hostname, responses, failures)
latch.countDown()
}
},
)
}
try {
@@ -138,7 +147,7 @@ class DnsOverHttps internal constructor(
response: Response,
hostname: String,
results: MutableList<InetAddress>,
failures: MutableList<Exception>
failures: MutableList<Exception>,
) {
try {
val addresses = readResponse(hostname, response)
@@ -153,7 +162,10 @@ class DnsOverHttps internal constructor(
}
@Throws(UnknownHostException::class)
private fun throwBestFailure(hostname: String, failures: List<Exception>): List<InetAddress> {
private fun throwBestFailure(
hostname: String,
failures: List<Exception>,
): List<InetAddress> {
if (failures.isEmpty()) {
throw UnknownHostException(hostname)
}
@@ -179,7 +191,8 @@ class DnsOverHttps internal constructor(
try {
// Use the cache without hitting the network first
// 504 code indicates that the Cache is stale
val preferCache = CacheControl.Builder()
val preferCache =
CacheControl.Builder()
.onlyIfCached()
.build()
val cacheRequest = request.newBuilder().cacheControl(preferCache).build()
@@ -199,7 +212,10 @@ class DnsOverHttps internal constructor(
}
@Throws(Exception::class)
private fun readResponse(hostname: String, response: Response): List<InetAddress> {
private fun readResponse(
hostname: String,
response: Response,
): List<InetAddress> {
if (response.cacheResponse == null && response.protocol !== Protocol.HTTP_2) {
Platform.get().log("Incorrect protocol: ${response.protocol}", Platform.WARN)
}
@@ -213,7 +229,7 @@ class DnsOverHttps internal constructor(
if (body.contentLength() > MAX_RESPONSE_SIZE) {
throw IOException(
"response size exceeds limit ($MAX_RESPONSE_SIZE bytes): ${body.contentLength()} bytes"
"response size exceeds limit ($MAX_RESPONSE_SIZE bytes): ${body.contentLength()} bytes",
)
}
@@ -223,19 +239,22 @@ class DnsOverHttps internal constructor(
}
}
private fun buildRequest(hostname: String, type: Int): Request =
Request.Builder().header("Accept", DNS_MESSAGE.toString()).apply {
val query = DnsRecordCodec.encodeQuery(hostname, type)
private fun buildRequest(
hostname: String,
type: Int,
): Request =
Request.Builder().header("Accept", DNS_MESSAGE.toString()).apply {
val query = DnsRecordCodec.encodeQuery(hostname, type)
if (post) {
url(url).post(query.toRequestBody(DNS_MESSAGE))
} else {
val encoded = query.base64Url().replace("=", "")
val requestUrl = url.newBuilder().addQueryParameter("dns", encoded).build()
if (post) {
url(url).post(query.toRequestBody(DNS_MESSAGE))
} else {
val encoded = query.base64Url().replace("=", "")
val requestUrl = url.newBuilder().addQueryParameter("dns", encoded).build()
url(requestUrl)
}
}.build()
url(requestUrl)
}
}.build()
class Builder {
internal var client: OkHttpClient? = null
@@ -250,49 +269,56 @@ class DnsOverHttps internal constructor(
fun build(): DnsOverHttps {
val client = this.client ?: throw NullPointerException("client not set")
return DnsOverHttps(
client.newBuilder().dns(buildBootstrapClient(this)).build(),
checkNotNull(url) { "url not set" },
includeIPv6,
post,
resolvePrivateAddresses,
resolvePublicAddresses
client.newBuilder().dns(buildBootstrapClient(this)).build(),
checkNotNull(url) { "url not set" },
includeIPv6,
post,
resolvePrivateAddresses,
resolvePublicAddresses,
)
}
fun client(client: OkHttpClient) = apply {
this.client = client
}
fun client(client: OkHttpClient) =
apply {
this.client = client
}
fun url(url: HttpUrl) = apply {
this.url = url
}
fun url(url: HttpUrl) =
apply {
this.url = url
}
fun includeIPv6(includeIPv6: Boolean) = apply {
this.includeIPv6 = includeIPv6
}
fun includeIPv6(includeIPv6: Boolean) =
apply {
this.includeIPv6 = includeIPv6
}
fun post(post: Boolean) = apply {
this.post = post
}
fun post(post: Boolean) =
apply {
this.post = post
}
fun resolvePrivateAddresses(resolvePrivateAddresses: Boolean) = apply {
this.resolvePrivateAddresses = resolvePrivateAddresses
}
fun resolvePrivateAddresses(resolvePrivateAddresses: Boolean) =
apply {
this.resolvePrivateAddresses = resolvePrivateAddresses
}
fun resolvePublicAddresses(resolvePublicAddresses: Boolean) = apply {
this.resolvePublicAddresses = resolvePublicAddresses
}
fun resolvePublicAddresses(resolvePublicAddresses: Boolean) =
apply {
this.resolvePublicAddresses = resolvePublicAddresses
}
fun bootstrapDnsHosts(bootstrapDnsHosts: List<InetAddress>?) = apply {
this.bootstrapDnsHosts = bootstrapDnsHosts
}
fun bootstrapDnsHosts(bootstrapDnsHosts: List<InetAddress>?) =
apply {
this.bootstrapDnsHosts = bootstrapDnsHosts
}
fun bootstrapDnsHosts(vararg bootstrapDnsHosts: InetAddress): Builder =
bootstrapDnsHosts(bootstrapDnsHosts.toList())
fun bootstrapDnsHosts(vararg bootstrapDnsHosts: InetAddress): Builder = bootstrapDnsHosts(bootstrapDnsHosts.toList())
fun systemDns(systemDns: Dns) = apply {
this.systemDns = systemDns
}
fun systemDns(systemDns: Dns) =
apply {
this.systemDns = systemDns
}
}
companion object {

View File

@@ -33,31 +33,38 @@ internal object DnsRecordCodec {
private const val TYPE_PTR = 0x000c
private val ASCII = Charsets.US_ASCII
fun encodeQuery(host: String, type: Int): ByteString = Buffer().apply {
writeShort(0) // query id
writeShort(256) // flags with recursion
writeShort(1) // question count
writeShort(0) // answerCount
writeShort(0) // authorityResourceCount
writeShort(0) // additional
fun encodeQuery(
host: String,
type: Int,
): ByteString =
Buffer().apply {
writeShort(0) // query id
writeShort(256) // flags with recursion
writeShort(1) // question count
writeShort(0) // answerCount
writeShort(0) // authorityResourceCount
writeShort(0) // additional
val nameBuf = Buffer()
val labels = host.split('.').dropLastWhile { it.isEmpty() }
for (label in labels) {
val utf8ByteCount = label.utf8Size()
require(utf8ByteCount == label.length.toLong()) { "non-ascii hostname: $host" }
nameBuf.writeByte(utf8ByteCount.toInt())
nameBuf.writeUtf8(label)
}
nameBuf.writeByte(0) // end
val nameBuf = Buffer()
val labels = host.split('.').dropLastWhile { it.isEmpty() }
for (label in labels) {
val utf8ByteCount = label.utf8Size()
require(utf8ByteCount == label.length.toLong()) { "non-ascii hostname: $host" }
nameBuf.writeByte(utf8ByteCount.toInt())
nameBuf.writeUtf8(label)
}
nameBuf.writeByte(0) // end
nameBuf.copyTo(this, 0, nameBuf.size)
writeShort(type)
writeShort(1) // CLASS_IN
}.readByteString()
nameBuf.copyTo(this, 0, nameBuf.size)
writeShort(type)
writeShort(1) // CLASS_IN
}.readByteString()
@Throws(Exception::class)
fun decodeAnswers(hostname: String, byteString: ByteString): List<InetAddress> {
fun decodeAnswers(
hostname: String,
byteString: ByteString,
): List<InetAddress> {
val result = mutableListOf<InetAddress>()
val buf = Buffer()
@@ -91,7 +98,8 @@ internal object DnsRecordCodec {
val type = buf.readShort().toInt() and 0xffff
buf.readShort() // class
@Suppress("UNUSED_VARIABLE") val ttl = buf.readInt().toLong() and 0xffffffffL // ttl
@Suppress("UNUSED_VARIABLE")
val ttl = buf.readInt().toLong() and 0xffffffffL // ttl
val length = buf.readShort().toInt() and 0xffff
if (type == TYPE_A || type == TYPE_AAAA) {

View File

@@ -55,9 +55,10 @@ class DnsOverHttpsTest {
private lateinit var server: MockWebServer
private lateinit var dns: Dns
private val cacheFs = FakeFileSystem()
private val bootstrapClient = OkHttpClient.Builder()
.protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1))
.build()
private val bootstrapClient =
OkHttpClient.Builder()
.protocols(listOf(Protocol.HTTP_2, Protocol.HTTP_1_1))
.build()
@BeforeEach
fun setUp(server: MockWebServer) {
@@ -72,8 +73,8 @@ class DnsOverHttpsTest {
dnsResponse(
"0000818000010003000000000567726170680866616365626f6f6b03636f6d0000010001c00c000500010" +
"0000a6d000603617069c012c0300005000100000cde000c04737461720463313072c012c04200010001000" +
"0003b00049df00112"
)
"0003b00049df00112",
),
)
val result = dns.lookup("google.com")
assertThat(result).isEqualTo(listOf(address("157.240.1.18")))
@@ -89,15 +90,15 @@ class DnsOverHttpsTest {
dnsResponse(
"0000818000010003000000000567726170680866616365626f6f6b03636f6d0000010001c00c0005000" +
"100000a6d000603617069c012c0300005000100000cde000c04737461720463313072c012c0420001000" +
"10000003b00049df00112"
)
"10000003b00049df00112",
),
)
server.enqueue(
dnsResponse(
"0000818000010003000000000567726170680866616365626f6f6b03636f6d00001c0001c00c0005000" +
"100000a1b000603617069c012c0300005000100000b1f000c04737461720463313072c012c042001c000" +
"10000003b00102a032880f0290011faceb00c00000002"
)
"10000003b00102a032880f0290011faceb00c00000002",
),
)
dns = buildLocalhost(bootstrapClient, true)
val result = dns.lookup("google.com")
@@ -111,7 +112,7 @@ class DnsOverHttpsTest {
assertThat(listOf(request1.path, request2.path))
.containsExactlyInAnyOrder(
"/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ",
"/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AABwAAQ"
"/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AABwAAQ",
)
}
@@ -121,8 +122,8 @@ class DnsOverHttpsTest {
dnsResponse(
"0000818300010000000100000e7364666c6b686673646c6b6a64660265650000010001c01b00060001000" +
"007070038026e7303746c64c01b0a686f73746d61737465720d6565737469696e7465726e6574c01b5adb1" +
"2c100000e10000003840012750000000e10"
)
"2c100000e10000003840012750000000e10",
),
)
try {
dns.lookup("google.com")
@@ -179,11 +180,11 @@ class DnsOverHttpsTest {
dnsResponse(
"0000818000010003000000000567726170680866616365626f6f6b03636f6d0000010001c00c000500010" +
"0000a6d000603617069c012c0300005000100000cde000c04737461720463313072c012c04200010001000" +
"0003b00049df00112"
"0003b00049df00112",
)
.newBuilder()
.setHeader("cache-control", "private, max-age=298")
.build()
.build(),
)
var result = cachedDns.lookup("google.com")
assertThat(result).containsExactly(address("157.240.1.18"))
@@ -204,29 +205,29 @@ class DnsOverHttpsTest {
dnsResponse(
"0000818000010003000000000567726170680866616365626f6f6b03636f6d0000010001c00c000500010" +
"0000a6d000603617069c012c0300005000100000cde000c04737461720463313072c012c04200010001000" +
"0003b00049df00112"
"0003b00049df00112",
)
.newBuilder()
.setHeader("cache-control", "max-age=1")
.build()
.build(),
)
var result = cachedDns.lookup("google.com")
assertThat(result).containsExactly(address("157.240.1.18"))
var recordedRequest = server.takeRequest(0, TimeUnit.SECONDS)
assertThat(recordedRequest!!.method).isEqualTo("GET")
assertThat(recordedRequest.path).isEqualTo(
"/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ"
"/lookup?ct&dns=AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ",
)
Thread.sleep(2000)
server.enqueue(
dnsResponse(
"0000818000010003000000000567726170680866616365626f6f6b03636f6d0000010001c00c000500010" +
"0000a6d000603617069c012c0300005000100000cde000c04737461720463313072c012c04200010001000" +
"0003b00049df00112"
"0003b00049df00112",
)
.newBuilder()
.setHeader("cache-control", "max-age=1")
.build()
.build(),
)
result = cachedDns.lookup("google.com")
assertThat(result).isEqualTo(listOf(address("157.240.1.18")))
@@ -244,7 +245,10 @@ class DnsOverHttpsTest {
.build()
}
private fun buildLocalhost(bootstrapClient: OkHttpClient, includeIPv6: Boolean): DnsOverHttps {
private fun buildLocalhost(
bootstrapClient: OkHttpClient,
includeIPv6: Boolean,
): DnsOverHttps {
val url = server.url("/lookup?ct")
return DnsOverHttps.Builder().client(bootstrapClient)
.includeIPv6(includeIPv6)

View File

@@ -14,12 +14,12 @@
* limitations under the License.
*/
@file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
package okhttp3.dnsoverhttps
import assertk.assertThat
import assertk.assertions.containsExactly
import assertk.assertions.isEqualTo
import assertk.fail
import java.net.InetAddress
import java.net.UnknownHostException
import kotlin.test.assertFailsWith
@@ -36,7 +36,10 @@ class DnsRecordCodecTest {
assertThat(encoded).isEqualTo("AAABAAABAAAAAAAABmdvb2dsZQNjb20AAAEAAQ")
}
private fun encodeQuery(host: String, type: Int): String {
private fun encodeQuery(
host: String,
type: Int,
): String {
return DnsRecordCodec.encodeQuery(host, type).base64Url().replace("=", "")
}
@@ -48,33 +51,45 @@ class DnsRecordCodecTest {
@Test
fun testGoogleDotComDecodingFromCloudflare() {
val encoded = decodeAnswers(
hostname = "test.com",
byteString = ("00008180000100010000000006676f6f676c6503636f6d0000010001c00c0001000100000043" +
"0004d83ad54e").decodeHex()
)
val encoded =
decodeAnswers(
hostname = "test.com",
byteString =
(
"00008180000100010000000006676f6f676c6503636f6d0000010001c00c0001000100000043" +
"0004d83ad54e"
).decodeHex(),
)
assertThat(encoded).containsExactly(InetAddress.getByName("216.58.213.78"))
}
@Test
fun testGoogleDotComDecodingFromGoogle() {
val decoded = decodeAnswers(
hostname = "test.com",
byteString = ("0000818000010003000000000567726170680866616365626f6f6b03636f6d0000010001c00c" +
"0005000100000a6d000603617069c012c0300005000100000cde000c04737461720463313072c012c0420001" +
"00010000003b00049df00112").decodeHex()
)
val decoded =
decodeAnswers(
hostname = "test.com",
byteString =
(
"0000818000010003000000000567726170680866616365626f6f6b03636f6d0000010001c00c" +
"0005000100000a6d000603617069c012c0300005000100000cde000c04737461720463313072c012c0420001" +
"00010000003b00049df00112"
).decodeHex(),
)
assertThat(decoded).containsExactly(InetAddress.getByName("157.240.1.18"))
}
@Test
fun testGoogleDotComDecodingFromGoogleIPv6() {
val decoded = decodeAnswers(
hostname = "test.com",
byteString = ("0000818000010003000000000567726170680866616365626f6f6b03636f6d00001c0001c00c" +
"0005000100000a1b000603617069c012c0300005000100000b1f000c04737461720463313072c012c042001c" +
"00010000003b00102a032880f0290011faceb00c00000002").decodeHex()
)
val decoded =
decodeAnswers(
hostname = "test.com",
byteString =
(
"0000818000010003000000000567726170680866616365626f6f6b03636f6d00001c0001c00c" +
"0005000100000a1b000603617069c012c0300005000100000b1f000c04737461720463313072c012c042001c" +
"00010000003b00102a032880f0290011faceb00c00000002"
).decodeHex(),
)
assertThat(decoded)
.containsExactly(InetAddress.getByName("2a03:2880:f029:11:face:b00c:0:2"))
}
@@ -84,9 +99,12 @@ class DnsRecordCodecTest {
assertFailsWith<UnknownHostException> {
decodeAnswers(
hostname = "sdflkhfsdlkjdf.ee",
byteString = ("0000818300010000000100000e7364666c6b686673646c6b6a64660265650000010001c01b" +
"00060001000007070038026e7303746c64c01b0a686f73746d61737465720d6565737469696e7465726e65" +
"74c01b5adb12c100000e10000003840012750000000e10").decodeHex()
byteString =
(
"0000818300010000000100000e7364666c6b686673646c6b6a64660265650000010001c01b" +
"00060001000007070038026e7303746c64c01b0a686f73746d61737465720d6565737469696e7465726e65" +
"74c01b5adb12c100000e10000003840012750000000e10"
).decodeHex(),
)
}.also { expected ->
assertThat(expected.message).isEqualTo("sdflkhfsdlkjdf.ee: NXDOMAIN")

View File

@@ -24,7 +24,10 @@ import okhttp3.OkHttpClient
import okhttp3.dnsoverhttps.DohProviders.providers
import org.conscrypt.OpenSSLProvider
private fun runBatch(dnsProviders: List<DnsOverHttps>, names: List<String>) {
private fun runBatch(
dnsProviders: List<DnsOverHttps>,
names: List<String>,
) {
var time = System.currentTimeMillis()
for (dns in dnsProviders) {
println("Testing ${dns.url}")
@@ -54,46 +57,52 @@ fun main() {
var names = listOf("google.com", "graph.facebook.com", "sdflkhfsdlkjdf.ee")
try {
println("uncached\n********\n")
var dnsProviders = providers(
client = bootstrapClient,
http2Only = false,
workingOnly = false,
getOnly = false,
)
var dnsProviders =
providers(
client = bootstrapClient,
http2Only = false,
workingOnly = false,
getOnly = false,
)
runBatch(dnsProviders, names)
val dnsCache = Cache(
directory = File("./target/TestDohMain.cache.${System.currentTimeMillis()}"),
maxSize = 10L * 1024 * 1024
)
val dnsCache =
Cache(
directory = File("./target/TestDohMain.cache.${System.currentTimeMillis()}"),
maxSize = 10L * 1024 * 1024,
)
println("Bad targets\n***********\n")
val url = "https://dns.cloudflare.com/.not-so-well-known/run-dmc-query".toHttpUrl()
val badProviders = listOf(
DnsOverHttps.Builder()
.client(bootstrapClient)
.url(url)
.post(true)
.build()
)
val badProviders =
listOf(
DnsOverHttps.Builder()
.client(bootstrapClient)
.url(url)
.post(true)
.build(),
)
runBatch(badProviders, names)
println("cached first run\n****************\n")
names = listOf("google.com", "graph.facebook.com")
bootstrapClient = bootstrapClient.newBuilder()
.cache(dnsCache)
.build()
dnsProviders = providers(
client = bootstrapClient,
http2Only = true,
workingOnly = true,
getOnly = true,
)
bootstrapClient =
bootstrapClient.newBuilder()
.cache(dnsCache)
.build()
dnsProviders =
providers(
client = bootstrapClient,
http2Only = true,
workingOnly = true,
getOnly = true,
)
runBatch(dnsProviders, names)
println("cached second run\n*****************\n")
dnsProviders = providers(
client = bootstrapClient,
http2Only = true,
workingOnly = true,
getOnly = true,
)
dnsProviders =
providers(
client = bootstrapClient,
http2Only = true,
workingOnly = true,
getOnly = true,
)
runBatch(dnsProviders, names)
} finally {
bootstrapClient.connectionPool.evictAll()