Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ public class MockWebServer : Closeable {
try {
val serverSocketFactory =
serverSocketFactory_
?: (ServerSocketFactory.getDefault()!!.also { this.serverSocketFactory_ = it })
?: (Platform.get().serverSocketFactory.also { this.serverSocketFactory_ = it })

val serverSocket =
serverSocketFactory
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import java.net.Proxy
import java.net.ProxySelector
import java.net.Socket
import java.util.concurrent.TimeUnit
import javax.net.SocketFactory
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLSocketFactory
Expand All @@ -42,6 +41,7 @@ import okhttp3.internal.connection.RealConnectionPool
import okhttp3.internal.connection.RealRoutePlanner
import okhttp3.internal.http.RealInterceptorChain
import okhttp3.internal.http.RecordingProxySelector
import okhttp3.internal.platform.Platform
import okhttp3.tls.HandshakeCertificates
import okhttp3.tls.internal.TlsUtil.localhost

Expand Down Expand Up @@ -118,7 +118,7 @@ class TestValueFactory : Closeable {
uriHost = uriHost,
uriPort = uriPort,
dns = dns,
socketFactory = SocketFactory.getDefault(),
socketFactory = Platform.get().socketFactory,
sslSocketFactory = null,
hostnameVerifier = null,
certificatePinner = null,
Expand All @@ -141,7 +141,7 @@ class TestValueFactory : Closeable {
uriHost = uriHost,
uriPort = uriPort,
dns = dns,
socketFactory = SocketFactory.getDefault(),
socketFactory = Platform.get().socketFactory,
sslSocketFactory = sslSocketFactory,
hostnameVerifier = hostnameVerifier,
certificatePinner = null,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
* Copyright (c) 2026 OkHttp Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("Since15")

package okhttp3.sockets

import java.security.Provider
import java.security.SecureRandom
import javax.net.ServerSocketFactory
import javax.net.SocketFactory
import javax.net.ssl.KeyManager
import javax.net.ssl.SSLContext
import javax.net.ssl.SSLContextSpi
import javax.net.ssl.SSLSocket
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509KeyManager
import javax.net.ssl.X509TrustManager
import okhttp3.Protocol
import okhttp3.internal.platform.Platform
import okhttp3.tls.internal.TlsUtil.newKeyManager
import okio.ByteString

class FakeNetworkPlatform : Platform() {
val network = FakeNetwork()

override val socketFactory: SocketFactory
get() = network.socketFactory

override val serverSocketFactory: ServerSocketFactory
get() = network.serverSocketFactory

override fun newSSLContext(): SSLContext {
@Suppress("DEPRECATION") // Non-deprecated overload requires Java 9+.
val provider =
object : Provider("FakeNetwork", 0.0, "") {
}
return object : SSLContext(FakeSslContextSpi(), provider, "TLSv1.2") {
}
}

override fun trustManager(sslSocketFactory: SSLSocketFactory) = null

override fun configureTlsExtensions(
sslSocket: SSLSocket,
hostname: String?,
protocols: List<@JvmSuppressWildcards Protocol>,
echConfigList: ByteString?,
) {
check(sslSocket is FakeSslSocket)
sslSocket.sslParameters.applicationProtocols = protocols.map { it.toString() }.toTypedArray()
sslSocket.echConfigList = echConfigList
}

override fun afterHandshake(sslSocket: SSLSocket) {
}

override fun getSelectedProtocol(sslSocket: SSLSocket): String? = sslSocket.applicationProtocol

override fun getHandshakeServerNames(sslSocket: SSLSocket): List<String> {
val serverNames = sslSocket.sslParameters.serverNames ?: return listOf()
return serverNames.map { it.encoded.decodeToString() }
}

override fun newSslSocketFactory(trustManager: X509TrustManager): SSLSocketFactory {
val sslContext = newSSLContext()
sslContext.init(
arrayOf(newKeyManager(null, null)),
arrayOf(trustManager),
SecureRandom(),
)
return sslContext.socketFactory
}

private class FakeSslContextSpi : SSLContextSpi() {
private var fakeTls: FakeTls? = null

override fun engineInit(
keyManagers: Array<out KeyManager>,
trustManagers: Array<out TrustManager>,
secureRandom: SecureRandom,
) {
check(this.fakeTls == null) { "already initialized" }
fakeTls =
FakeTls(
handshaker = InsecureHandshaker(),
keyManager = keyManagers.filterIsInstance<X509KeyManager>().single(),
trustManager = trustManagers.filterIsInstance<X509TrustManager>().single(),
)
}

override fun engineGetSocketFactory(): SSLSocketFactory {
val fakeTls = this.fakeTls ?: error("call init() first")
return fakeTls.sslSocketFactory
}

override fun engineGetServerSocketFactory() = error("unsupported")

override fun engineCreateSSLEngine() = error("unsupported")

override fun engineCreateSSLEngine(
host: String,
port: Int,
) = error("unsupported")

override fun engineGetServerSessionContext() = error("unsupported")

override fun engineGetClientSessionContext() = error("unsupported")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ internal class FakeSslSocket(
}
private var enableSessionCreation = true
private var useClientMode = true
private var echConfigList: ByteString? = null
var echConfigList: ByteString? = null

override fun getEnabledProtocols(): Array<String> = sslParameters.protocols

Expand Down Expand Up @@ -126,7 +126,7 @@ internal class FakeSslSocket(
tlsVersions = tlsVersions,
cipherSuites = cipherSuites,
protocols = protocols,
handshakeCertificates = tls.handshakeCertificates,
keyManager = tls.keyManager,
hostname = hostname,
echConfigList = echConfigList,
)
Expand All @@ -137,7 +137,7 @@ internal class FakeSslSocket(
tlsVersions = tlsVersions,
cipherSuites = cipherSuites,
protocols = protocols,
handshakeCertificates = tls.handshakeCertificates,
keyManager = tls.keyManager,
clientAuth =
when {
sslParameters.needClientAuth -> Handshaker.ClientAuth.Required
Expand Down
14 changes: 11 additions & 3 deletions okhttp-testing-support/src/main/kotlin/okhttp3/sockets/FakeTls.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import java.io.InputStream
import java.net.InetAddress
import java.net.Socket
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.X509KeyManager
import javax.net.ssl.X509TrustManager
import okhttp3.CipherSuite
import okhttp3.TlsVersion
Expand All @@ -36,7 +37,8 @@ import okhttp3.tls.HandshakeCertificates
*/
class FakeTls(
val handshaker: Handshaker,
val handshakeCertificates: HandshakeCertificates,
val keyManager: X509KeyManager,
val trustManager: X509TrustManager,
val supportedTlsVersions: List<TlsVersion> =
listOf(
TlsVersion.TLS_1_3,
Expand All @@ -50,8 +52,14 @@ class FakeTls(
),
val defaultCipherSuites: List<CipherSuite> = supportedCipherSuites,
) {
val trustManager: X509TrustManager
get() = handshakeCertificates.trustManager
constructor(
handshaker: Handshaker,
handshakeCertificates: HandshakeCertificates,
) : this(
handshaker = handshaker,
keyManager = handshakeCertificates.keyManager,
trustManager = handshakeCertificates.trustManager,
)

val sslSocketFactory =
object : SSLSocketFactory() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@
package okhttp3.sockets

import java.io.IOException
import javax.net.ssl.X509KeyManager
import okhttp3.CipherSuite
import okhttp3.Handshake
import okhttp3.Protocol
import okhttp3.TlsVersion
import okhttp3.tls.HandshakeCertificates
import okio.ByteString
import okio.Socket

Expand Down Expand Up @@ -48,14 +48,14 @@ interface Handshaker {
val tlsVersions: List<TlsVersion>
val cipherSuites: List<CipherSuite>
val protocols: List<Protocol>?
val handshakeCertificates: HandshakeCertificates
val keyManager: X509KeyManager
}

class ClientInputs(
override val tlsVersions: List<TlsVersion>,
override val cipherSuites: List<CipherSuite>,
override val protocols: List<Protocol>?,
override val handshakeCertificates: HandshakeCertificates,
override val keyManager: X509KeyManager,
val hostname: String?,
val echConfigList: ByteString?,
) : Inputs
Expand All @@ -64,7 +64,7 @@ interface Handshaker {
override val tlsVersions: List<TlsVersion>,
override val cipherSuites: List<CipherSuite>,
override val protocols: List<Protocol>?,
override val handshakeCertificates: HandshakeCertificates,
override val keyManager: X509KeyManager,
val clientAuth: ClientAuth,
) : Inputs

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ class InsecureHandshaker : Handshaker {
val clientCertificates =
when (server.clientAuth) {
Handshaker.ClientAuth.Required -> {
client.handshakeCertificates.keyManager.clientCertificatesOrNull(keyType)
client.keyManager.clientCertificatesOrNull(keyType)
?: throw SSLHandshakeException("required client certificates not sent")
}

Handshaker.ClientAuth.Requested -> {
client.handshakeCertificates.keyManager.clientCertificatesOrNull(keyType)
client.keyManager.clientCertificatesOrNull(keyType)
?: listOf()
}

Expand All @@ -61,7 +61,7 @@ class InsecureHandshaker : Handshaker {
}
}

val serverCertificates = server.handshakeCertificates.keyManager.serverCertificates(keyType)
val serverCertificates = server.keyManager.serverCertificates(keyType)

val (clientSocket, serverSocket) = inMemorySocketPair(maxBufferSize = 1024 * 1024)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,12 @@ import java.security.PrivateKey
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import java.util.concurrent.Future
import javax.net.ServerSocketFactory
import javax.net.SocketFactory
import javax.net.ssl.SSLSocket
import okhttp3.Handshake
import okhttp3.Handshake.Companion.handshake
import okhttp3.TestUtil.threadFactory
import okhttp3.internal.closeQuietly
import okhttp3.internal.platform.Platform
import okhttp3.testing.PlatformRule
import okio.ByteString.Companion.toByteString
import org.junit.jupiter.api.AfterEach
Expand Down Expand Up @@ -180,7 +179,7 @@ class HandshakeCertificatesTest {
}

private fun startTlsServer(): InetSocketAddress {
val serverSocketFactory = ServerSocketFactory.getDefault()
val serverSocketFactory = Platform.get().serverSocketFactory

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

overall these seem like a net positive.

serverSocket = serverSocketFactory.createServerSocket()
val serverAddress = InetAddress.getByName("localhost")
serverSocket!!.bind(InetSocketAddress(serverAddress, 0), 50)
Expand Down Expand Up @@ -212,7 +211,7 @@ class HandshakeCertificatesTest {
serverAddress: InetSocketAddress,
): Future<Handshake> {
return executorService.submit<Handshake> {
SocketFactory.getDefault().createSocket().use { rawSocket ->
Platform.get().socketFactory.createSocket().use { rawSocket ->
rawSocket.connect(serverAddress)
val sslSocket =
client.sslSocketFactory().createSocket(
Expand Down
4 changes: 2 additions & 2 deletions okhttp/src/commonJvmAndroid/kotlin/okhttp3/Cache.kt
Original file line number Diff line number Diff line change
Expand Up @@ -704,10 +704,10 @@ class Cache internal constructor(

companion object {
/** Synthetic response header: the local time when the request was sent. */
private val SENT_MILLIS = "${Platform.get().getPrefix()}-Sent-Millis"
private val SENT_MILLIS = "${Platform.get().prefix}-Sent-Millis"

/** Synthetic response header: the local time when the response was received. */
private val RECEIVED_MILLIS = "${Platform.get().getPrefix()}-Received-Millis"
private val RECEIVED_MILLIS = "${Platform.get().prefix}-Received-Millis"
}
}

Expand Down
2 changes: 1 addition & 1 deletion okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,7 @@ open class OkHttpClient internal constructor(
internal var proxy: Proxy? = null
internal var proxySelector: ProxySelector? = null
internal var proxyAuthenticator: Authenticator = Authenticator.NONE
internal var socketFactory: SocketFactory = SocketFactory.getDefault()
internal var socketFactory: SocketFactory = Platform.get().socketFactory
internal var sslSocketFactoryOrNull: SSLSocketFactory? = null
internal var x509TrustManagerOrNull: X509TrustManager? = null
internal var connectionSpecs: List<ConnectionSpec> = DEFAULT_CONNECTION_SPECS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ import java.security.GeneralSecurityException
import java.security.KeyStore
import java.util.logging.Level
import java.util.logging.Logger
import javax.net.ServerSocketFactory
import javax.net.SocketFactory
import javax.net.ssl.ExtendedSSLSession
import javax.net.ssl.SNIHostName
import javax.net.ssl.SSLContext
Expand Down Expand Up @@ -72,8 +74,15 @@ import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
* Supported on Android 6.0+ via `NetworkSecurityPolicy`.
*/
open class Platform {
open val socketFactory: SocketFactory
get() = SocketFactory.getDefault()

open val serverSocketFactory: ServerSocketFactory
get() = ServerSocketFactory.getDefault()

/** Prefix used on custom headers. */
fun getPrefix() = "OkHttp"
val prefix: String
get() = "OkHttp"

open fun newSSLContext(): SSLContext = SSLContext.getInstance("TLS")

Expand Down
Loading
Loading