blob: ecae06e4ccc6a7e047ea7cdf947447bbb038ecbc [file] [log] [blame]
Mike Yubab3daa2018-10-19 22:11:43 +08001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ken Chen5471dca2019-04-15 15:25:35 +080017#define LOG_TAG "resolv"
Mike Yubab3daa2018-10-19 22:11:43 +080018
Bernie Innocentiec4219b2019-01-30 11:16:36 +090019#include "DnsTlsSocket.h"
Mike Yubab3daa2018-10-19 22:11:43 +080020
Mike Yubab3daa2018-10-19 22:11:43 +080021#include <arpa/inet.h>
22#include <arpa/nameser.h>
23#include <errno.h>
24#include <linux/tcp.h>
25#include <openssl/err.h>
26#include <openssl/sha.h>
Ben Schwartz2187abe2019-01-10 14:30:46 -050027#include <sys/eventfd.h>
Mike Yubab3daa2018-10-19 22:11:43 +080028#include <sys/poll.h>
Sehee Park2c118782019-05-07 13:02:45 +090029#include <unistd.h>
Ben Schwartz2187abe2019-01-10 14:30:46 -050030#include <algorithm>
Mike Yubab3daa2018-10-19 22:11:43 +080031
Bernie Innocentiec4219b2019-01-30 11:16:36 +090032#include "DnsTlsSessionCache.h"
33#include "IDnsTlsSocketObserver.h"
Mike Yubab3daa2018-10-19 22:11:43 +080034
chenbruceaff85842019-05-31 15:46:42 +080035#include <android-base/logging.h>
Mike Yu04f1d482019-08-08 11:09:32 +080036#include <netdutils/SocketOption.h>
37#include <netdutils/ThreadUtil.h>
chenbruceaff85842019-05-31 15:46:42 +080038
Mike Yue93d9ae2020-08-25 19:09:51 +080039#include "Experiments.h"
Praveen Moongalam Thyagarajan8ab18ba2019-09-04 14:46:50 -070040#include "netd_resolv/resolv.h"
Sehee Park2c118782019-05-07 13:02:45 +090041#include "private/android_filesystem_config.h" // AID_DNS
Sehee Parkd975bf32019-08-07 13:21:16 +090042#include "resolv_private.h"
Mike Yubab3daa2018-10-19 22:11:43 +080043
44namespace android {
45
46using netdutils::enableSockopt;
47using netdutils::enableTcpKeepAlives;
48using netdutils::isOk;
Mike Yucb902c92020-05-20 19:26:56 +080049using netdutils::setThreadName;
Bernie Innocentiec4219b2019-01-30 11:16:36 +090050using netdutils::Slice;
Mike Yubab3daa2018-10-19 22:11:43 +080051using netdutils::Status;
52
53namespace net {
54namespace {
55
56constexpr const char kCaCertDir[] = "/system/etc/security/cacerts";
Mike Yubab3daa2018-10-19 22:11:43 +080057
Mike Yua772c202019-09-23 17:47:21 +080058int waitForReading(int fd, int timeoutMs = -1) {
59 pollfd fds = {.fd = fd, .events = POLLIN};
60 return TEMP_FAILURE_RETRY(poll(&fds, 1, timeoutMs));
Mike Yubab3daa2018-10-19 22:11:43 +080061}
62
Mike Yua772c202019-09-23 17:47:21 +080063int waitForWriting(int fd, int timeoutMs = -1) {
64 pollfd fds = {.fd = fd, .events = POLLOUT};
65 return TEMP_FAILURE_RETRY(poll(&fds, 1, timeoutMs));
Mike Yubab3daa2018-10-19 22:11:43 +080066}
67
68} // namespace
69
70Status DnsTlsSocket::tcpConnect() {
chenbruceaff85842019-05-31 15:46:42 +080071 LOG(DEBUG) << mMark << " connecting TCP socket";
Mike Yubab3daa2018-10-19 22:11:43 +080072 int type = SOCK_NONBLOCK | SOCK_CLOEXEC;
73 switch (mServer.protocol) {
74 case IPPROTO_TCP:
75 type |= SOCK_STREAM;
76 break;
77 default:
78 return Status(EPROTONOSUPPORT);
79 }
80
81 mSslFd.reset(socket(mServer.ss.ss_family, type, mServer.protocol));
82 if (mSslFd.get() == -1) {
Mike Yuf6b64092020-09-18 14:25:58 +080083 PLOG(ERROR) << "Failed to create socket";
Mike Yubab3daa2018-10-19 22:11:43 +080084 return Status(errno);
85 }
86
Praveen Moongalam Thyagarajan8ab18ba2019-09-04 14:46:50 -070087 resolv_tag_socket(mSslFd.get(), AID_DNS, NET_CONTEXT_INVALID_PID);
Sehee Park2c118782019-05-07 13:02:45 +090088
Mike Yubab3daa2018-10-19 22:11:43 +080089 const socklen_t len = sizeof(mMark);
90 if (setsockopt(mSslFd.get(), SOL_SOCKET, SO_MARK, &mMark, len) == -1) {
Mike Yuf6b64092020-09-18 14:25:58 +080091 const int err = errno;
92 PLOG(ERROR) << "Failed to set socket mark";
Mike Yubab3daa2018-10-19 22:11:43 +080093 mSslFd.reset();
Mike Yuf6b64092020-09-18 14:25:58 +080094 return Status(err);
Mike Yubab3daa2018-10-19 22:11:43 +080095 }
96
97 const Status tfo = enableSockopt(mSslFd.get(), SOL_TCP, TCP_FASTOPEN_CONNECT);
98 if (!isOk(tfo) && tfo.code() != ENOPROTOOPT) {
chenbruceaff85842019-05-31 15:46:42 +080099 LOG(WARNING) << "Failed to enable TFO: " << tfo.msg();
Mike Yubab3daa2018-10-19 22:11:43 +0800100 }
101
102 // Send 5 keepalives, 3 seconds apart, after 15 seconds of inactivity.
103 enableTcpKeepAlives(mSslFd.get(), 15U, 5U, 3U).ignoreError();
104
105 if (connect(mSslFd.get(), reinterpret_cast<const struct sockaddr *>(&mServer.ss),
106 sizeof(mServer.ss)) != 0 &&
107 errno != EINPROGRESS) {
Mike Yuf6b64092020-09-18 14:25:58 +0800108 const int err = errno;
Mike Yu423b58e2021-04-07 17:09:09 +0800109 PLOG(WARNING) << "Socket failed to connect";
Mike Yubab3daa2018-10-19 22:11:43 +0800110 mSslFd.reset();
Mike Yuf6b64092020-09-18 14:25:58 +0800111 return Status(err);
Mike Yubab3daa2018-10-19 22:11:43 +0800112 }
113
114 return netdutils::status::ok;
115}
116
waynema0e73c2e2019-07-31 15:04:08 +0800117bool DnsTlsSocket::setTestCaCertificate() {
118 bssl::UniquePtr<BIO> bio(
119 BIO_new_mem_buf(mServer.certificate.data(), mServer.certificate.size()));
120 bssl::UniquePtr<X509> cert(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
121 if (!cert) {
122 LOG(ERROR) << "Failed to read cert";
Mike Yubab3daa2018-10-19 22:11:43 +0800123 return false;
124 }
waynema0e73c2e2019-07-31 15:04:08 +0800125
126 X509_STORE* cert_store = SSL_CTX_get_cert_store(mSslCtx.get());
127 if (!X509_STORE_add_cert(cert_store, cert.get())) {
128 LOG(ERROR) << "Failed to add cert";
Mike Yubab3daa2018-10-19 22:11:43 +0800129 return false;
130 }
131 return true;
132}
133
waynema0e73c2e2019-07-31 15:04:08 +0800134// TODO: Try to use static sSslCtx instead of mSslCtx
Mike Yubab3daa2018-10-19 22:11:43 +0800135bool DnsTlsSocket::initialize() {
waynema0e73c2e2019-07-31 15:04:08 +0800136 // This method is called every time when a new SSL connection is created.
137 // This lock only serves to help catch bugs in code that calls this method.
Mike Yubab3daa2018-10-19 22:11:43 +0800138 std::lock_guard guard(mLock);
139 if (mSslCtx) {
140 // This is a bug in the caller.
141 return false;
142 }
143 mSslCtx.reset(SSL_CTX_new(TLS_method()));
144 if (!mSslCtx) {
145 return false;
146 }
147
waynema0e73c2e2019-07-31 15:04:08 +0800148 // Load system CA certs from CAPath for hostname verification.
Mike Yubab3daa2018-10-19 22:11:43 +0800149 //
150 // For discussion of alternative, sustainable approaches see b/71909242.
Ken Chen18f64f12020-01-16 21:12:56 +0800151 if (!mServer.certificate.empty()) {
Ken Chen26dc2b02020-06-16 18:49:39 +0800152 // Inject test CA certs from ResolverParamsParcel.caCertificate for INTERNAL TESTING ONLY.
153 // This is only allowed by DnsResolverService if the caller is AID_ROOT.
Lorenzo Colitti4658b252019-11-14 23:45:05 +0900154 LOG(WARNING) << "Setting test CA certificate. This should never happen in production code.";
waynema0e73c2e2019-07-31 15:04:08 +0800155 if (!setTestCaCertificate()) {
156 LOG(ERROR) << "Failed to set test CA certificate";
157 return false;
158 }
159 } else {
160 if (SSL_CTX_load_verify_locations(mSslCtx.get(), nullptr, kCaCertDir) != 1) {
161 LOG(ERROR) << "Failed to load CA cert dir: " << kCaCertDir;
162 return false;
163 }
Mike Yubab3daa2018-10-19 22:11:43 +0800164 }
165
166 // Enable TLS false start
167 SSL_CTX_set_false_start_allowed_without_alpn(mSslCtx.get(), 1);
168 SSL_CTX_set_mode(mSslCtx.get(), SSL_MODE_ENABLE_FALSE_START);
169
170 // Enable session cache
171 mCache->prepareSslContext(mSslCtx.get());
172
Mike Yu441d9372020-07-15 17:06:22 +0800173 mEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
Mike Yue93d9ae2020-08-25 19:09:51 +0800174 mShutdownEvent.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
Mike Yu441d9372020-07-15 17:06:22 +0800175
Mike Yu19192712020-08-28 11:56:31 +0800176 const Experiments* const instance = Experiments::getInstance();
177 mConnectTimeoutMs = instance->getFlag("dot_connect_timeout_ms", kDotConnectTimeoutMs);
178 if (mConnectTimeoutMs < 1000) mConnectTimeoutMs = 1000;
179
180 mAsyncHandshake = instance->getFlag("dot_async_handshake", 0);
181 LOG(DEBUG) << "DnsTlsSocket is initialized with { mConnectTimeoutMs: " << mConnectTimeoutMs
182 << ", mAsyncHandshake: " << mAsyncHandshake << " }";
183
Mike Yu0c8e4522020-08-24 14:41:32 +0800184 transitionState(State::UNINITIALIZED, State::INITIALIZED);
185
Mike Yu441d9372020-07-15 17:06:22 +0800186 return true;
187}
188
189bool DnsTlsSocket::startHandshake() {
190 std::lock_guard guard(mLock);
Mike Yu0c8e4522020-08-24 14:41:32 +0800191 if (mState != State::INITIALIZED) {
192 LOG(ERROR) << "Calling startHandshake in unexpected state " << static_cast<int>(mState);
Mike Yu441d9372020-07-15 17:06:22 +0800193 return false;
194 }
Mike Yu0c8e4522020-08-24 14:41:32 +0800195 transitionState(State::INITIALIZED, State::CONNECTING);
Mike Yu441d9372020-07-15 17:06:22 +0800196
Mike Yue93d9ae2020-08-25 19:09:51 +0800197 if (!mAsyncHandshake) {
198 if (Status status = tcpConnect(); !status.ok()) {
199 transitionState(State::CONNECTING, State::WAIT_FOR_DELETE);
200 LOG(WARNING) << "TCP Handshake failed: " << status.code();
201 return false;
202 }
203 if (mSsl = sslConnect(mSslFd.get()); !mSsl) {
204 transitionState(State::CONNECTING, State::WAIT_FOR_DELETE);
205 LOG(WARNING) << "TLS Handshake failed";
206 return false;
207 }
Mike Yubab3daa2018-10-19 22:11:43 +0800208 }
Ben Schwartz2187abe2019-01-10 14:30:46 -0500209
Mike Yubab3daa2018-10-19 22:11:43 +0800210 // Start the I/O loop.
211 mLoopThread.reset(new std::thread(&DnsTlsSocket::loop, this));
212
213 return true;
214}
215
Mike Yue93d9ae2020-08-25 19:09:51 +0800216bssl::UniquePtr<SSL> DnsTlsSocket::prepareForSslConnect(int fd) {
Mike Yubab3daa2018-10-19 22:11:43 +0800217 if (!mSslCtx) {
chenbruceaff85842019-05-31 15:46:42 +0800218 LOG(ERROR) << "Internal error: context is null in sslConnect";
Mike Yubab3daa2018-10-19 22:11:43 +0800219 return nullptr;
220 }
221 if (!SSL_CTX_set_min_proto_version(mSslCtx.get(), TLS1_2_VERSION)) {
chenbruceaff85842019-05-31 15:46:42 +0800222 LOG(ERROR) << "Failed to set minimum TLS version";
Mike Yubab3daa2018-10-19 22:11:43 +0800223 return nullptr;
224 }
225
226 bssl::UniquePtr<SSL> ssl(SSL_new(mSslCtx.get()));
227 // This file descriptor is owned by mSslFd, so don't let libssl close it.
228 bssl::UniquePtr<BIO> bio(BIO_new_socket(fd, BIO_NOCLOSE));
229 SSL_set_bio(ssl.get(), bio.get(), bio.get());
Maciej Żenczykowski3ff678b2020-04-23 08:51:26 -0700230 (void)bio.release();
Mike Yubab3daa2018-10-19 22:11:43 +0800231
232 if (!mCache->prepareSsl(ssl.get())) {
233 return nullptr;
234 }
235
236 if (!mServer.name.empty()) {
waynema0e73c2e2019-07-31 15:04:08 +0800237 LOG(VERBOSE) << "Checking DNS over TLS hostname = " << mServer.name.c_str();
Mike Yubab3daa2018-10-19 22:11:43 +0800238 if (SSL_set_tlsext_host_name(ssl.get(), mServer.name.c_str()) != 1) {
waynema0e73c2e2019-07-31 15:04:08 +0800239 LOG(ERROR) << "Failed to set SNI to " << mServer.name;
Mike Yubab3daa2018-10-19 22:11:43 +0800240 return nullptr;
241 }
242 X509_VERIFY_PARAM* param = SSL_get0_param(ssl.get());
243 if (X509_VERIFY_PARAM_set1_host(param, mServer.name.data(), mServer.name.size()) != 1) {
chenbruceaff85842019-05-31 15:46:42 +0800244 LOG(ERROR) << "Failed to set verify host param to " << mServer.name;
Mike Yubab3daa2018-10-19 22:11:43 +0800245 return nullptr;
246 }
247 // This will cause the handshake to fail if certificate verification fails.
248 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, nullptr);
249 }
250
251 bssl::UniquePtr<SSL_SESSION> session = mCache->getSession();
252 if (session) {
chenbruceaff85842019-05-31 15:46:42 +0800253 LOG(DEBUG) << "Setting session";
Mike Yubab3daa2018-10-19 22:11:43 +0800254 SSL_set_session(ssl.get(), session.get());
255 } else {
chenbruceaff85842019-05-31 15:46:42 +0800256 LOG(DEBUG) << "No session available";
Mike Yubab3daa2018-10-19 22:11:43 +0800257 }
258
Mike Yue93d9ae2020-08-25 19:09:51 +0800259 return ssl;
260}
261
262bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {
263 bssl::UniquePtr<SSL> ssl;
264 if (ssl = prepareForSslConnect(fd); !ssl) {
265 return nullptr;
266 }
267
Mike Yubab3daa2018-10-19 22:11:43 +0800268 for (;;) {
Mike Yu17bb79a2020-05-20 19:57:12 +0800269 LOG(DEBUG) << " Calling SSL_connect with mark 0x" << std::hex << mMark;
Mike Yubab3daa2018-10-19 22:11:43 +0800270 int ret = SSL_connect(ssl.get());
Mike Yu17bb79a2020-05-20 19:57:12 +0800271 LOG(DEBUG) << " SSL_connect returned " << ret << " with mark 0x" << std::hex << mMark;
Mike Yubab3daa2018-10-19 22:11:43 +0800272 if (ret == 1) break; // SSL handshake complete;
273
274 const int ssl_err = SSL_get_error(ssl.get(), ret);
275 switch (ssl_err) {
276 case SSL_ERROR_WANT_READ:
Mike Yua772c202019-09-23 17:47:21 +0800277 // SSL_ERROR_WANT_READ is returned because the application data has been sent during
278 // the TCP connection handshake, the device is waiting for the SSL handshake reply
279 // from the server.
Mike Yu19192712020-08-28 11:56:31 +0800280 if (int err = waitForReading(fd, mConnectTimeoutMs); err <= 0) {
Mike Yu17bb79a2020-05-20 19:57:12 +0800281 PLOG(WARNING) << "SSL_connect read error " << err << ", mark 0x" << std::hex
282 << mMark;
Mike Yubab3daa2018-10-19 22:11:43 +0800283 return nullptr;
284 }
285 break;
286 case SSL_ERROR_WANT_WRITE:
Mike Yua772c202019-09-23 17:47:21 +0800287 // If no application data is sent during the TCP connection handshake, the
288 // device is waiting for the connection established to perform SSL handshake.
Mike Yu19192712020-08-28 11:56:31 +0800289 if (int err = waitForWriting(fd, mConnectTimeoutMs); err <= 0) {
Mike Yu17bb79a2020-05-20 19:57:12 +0800290 PLOG(WARNING) << "SSL_connect write error " << err << ", mark 0x" << std::hex
291 << mMark;
Mike Yubab3daa2018-10-19 22:11:43 +0800292 return nullptr;
293 }
294 break;
295 default:
Mike Yu17bb79a2020-05-20 19:57:12 +0800296 PLOG(WARNING) << "SSL_connect ssl error =" << ssl_err << ", mark 0x" << std::hex
297 << mMark;
Mike Yubab3daa2018-10-19 22:11:43 +0800298 return nullptr;
299 }
300 }
301
chenbruceaff85842019-05-31 15:46:42 +0800302 LOG(DEBUG) << mMark << " handshake complete";
Mike Yubab3daa2018-10-19 22:11:43 +0800303
304 return ssl;
305}
306
Mike Yue93d9ae2020-08-25 19:09:51 +0800307bssl::UniquePtr<SSL> DnsTlsSocket::sslConnectV2(int fd) {
308 bssl::UniquePtr<SSL> ssl;
309 if (ssl = prepareForSslConnect(fd); !ssl) {
310 return nullptr;
311 }
312
313 for (;;) {
314 LOG(DEBUG) << " Calling SSL_connect with mark 0x" << std::hex << mMark;
315 int ret = SSL_connect(ssl.get());
316 LOG(DEBUG) << " SSL_connect returned " << ret << " with mark 0x" << std::hex << mMark;
317 if (ret == 1) break; // SSL handshake complete;
318
319 enum { SSLFD = 0, EVENTFD = 1 };
320 pollfd fds[2] = {
321 {.fd = mSslFd.get(), .events = 0},
322 {.fd = mShutdownEvent.get(), .events = POLLIN},
323 };
324
325 const int ssl_err = SSL_get_error(ssl.get(), ret);
326 switch (ssl_err) {
327 case SSL_ERROR_WANT_READ:
328 fds[SSLFD].events = POLLIN;
329 break;
330 case SSL_ERROR_WANT_WRITE:
331 fds[SSLFD].events = POLLOUT;
332 break;
333 default:
334 PLOG(WARNING) << "SSL_connect ssl error =" << ssl_err << ", mark 0x" << std::hex
335 << mMark;
336 return nullptr;
337 }
338
Mike Yu19192712020-08-28 11:56:31 +0800339 int n = TEMP_FAILURE_RETRY(poll(fds, std::size(fds), mConnectTimeoutMs));
Mike Yue93d9ae2020-08-25 19:09:51 +0800340 if (n <= 0) {
341 PLOG(WARNING) << ((n == 0) ? "handshake timeout" : "Poll failed");
342 return nullptr;
343 }
344
345 if (fds[EVENTFD].revents & (POLLIN | POLLERR)) {
346 LOG(WARNING) << "Got shutdown request during handshake";
347 return nullptr;
348 }
349 if (fds[SSLFD].revents & POLLERR) {
350 LOG(WARNING) << "Got POLLERR on SSLFD during handshake";
351 return nullptr;
352 }
353 }
354
355 LOG(DEBUG) << mMark << " handshake complete";
356
357 return ssl;
358}
359
Mike Yubab3daa2018-10-19 22:11:43 +0800360void DnsTlsSocket::sslDisconnect() {
361 if (mSsl) {
362 SSL_shutdown(mSsl.get());
363 mSsl.reset();
364 }
365 mSslFd.reset();
366}
367
368bool DnsTlsSocket::sslWrite(const Slice buffer) {
chenbruceaff85842019-05-31 15:46:42 +0800369 LOG(DEBUG) << mMark << " Writing " << buffer.size() << " bytes";
Mike Yubab3daa2018-10-19 22:11:43 +0800370 for (;;) {
371 int ret = SSL_write(mSsl.get(), buffer.base(), buffer.size());
372 if (ret == int(buffer.size())) break; // SSL write complete;
373
374 if (ret < 1) {
375 const int ssl_err = SSL_get_error(mSsl.get(), ret);
376 switch (ssl_err) {
377 case SSL_ERROR_WANT_WRITE:
Mike Yua772c202019-09-23 17:47:21 +0800378 if (int err = waitForWriting(mSslFd.get()); err <= 0) {
379 PLOG(WARNING) << "Poll failed in sslWrite, error " << err;
Mike Yubab3daa2018-10-19 22:11:43 +0800380 return false;
381 }
382 continue;
383 case 0:
384 break; // SSL write complete;
385 default:
chenbruceaff85842019-05-31 15:46:42 +0800386 LOG(DEBUG) << "SSL_write error " << ssl_err;
Mike Yubab3daa2018-10-19 22:11:43 +0800387 return false;
388 }
389 }
390 }
chenbruceaff85842019-05-31 15:46:42 +0800391 LOG(DEBUG) << mMark << " Wrote " << buffer.size() << " bytes";
Mike Yubab3daa2018-10-19 22:11:43 +0800392 return true;
393}
394
395void DnsTlsSocket::loop() {
396 std::lock_guard guard(mLock);
Ben Schwartz2187abe2019-01-10 14:30:46 -0500397 std::deque<std::vector<uint8_t>> q;
Mike Yubab3daa2018-10-19 22:11:43 +0800398 const int timeout_msecs = DnsTlsSocket::kIdleTimeout.count() * 1000;
Mike Yu04f1d482019-08-08 11:09:32 +0800399
chenbruce9b72daa2021-08-20 00:00:49 +0800400 setThreadName(fmt::format("TlsListen_{}", mMark & 0xffff));
Mike Yu0c8e4522020-08-24 14:41:32 +0800401
Mike Yue93d9ae2020-08-25 19:09:51 +0800402 if (mAsyncHandshake) {
403 if (Status status = tcpConnect(); !status.ok()) {
404 LOG(WARNING) << "TCP Handshake failed: " << status.code();
405 mObserver->onClosed();
406 transitionState(State::CONNECTING, State::WAIT_FOR_DELETE);
407 return;
408 }
409 if (mSsl = sslConnectV2(mSslFd.get()); !mSsl) {
410 LOG(WARNING) << "TLS Handshake failed";
411 mObserver->onClosed();
412 transitionState(State::CONNECTING, State::WAIT_FOR_DELETE);
413 return;
414 }
415 LOG(DEBUG) << "Handshaking succeeded";
416 }
417
418 transitionState(State::CONNECTING, State::CONNECTED);
419
Mike Yubab3daa2018-10-19 22:11:43 +0800420 while (true) {
421 // poll() ignores negative fds
422 struct pollfd fds[2] = { { .fd = -1 }, { .fd = -1 } };
Ben Schwartz2187abe2019-01-10 14:30:46 -0500423 enum { SSLFD = 0, EVENTFD = 1 };
Mike Yubab3daa2018-10-19 22:11:43 +0800424
425 // Always listen for a response from server.
426 fds[SSLFD].fd = mSslFd.get();
427 fds[SSLFD].events = POLLIN;
428
Ben Schwartz2187abe2019-01-10 14:30:46 -0500429 // If we have pending queries, wait for space to write one.
430 // Otherwise, listen for new queries.
Ben Schwartz62176fd2019-01-22 17:32:17 -0500431 // Note: This blocks the destructor until q is empty, i.e. until all pending
432 // queries are sent or have failed to send.
Ben Schwartz2187abe2019-01-10 14:30:46 -0500433 if (!q.empty()) {
Mike Yubab3daa2018-10-19 22:11:43 +0800434 fds[SSLFD].events |= POLLOUT;
435 } else {
Ben Schwartz2187abe2019-01-10 14:30:46 -0500436 fds[EVENTFD].fd = mEventFd.get();
437 fds[EVENTFD].events = POLLIN;
Mike Yubab3daa2018-10-19 22:11:43 +0800438 }
439
440 const int s = TEMP_FAILURE_RETRY(poll(fds, std::size(fds), timeout_msecs));
441 if (s == 0) {
chenbruceaff85842019-05-31 15:46:42 +0800442 LOG(DEBUG) << "Idle timeout";
Mike Yubab3daa2018-10-19 22:11:43 +0800443 break;
444 }
445 if (s < 0) {
Mike Yuf6b64092020-09-18 14:25:58 +0800446 PLOG(DEBUG) << "Poll failed";
Mike Yubab3daa2018-10-19 22:11:43 +0800447 break;
448 }
Ben Schwartz62176fd2019-01-22 17:32:17 -0500449 if (fds[SSLFD].revents & (POLLIN | POLLERR | POLLHUP)) {
Mike Yu5e1b9912020-11-10 16:50:13 +0800450 bool readFailed = false;
451
452 // readResponse() only reads one DNS (and consumes exact bytes) from ssl.
453 // Keep doing so until ssl has no pending data.
454 // TODO: readResponse() can block until it reads a complete DNS response. Consider
455 // refactoring it to not get blocked in any case.
456 do {
457 if (!readResponse()) {
458 LOG(DEBUG) << "SSL remote close or read error.";
459 readFailed = true;
460 }
461 } while (SSL_pending(mSsl.get()) > 0 && !readFailed);
462
463 if (readFailed) {
Mike Yubab3daa2018-10-19 22:11:43 +0800464 break;
465 }
466 }
Ben Schwartz2187abe2019-01-10 14:30:46 -0500467 if (fds[EVENTFD].revents & (POLLIN | POLLERR)) {
468 int64_t num_queries;
469 ssize_t res = read(mEventFd.get(), &num_queries, sizeof(num_queries));
Mike Yubab3daa2018-10-19 22:11:43 +0800470 if (res < 0) {
chenbruceaff85842019-05-31 15:46:42 +0800471 LOG(WARNING) << "Error during eventfd read";
Mike Yubab3daa2018-10-19 22:11:43 +0800472 break;
473 } else if (res == 0) {
chenbruceaff85842019-05-31 15:46:42 +0800474 LOG(WARNING) << "eventfd closed; disconnecting";
Mike Yubab3daa2018-10-19 22:11:43 +0800475 break;
Ben Schwartz2187abe2019-01-10 14:30:46 -0500476 } else if (res != sizeof(num_queries)) {
chenbruceaff85842019-05-31 15:46:42 +0800477 LOG(ERROR) << "Int size mismatch: " << res << " != " << sizeof(num_queries);
Ben Schwartz2187abe2019-01-10 14:30:46 -0500478 break;
Ben Schwartz62176fd2019-01-22 17:32:17 -0500479 } else if (num_queries < 0) {
chenbruceaff85842019-05-31 15:46:42 +0800480 LOG(DEBUG) << "Negative eventfd read indicates destructor-initiated shutdown";
Ben Schwartz2187abe2019-01-10 14:30:46 -0500481 break;
482 }
483 // Take ownership of all pending queries. (q is always empty here.)
484 mQueue.swap(q);
Mike Yubab3daa2018-10-19 22:11:43 +0800485 } else if (fds[SSLFD].revents & POLLOUT) {
Ben Schwartz2187abe2019-01-10 14:30:46 -0500486 // q cannot be empty here.
487 // Sending the entire queue here would risk a TCP flow control deadlock, so
488 // we only send a single query on each cycle of this loop.
489 // TODO: Coalesce multiple pending queries if there is enough space in the
490 // write buffer.
491 if (!sendQuery(q.front())) {
Mike Yubab3daa2018-10-19 22:11:43 +0800492 break;
493 }
Ben Schwartz2187abe2019-01-10 14:30:46 -0500494 q.pop_front();
Mike Yubab3daa2018-10-19 22:11:43 +0800495 }
496 }
chenbruceaff85842019-05-31 15:46:42 +0800497 LOG(DEBUG) << "Disconnecting";
Mike Yubab3daa2018-10-19 22:11:43 +0800498 sslDisconnect();
chenbruceaff85842019-05-31 15:46:42 +0800499 LOG(DEBUG) << "Calling onClosed";
Mike Yubab3daa2018-10-19 22:11:43 +0800500 mObserver->onClosed();
Mike Yu0c8e4522020-08-24 14:41:32 +0800501 transitionState(State::CONNECTED, State::WAIT_FOR_DELETE);
chenbruceaff85842019-05-31 15:46:42 +0800502 LOG(DEBUG) << "Ending loop";
Mike Yubab3daa2018-10-19 22:11:43 +0800503}
504
505DnsTlsSocket::~DnsTlsSocket() {
chenbruceaff85842019-05-31 15:46:42 +0800506 LOG(DEBUG) << "Destructor";
Mike Yubab3daa2018-10-19 22:11:43 +0800507 // This will trigger an orderly shutdown in loop().
Ben Schwartz62176fd2019-01-22 17:32:17 -0500508 requestLoopShutdown();
Mike Yubab3daa2018-10-19 22:11:43 +0800509 {
510 // Wait for the orderly shutdown to complete.
511 std::lock_guard guard(mLock);
512 if (mLoopThread && std::this_thread::get_id() == mLoopThread->get_id()) {
chenbruceaff85842019-05-31 15:46:42 +0800513 LOG(ERROR) << "Violation of re-entrance precondition";
Mike Yubab3daa2018-10-19 22:11:43 +0800514 return;
515 }
516 }
517 if (mLoopThread) {
chenbruceaff85842019-05-31 15:46:42 +0800518 LOG(DEBUG) << "Waiting for loop thread to terminate";
Mike Yubab3daa2018-10-19 22:11:43 +0800519 mLoopThread->join();
520 mLoopThread.reset();
521 }
chenbruceaff85842019-05-31 15:46:42 +0800522 LOG(DEBUG) << "Destructor completed";
Mike Yubab3daa2018-10-19 22:11:43 +0800523}
524
525bool DnsTlsSocket::query(uint16_t id, const Slice query) {
Ben Schwartz2187abe2019-01-10 14:30:46 -0500526 // Compose the entire message in a single buffer, so that it can be
527 // sent as a single TLS record.
528 std::vector<uint8_t> buf(query.size() + 4);
529 // Write 2-byte length
530 uint16_t len = query.size() + 2; // + 2 for the ID.
531 buf[0] = len >> 8;
532 buf[1] = len;
533 // Write 2-byte ID
534 buf[2] = id >> 8;
535 buf[3] = id;
536 // Copy body
537 std::memcpy(buf.data() + 4, query.base(), query.size());
538
539 mQueue.push(std::move(buf));
540 // Increment the mEventFd counter by 1.
Ben Schwartz62176fd2019-01-22 17:32:17 -0500541 return incrementEventFd(1);
542}
543
544void DnsTlsSocket::requestLoopShutdown() {
Bernie Innocenti97ee1092019-03-28 15:52:59 +0900545 if (mEventFd != -1) {
546 // Write a negative number to the eventfd. This triggers an immediate shutdown.
547 incrementEventFd(INT64_MIN);
548 }
Mike Yue93d9ae2020-08-25 19:09:51 +0800549 if (mShutdownEvent != -1) {
550 if (eventfd_write(mShutdownEvent.get(), INT64_MIN) == -1) {
551 PLOG(ERROR) << "Failed to write to mShutdownEvent";
552 }
553 }
Ben Schwartz62176fd2019-01-22 17:32:17 -0500554}
555
556bool DnsTlsSocket::incrementEventFd(const int64_t count) {
Bernie Innocenti97ee1092019-03-28 15:52:59 +0900557 if (mEventFd == -1) {
chenbruceaff85842019-05-31 15:46:42 +0800558 LOG(ERROR) << "eventfd is not initialized";
Ben Schwartz62176fd2019-01-22 17:32:17 -0500559 return false;
560 }
Bernie Innocenti97ee1092019-03-28 15:52:59 +0900561 ssize_t written = write(mEventFd.get(), &count, sizeof(count));
Ben Schwartz62176fd2019-01-22 17:32:17 -0500562 if (written != sizeof(count)) {
chenbruceaff85842019-05-31 15:46:42 +0800563 LOG(ERROR) << "Failed to increment eventfd by " << count;
Ben Schwartz62176fd2019-01-22 17:32:17 -0500564 return false;
565 }
566 return true;
Mike Yubab3daa2018-10-19 22:11:43 +0800567}
568
Mike Yu0c8e4522020-08-24 14:41:32 +0800569void DnsTlsSocket::transitionState(State from, State to) {
570 if (mState != from) {
571 LOG(WARNING) << "BUG: transitioning from an unexpected state " << static_cast<int>(mState)
572 << ", expect: from " << static_cast<int>(from) << " to "
573 << static_cast<int>(to);
574 }
575 mState = to;
576}
577
Mike Yubab3daa2018-10-19 22:11:43 +0800578// Read exactly len bytes into buffer or fail with an SSL error code
579int DnsTlsSocket::sslRead(const Slice buffer, bool wait) {
580 size_t remaining = buffer.size();
581 while (remaining > 0) {
582 int ret = SSL_read(mSsl.get(), buffer.limit() - remaining, remaining);
583 if (ret == 0) {
chenbruceaff85842019-05-31 15:46:42 +0800584 if (remaining < buffer.size())
585 LOG(WARNING) << "SSL closed with " << remaining << " of " << buffer.size()
586 << " bytes remaining";
Mike Yubab3daa2018-10-19 22:11:43 +0800587 return SSL_ERROR_ZERO_RETURN;
588 }
589
590 if (ret < 0) {
591 const int ssl_err = SSL_get_error(mSsl.get(), ret);
592 if (wait && ssl_err == SSL_ERROR_WANT_READ) {
Mike Yua772c202019-09-23 17:47:21 +0800593 if (int err = waitForReading(mSslFd.get()); err <= 0) {
594 PLOG(WARNING) << "Poll failed in sslRead, error " << err;
Mike Yubab3daa2018-10-19 22:11:43 +0800595 return SSL_ERROR_SYSCALL;
596 }
597 continue;
598 } else {
chenbruceaff85842019-05-31 15:46:42 +0800599 LOG(DEBUG) << "SSL_read error " << ssl_err;
Mike Yubab3daa2018-10-19 22:11:43 +0800600 return ssl_err;
601 }
602 }
603
604 remaining -= ret;
605 wait = true; // Once a read is started, try to finish.
606 }
607 return SSL_ERROR_NONE;
608}
609
Ben Schwartz2187abe2019-01-10 14:30:46 -0500610bool DnsTlsSocket::sendQuery(const std::vector<uint8_t>& buf) {
Mike Yubab3daa2018-10-19 22:11:43 +0800611 if (!sslWrite(netdutils::makeSlice(buf))) {
612 return false;
613 }
chenbruceaff85842019-05-31 15:46:42 +0800614 LOG(DEBUG) << mMark << " SSL_write complete";
Mike Yubab3daa2018-10-19 22:11:43 +0800615 return true;
616}
617
618bool DnsTlsSocket::readResponse() {
chenbruceaff85842019-05-31 15:46:42 +0800619 LOG(DEBUG) << "reading response";
Mike Yubab3daa2018-10-19 22:11:43 +0800620 uint8_t responseHeader[2];
621 int err = sslRead(Slice(responseHeader, 2), false);
622 if (err == SSL_ERROR_WANT_READ) {
chenbruceaff85842019-05-31 15:46:42 +0800623 LOG(DEBUG) << "Ignoring spurious wakeup from server";
Mike Yubab3daa2018-10-19 22:11:43 +0800624 return true;
625 }
626 if (err != SSL_ERROR_NONE) {
627 return false;
628 }
629 // Truncate responses larger than MAX_SIZE. This is safe because a DNS packet is
630 // always invalid when truncated, so the response will be treated as an error.
631 constexpr uint16_t MAX_SIZE = 8192;
632 const uint16_t responseSize = (responseHeader[0] << 8) | responseHeader[1];
chenbruceaff85842019-05-31 15:46:42 +0800633 LOG(DEBUG) << mMark << " Expecting response of size " << responseSize;
Mike Yubab3daa2018-10-19 22:11:43 +0800634 std::vector<uint8_t> response(std::min(responseSize, MAX_SIZE));
635 if (sslRead(netdutils::makeSlice(response), true) != SSL_ERROR_NONE) {
chenbruceaff85842019-05-31 15:46:42 +0800636 LOG(DEBUG) << mMark << " Failed to read " << response.size() << " bytes";
Mike Yubab3daa2018-10-19 22:11:43 +0800637 return false;
638 }
639 uint16_t remainingBytes = responseSize - response.size();
640 while (remainingBytes > 0) {
641 constexpr uint16_t CHUNK_SIZE = 2048;
642 std::vector<uint8_t> discard(std::min(remainingBytes, CHUNK_SIZE));
643 if (sslRead(netdutils::makeSlice(discard), true) != SSL_ERROR_NONE) {
chenbruceaff85842019-05-31 15:46:42 +0800644 LOG(DEBUG) << mMark << " Failed to discard " << discard.size() << " bytes";
Mike Yubab3daa2018-10-19 22:11:43 +0800645 return false;
646 }
647 remainingBytes -= discard.size();
648 }
chenbruceaff85842019-05-31 15:46:42 +0800649 LOG(DEBUG) << mMark << " SSL_read complete";
Mike Yubab3daa2018-10-19 22:11:43 +0800650
651 mObserver->onResponse(std::move(response));
652 return true;
653}
654
655} // end of namespace net
656} // end of namespace android