一.简介
OKHttp是一个处理网络请求的开源项目,由移动支付Square公司贡献,用于替代HttpUrlConnection和Apache HttpClient(android API23 6.0里已移除HttpClient)。OKHttp处理的网络请求支持https,因此本篇文章主要时跟踪https使用时的ssl握手过程。
二.ssl握手代码跟踪
okhttp版本: 3.2.0
使用工具: Android Studio
方法: 使用okhttp3框架写一个apk,其中支持使用异步请求访问“https://www.baidu.com”网页,然后使用Android Studio调试并逐步跟入。
代码记录:
- okHttpClient.newCall(request).enqueue(callback);
调式可发现newCall(request)返回的对象类型是RealCall,所在类文件为 /okhttp3/RealCall.java; - client.dispatcher().enqueue(new AsyncCall(responseCallback, forWebSocket));
跟入RealCall,可知异步请求的发送封装在AsyncCall的execute()方法中。 - Response response = getResponseWithInterceptorChain(forWebSocket);
- Response getResponse(Request request, boolean forWebSocket)
所在类为 RealCall。 - HttpEngine 类
engine.sendRequest();
–> httpStream = connect();
–> streamAllocation.newStream()
–> streamAllocation 类中 - streamAllocation 类
RealConnection resultConnection = findHealthyConnection(connectTimeout, readTimeout, writeTimeout, connectionRetryEnabled, doExtensiveHealthChecks);
—> RealConnection candidate = findConnection(connectTimeout, readTimeout, writeTimeout, connectionRetryEnabled);
—> RealConnection newConnection = new RealConnection(selectedRoute);
—> newConnection.connect(connectTimeout, readTimeout, writeTimeout, address.connectionSpecs(), onnectionRetryEnabled);
—> RealConnection 类 - RealConnection 类
connectSocket(connectTimeout, readTimeout, writeTimeout, connectionSpecSelector);
—> connectTls(readTimeout, writeTimeout, connectionSpecSelector);
—> sslSocket = (SSLSocket) sslSocketFactory.createSocket(rawSocket, address.url().host(), address.url().port(), true /* autoClose */);
—> ConnectionSpec connectionSpec = connectionSpecSelector.configureSecureSocket(sslSocket); # Configure the socket’s ciphers, TLS versions, and extensions.
—> sslSocket.startHandshake(); # 开始握手,顾名思义,证书校验和密钥交换都在这一环中
—> Handshake unverifiedHandshake = Handshake.get(sslSocket.getSession()); #unverifiedHandshake中包含tls版本,cipher suite版本,以及服务端的证书
—> address.hostnameVerifier().verify(address.url().host(), sslSocket.getSession()) # 域名校验
三.总结
简单地跟踪了下okhttp3中https使用时的ssl握手过程,不够详细。路过且有兴趣者,可自己跟一遍。若有不足,请多指正。