blob: 838886abbb0c043ecc3b871d02e1450c8872be4a [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
Chiachang Wang32372172019-07-06 13:54:18 +080035#include <Fwmark.h>
chenbruceaff85842019-05-31 15:46:42 +080036#include <android-base/logging.h>
Chiachang Wang32372172019-07-06 13:54:18 +080037#include <android-base/stringprintf.h>
Mike Yu04f1d482019-08-08 11:09:32 +080038#include <netdutils/SocketOption.h>
39#include <netdutils/ThreadUtil.h>
chenbruceaff85842019-05-31 15:46:42 +080040
Sehee Park2c118782019-05-07 13:02:45 +090041#include "private/android_filesystem_config.h" // AID_DNS
Mike Yubab3daa2018-10-19 22:11:43 +080042
waynema0e73c2e2019-07-31 15:04:08 +080043// NOTE: Inject CA certificate for internal testing -- do NOT enable in production builds
44#ifndef RESOLV_INJECT_CA_CERTIFICATE
45#define RESOLV_INJECT_CA_CERTIFICATE 0
46#endif
47
Mike Yubab3daa2018-10-19 22:11:43 +080048namespace android {
49
50using netdutils::enableSockopt;
51using netdutils::enableTcpKeepAlives;
52using netdutils::isOk;
Bernie Innocentiec4219b2019-01-30 11:16:36 +090053using netdutils::Slice;
Mike Yubab3daa2018-10-19 22:11:43 +080054using netdutils::Status;
55
56namespace net {
57namespace {
58
59constexpr const char kCaCertDir[] = "/system/etc/security/cacerts";
Mike Yubab3daa2018-10-19 22:11:43 +080060
61int waitForReading(int fd) {
62 struct pollfd fds = { .fd = fd, .events = POLLIN };
63 const int ret = TEMP_FAILURE_RETRY(poll(&fds, 1, -1));
64 return ret;
65}
66
67int waitForWriting(int fd) {
68 struct pollfd fds = { .fd = fd, .events = POLLOUT };
69 const int ret = TEMP_FAILURE_RETRY(poll(&fds, 1, -1));
70 return ret;
71}
72
Chiachang Wang32372172019-07-06 13:54:18 +080073std::string markToFwmarkString(unsigned mMark) {
74 Fwmark mark;
75 mark.intValue = mMark;
76 return android::base::StringPrintf("%d, %d, %d, %d, %d", mark.netId, mark.explicitlySelected,
77 mark.protectedFromVpn, mark.permission, mark.uidBillingDone);
78}
79
Mike Yubab3daa2018-10-19 22:11:43 +080080} // namespace
81
82Status DnsTlsSocket::tcpConnect() {
chenbruceaff85842019-05-31 15:46:42 +080083 LOG(DEBUG) << mMark << " connecting TCP socket";
Mike Yubab3daa2018-10-19 22:11:43 +080084 int type = SOCK_NONBLOCK | SOCK_CLOEXEC;
85 switch (mServer.protocol) {
86 case IPPROTO_TCP:
87 type |= SOCK_STREAM;
88 break;
89 default:
90 return Status(EPROTONOSUPPORT);
91 }
92
93 mSslFd.reset(socket(mServer.ss.ss_family, type, mServer.protocol));
94 if (mSslFd.get() == -1) {
chenbruceaff85842019-05-31 15:46:42 +080095 LOG(ERROR) << "Failed to create socket";
Mike Yubab3daa2018-10-19 22:11:43 +080096 return Status(errno);
97 }
98
Sehee Park2c118782019-05-07 13:02:45 +090099 if (fchown(mSslFd.get(), AID_DNS, -1) == -1) {
100 LOG(WARNING) << "Failed to chown socket: %s" << strerror(errno);
101 }
102
Mike Yubab3daa2018-10-19 22:11:43 +0800103 const socklen_t len = sizeof(mMark);
104 if (setsockopt(mSslFd.get(), SOL_SOCKET, SO_MARK, &mMark, len) == -1) {
chenbruceaff85842019-05-31 15:46:42 +0800105 LOG(ERROR) << "Failed to set socket mark";
Mike Yubab3daa2018-10-19 22:11:43 +0800106 mSslFd.reset();
107 return Status(errno);
108 }
109
110 const Status tfo = enableSockopt(mSslFd.get(), SOL_TCP, TCP_FASTOPEN_CONNECT);
111 if (!isOk(tfo) && tfo.code() != ENOPROTOOPT) {
chenbruceaff85842019-05-31 15:46:42 +0800112 LOG(WARNING) << "Failed to enable TFO: " << tfo.msg();
Mike Yubab3daa2018-10-19 22:11:43 +0800113 }
114
115 // Send 5 keepalives, 3 seconds apart, after 15 seconds of inactivity.
116 enableTcpKeepAlives(mSslFd.get(), 15U, 5U, 3U).ignoreError();
117
118 if (connect(mSslFd.get(), reinterpret_cast<const struct sockaddr *>(&mServer.ss),
119 sizeof(mServer.ss)) != 0 &&
120 errno != EINPROGRESS) {
chenbruceaff85842019-05-31 15:46:42 +0800121 LOG(DEBUG) << "Socket failed to connect";
Mike Yubab3daa2018-10-19 22:11:43 +0800122 mSslFd.reset();
123 return Status(errno);
124 }
125
126 return netdutils::status::ok;
127}
128
waynema0e73c2e2019-07-31 15:04:08 +0800129bool DnsTlsSocket::setTestCaCertificate() {
130 bssl::UniquePtr<BIO> bio(
131 BIO_new_mem_buf(mServer.certificate.data(), mServer.certificate.size()));
132 bssl::UniquePtr<X509> cert(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
133 if (!cert) {
134 LOG(ERROR) << "Failed to read cert";
Mike Yubab3daa2018-10-19 22:11:43 +0800135 return false;
136 }
waynema0e73c2e2019-07-31 15:04:08 +0800137
138 X509_STORE* cert_store = SSL_CTX_get_cert_store(mSslCtx.get());
139 if (!X509_STORE_add_cert(cert_store, cert.get())) {
140 LOG(ERROR) << "Failed to add cert";
Mike Yubab3daa2018-10-19 22:11:43 +0800141 return false;
142 }
143 return true;
144}
145
waynema0e73c2e2019-07-31 15:04:08 +0800146// TODO: Try to use static sSslCtx instead of mSslCtx
Mike Yubab3daa2018-10-19 22:11:43 +0800147bool DnsTlsSocket::initialize() {
waynema0e73c2e2019-07-31 15:04:08 +0800148 // This method is called every time when a new SSL connection is created.
149 // This lock only serves to help catch bugs in code that calls this method.
Mike Yubab3daa2018-10-19 22:11:43 +0800150 std::lock_guard guard(mLock);
151 if (mSslCtx) {
152 // This is a bug in the caller.
153 return false;
154 }
155 mSslCtx.reset(SSL_CTX_new(TLS_method()));
156 if (!mSslCtx) {
157 return false;
158 }
159
waynema0e73c2e2019-07-31 15:04:08 +0800160 // Load system CA certs from CAPath for hostname verification.
Mike Yubab3daa2018-10-19 22:11:43 +0800161 //
162 // For discussion of alternative, sustainable approaches see b/71909242.
waynema0e73c2e2019-07-31 15:04:08 +0800163 if (RESOLV_INJECT_CA_CERTIFICATE && !mServer.certificate.empty()) {
164 // Inject test CA certs from ResolverParamsParcel.caCertificate for internal testing.
165 LOG(WARNING) << "test CA certificate is valid";
166 if (!setTestCaCertificate()) {
167 LOG(ERROR) << "Failed to set test CA certificate";
168 return false;
169 }
170 } else {
171 if (SSL_CTX_load_verify_locations(mSslCtx.get(), nullptr, kCaCertDir) != 1) {
172 LOG(ERROR) << "Failed to load CA cert dir: " << kCaCertDir;
173 return false;
174 }
Mike Yubab3daa2018-10-19 22:11:43 +0800175 }
176
177 // Enable TLS false start
178 SSL_CTX_set_false_start_allowed_without_alpn(mSslCtx.get(), 1);
179 SSL_CTX_set_mode(mSslCtx.get(), SSL_MODE_ENABLE_FALSE_START);
180
181 // Enable session cache
182 mCache->prepareSslContext(mSslCtx.get());
183
184 // Connect
185 Status status = tcpConnect();
186 if (!status.ok()) {
187 return false;
188 }
189 mSsl = sslConnect(mSslFd.get());
190 if (!mSsl) {
191 return false;
192 }
Ben Schwartz2187abe2019-01-10 14:30:46 -0500193
194 mEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
Mike Yubab3daa2018-10-19 22:11:43 +0800195
196 // Start the I/O loop.
197 mLoopThread.reset(new std::thread(&DnsTlsSocket::loop, this));
198
199 return true;
200}
201
202bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {
203 if (!mSslCtx) {
chenbruceaff85842019-05-31 15:46:42 +0800204 LOG(ERROR) << "Internal error: context is null in sslConnect";
Mike Yubab3daa2018-10-19 22:11:43 +0800205 return nullptr;
206 }
207 if (!SSL_CTX_set_min_proto_version(mSslCtx.get(), TLS1_2_VERSION)) {
chenbruceaff85842019-05-31 15:46:42 +0800208 LOG(ERROR) << "Failed to set minimum TLS version";
Mike Yubab3daa2018-10-19 22:11:43 +0800209 return nullptr;
210 }
211
212 bssl::UniquePtr<SSL> ssl(SSL_new(mSslCtx.get()));
213 // This file descriptor is owned by mSslFd, so don't let libssl close it.
214 bssl::UniquePtr<BIO> bio(BIO_new_socket(fd, BIO_NOCLOSE));
215 SSL_set_bio(ssl.get(), bio.get(), bio.get());
216 bio.release();
217
218 if (!mCache->prepareSsl(ssl.get())) {
219 return nullptr;
220 }
221
222 if (!mServer.name.empty()) {
waynema0e73c2e2019-07-31 15:04:08 +0800223 LOG(VERBOSE) << "Checking DNS over TLS hostname = " << mServer.name.c_str();
Mike Yubab3daa2018-10-19 22:11:43 +0800224 if (SSL_set_tlsext_host_name(ssl.get(), mServer.name.c_str()) != 1) {
waynema0e73c2e2019-07-31 15:04:08 +0800225 LOG(ERROR) << "Failed to set SNI to " << mServer.name;
Mike Yubab3daa2018-10-19 22:11:43 +0800226 return nullptr;
227 }
228 X509_VERIFY_PARAM* param = SSL_get0_param(ssl.get());
229 if (X509_VERIFY_PARAM_set1_host(param, mServer.name.data(), mServer.name.size()) != 1) {
chenbruceaff85842019-05-31 15:46:42 +0800230 LOG(ERROR) << "Failed to set verify host param to " << mServer.name;
Mike Yubab3daa2018-10-19 22:11:43 +0800231 return nullptr;
232 }
233 // This will cause the handshake to fail if certificate verification fails.
234 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, nullptr);
235 }
236
237 bssl::UniquePtr<SSL_SESSION> session = mCache->getSession();
238 if (session) {
chenbruceaff85842019-05-31 15:46:42 +0800239 LOG(DEBUG) << "Setting session";
Mike Yubab3daa2018-10-19 22:11:43 +0800240 SSL_set_session(ssl.get(), session.get());
241 } else {
chenbruceaff85842019-05-31 15:46:42 +0800242 LOG(DEBUG) << "No session available";
Mike Yubab3daa2018-10-19 22:11:43 +0800243 }
244
245 for (;;) {
Chiachang Wang32372172019-07-06 13:54:18 +0800246 LOG(DEBUG) << " Calling SSL_connect with " << markToFwmarkString(mMark);
Mike Yubab3daa2018-10-19 22:11:43 +0800247 int ret = SSL_connect(ssl.get());
Chiachang Wang32372172019-07-06 13:54:18 +0800248 LOG(DEBUG) << " SSL_connect returned " << ret << " with " << markToFwmarkString(mMark);
Mike Yubab3daa2018-10-19 22:11:43 +0800249 if (ret == 1) break; // SSL handshake complete;
250
251 const int ssl_err = SSL_get_error(ssl.get(), ret);
252 switch (ssl_err) {
253 case SSL_ERROR_WANT_READ:
254 if (waitForReading(fd) != 1) {
Chiachang Wang32372172019-07-06 13:54:18 +0800255 PLOG(WARNING) << "SSL_connect read error, " << markToFwmarkString(mMark);
Mike Yubab3daa2018-10-19 22:11:43 +0800256 return nullptr;
257 }
258 break;
259 case SSL_ERROR_WANT_WRITE:
260 if (waitForWriting(fd) != 1) {
Chiachang Wang32372172019-07-06 13:54:18 +0800261 PLOG(WARNING) << "SSL_connect write error, " << markToFwmarkString(mMark);
Mike Yubab3daa2018-10-19 22:11:43 +0800262 return nullptr;
263 }
264 break;
265 default:
Chiachang Wang32372172019-07-06 13:54:18 +0800266 PLOG(WARNING) << "SSL_connect ssl error =" << ssl_err << ", "
267 << markToFwmarkString(mMark);
Mike Yubab3daa2018-10-19 22:11:43 +0800268 return nullptr;
269 }
270 }
271
chenbruceaff85842019-05-31 15:46:42 +0800272 LOG(DEBUG) << mMark << " handshake complete";
Mike Yubab3daa2018-10-19 22:11:43 +0800273
274 return ssl;
275}
276
277void DnsTlsSocket::sslDisconnect() {
278 if (mSsl) {
279 SSL_shutdown(mSsl.get());
280 mSsl.reset();
281 }
282 mSslFd.reset();
283}
284
285bool DnsTlsSocket::sslWrite(const Slice buffer) {
chenbruceaff85842019-05-31 15:46:42 +0800286 LOG(DEBUG) << mMark << " Writing " << buffer.size() << " bytes";
Mike Yubab3daa2018-10-19 22:11:43 +0800287 for (;;) {
288 int ret = SSL_write(mSsl.get(), buffer.base(), buffer.size());
289 if (ret == int(buffer.size())) break; // SSL write complete;
290
291 if (ret < 1) {
292 const int ssl_err = SSL_get_error(mSsl.get(), ret);
293 switch (ssl_err) {
294 case SSL_ERROR_WANT_WRITE:
295 if (waitForWriting(mSslFd.get()) != 1) {
chenbruceaff85842019-05-31 15:46:42 +0800296 LOG(DEBUG) << "SSL_write error";
Mike Yubab3daa2018-10-19 22:11:43 +0800297 return false;
298 }
299 continue;
300 case 0:
301 break; // SSL write complete;
302 default:
chenbruceaff85842019-05-31 15:46:42 +0800303 LOG(DEBUG) << "SSL_write error " << ssl_err;
Mike Yubab3daa2018-10-19 22:11:43 +0800304 return false;
305 }
306 }
307 }
chenbruceaff85842019-05-31 15:46:42 +0800308 LOG(DEBUG) << mMark << " Wrote " << buffer.size() << " bytes";
Mike Yubab3daa2018-10-19 22:11:43 +0800309 return true;
310}
311
312void DnsTlsSocket::loop() {
313 std::lock_guard guard(mLock);
Ben Schwartz2187abe2019-01-10 14:30:46 -0500314 std::deque<std::vector<uint8_t>> q;
Mike Yubab3daa2018-10-19 22:11:43 +0800315 const int timeout_msecs = DnsTlsSocket::kIdleTimeout.count() * 1000;
Mike Yu04f1d482019-08-08 11:09:32 +0800316
317 Fwmark mark;
318 mark.intValue = mMark;
319 netdutils::setThreadName(android::base::StringPrintf("TlsListen_%u", mark.netId).c_str());
Mike Yubab3daa2018-10-19 22:11:43 +0800320 while (true) {
321 // poll() ignores negative fds
322 struct pollfd fds[2] = { { .fd = -1 }, { .fd = -1 } };
Ben Schwartz2187abe2019-01-10 14:30:46 -0500323 enum { SSLFD = 0, EVENTFD = 1 };
Mike Yubab3daa2018-10-19 22:11:43 +0800324
325 // Always listen for a response from server.
326 fds[SSLFD].fd = mSslFd.get();
327 fds[SSLFD].events = POLLIN;
328
Ben Schwartz2187abe2019-01-10 14:30:46 -0500329 // If we have pending queries, wait for space to write one.
330 // Otherwise, listen for new queries.
Ben Schwartz62176fd2019-01-22 17:32:17 -0500331 // Note: This blocks the destructor until q is empty, i.e. until all pending
332 // queries are sent or have failed to send.
Ben Schwartz2187abe2019-01-10 14:30:46 -0500333 if (!q.empty()) {
Mike Yubab3daa2018-10-19 22:11:43 +0800334 fds[SSLFD].events |= POLLOUT;
335 } else {
Ben Schwartz2187abe2019-01-10 14:30:46 -0500336 fds[EVENTFD].fd = mEventFd.get();
337 fds[EVENTFD].events = POLLIN;
Mike Yubab3daa2018-10-19 22:11:43 +0800338 }
339
340 const int s = TEMP_FAILURE_RETRY(poll(fds, std::size(fds), timeout_msecs));
341 if (s == 0) {
chenbruceaff85842019-05-31 15:46:42 +0800342 LOG(DEBUG) << "Idle timeout";
Mike Yubab3daa2018-10-19 22:11:43 +0800343 break;
344 }
345 if (s < 0) {
chenbruceaff85842019-05-31 15:46:42 +0800346 LOG(DEBUG) << "Poll failed: " << errno;
Mike Yubab3daa2018-10-19 22:11:43 +0800347 break;
348 }
Ben Schwartz62176fd2019-01-22 17:32:17 -0500349 if (fds[SSLFD].revents & (POLLIN | POLLERR | POLLHUP)) {
Mike Yubab3daa2018-10-19 22:11:43 +0800350 if (!readResponse()) {
chenbruceaff85842019-05-31 15:46:42 +0800351 LOG(DEBUG) << "SSL remote close or read error.";
Mike Yubab3daa2018-10-19 22:11:43 +0800352 break;
353 }
354 }
Ben Schwartz2187abe2019-01-10 14:30:46 -0500355 if (fds[EVENTFD].revents & (POLLIN | POLLERR)) {
356 int64_t num_queries;
357 ssize_t res = read(mEventFd.get(), &num_queries, sizeof(num_queries));
Mike Yubab3daa2018-10-19 22:11:43 +0800358 if (res < 0) {
chenbruceaff85842019-05-31 15:46:42 +0800359 LOG(WARNING) << "Error during eventfd read";
Mike Yubab3daa2018-10-19 22:11:43 +0800360 break;
361 } else if (res == 0) {
chenbruceaff85842019-05-31 15:46:42 +0800362 LOG(WARNING) << "eventfd closed; disconnecting";
Mike Yubab3daa2018-10-19 22:11:43 +0800363 break;
Ben Schwartz2187abe2019-01-10 14:30:46 -0500364 } else if (res != sizeof(num_queries)) {
chenbruceaff85842019-05-31 15:46:42 +0800365 LOG(ERROR) << "Int size mismatch: " << res << " != " << sizeof(num_queries);
Ben Schwartz2187abe2019-01-10 14:30:46 -0500366 break;
Ben Schwartz62176fd2019-01-22 17:32:17 -0500367 } else if (num_queries < 0) {
chenbruceaff85842019-05-31 15:46:42 +0800368 LOG(DEBUG) << "Negative eventfd read indicates destructor-initiated shutdown";
Ben Schwartz2187abe2019-01-10 14:30:46 -0500369 break;
370 }
371 // Take ownership of all pending queries. (q is always empty here.)
372 mQueue.swap(q);
Mike Yubab3daa2018-10-19 22:11:43 +0800373 } else if (fds[SSLFD].revents & POLLOUT) {
Ben Schwartz2187abe2019-01-10 14:30:46 -0500374 // q cannot be empty here.
375 // Sending the entire queue here would risk a TCP flow control deadlock, so
376 // we only send a single query on each cycle of this loop.
377 // TODO: Coalesce multiple pending queries if there is enough space in the
378 // write buffer.
379 if (!sendQuery(q.front())) {
Mike Yubab3daa2018-10-19 22:11:43 +0800380 break;
381 }
Ben Schwartz2187abe2019-01-10 14:30:46 -0500382 q.pop_front();
Mike Yubab3daa2018-10-19 22:11:43 +0800383 }
384 }
chenbruceaff85842019-05-31 15:46:42 +0800385 LOG(DEBUG) << "Disconnecting";
Mike Yubab3daa2018-10-19 22:11:43 +0800386 sslDisconnect();
chenbruceaff85842019-05-31 15:46:42 +0800387 LOG(DEBUG) << "Calling onClosed";
Mike Yubab3daa2018-10-19 22:11:43 +0800388 mObserver->onClosed();
chenbruceaff85842019-05-31 15:46:42 +0800389 LOG(DEBUG) << "Ending loop";
Mike Yubab3daa2018-10-19 22:11:43 +0800390}
391
392DnsTlsSocket::~DnsTlsSocket() {
chenbruceaff85842019-05-31 15:46:42 +0800393 LOG(DEBUG) << "Destructor";
Mike Yubab3daa2018-10-19 22:11:43 +0800394 // This will trigger an orderly shutdown in loop().
Ben Schwartz62176fd2019-01-22 17:32:17 -0500395 requestLoopShutdown();
Mike Yubab3daa2018-10-19 22:11:43 +0800396 {
397 // Wait for the orderly shutdown to complete.
398 std::lock_guard guard(mLock);
399 if (mLoopThread && std::this_thread::get_id() == mLoopThread->get_id()) {
chenbruceaff85842019-05-31 15:46:42 +0800400 LOG(ERROR) << "Violation of re-entrance precondition";
Mike Yubab3daa2018-10-19 22:11:43 +0800401 return;
402 }
403 }
404 if (mLoopThread) {
chenbruceaff85842019-05-31 15:46:42 +0800405 LOG(DEBUG) << "Waiting for loop thread to terminate";
Mike Yubab3daa2018-10-19 22:11:43 +0800406 mLoopThread->join();
407 mLoopThread.reset();
408 }
chenbruceaff85842019-05-31 15:46:42 +0800409 LOG(DEBUG) << "Destructor completed";
Mike Yubab3daa2018-10-19 22:11:43 +0800410}
411
412bool DnsTlsSocket::query(uint16_t id, const Slice query) {
Ben Schwartz2187abe2019-01-10 14:30:46 -0500413 // Compose the entire message in a single buffer, so that it can be
414 // sent as a single TLS record.
415 std::vector<uint8_t> buf(query.size() + 4);
416 // Write 2-byte length
417 uint16_t len = query.size() + 2; // + 2 for the ID.
418 buf[0] = len >> 8;
419 buf[1] = len;
420 // Write 2-byte ID
421 buf[2] = id >> 8;
422 buf[3] = id;
423 // Copy body
424 std::memcpy(buf.data() + 4, query.base(), query.size());
425
426 mQueue.push(std::move(buf));
427 // Increment the mEventFd counter by 1.
Ben Schwartz62176fd2019-01-22 17:32:17 -0500428 return incrementEventFd(1);
429}
430
431void DnsTlsSocket::requestLoopShutdown() {
Bernie Innocenti97ee1092019-03-28 15:52:59 +0900432 if (mEventFd != -1) {
433 // Write a negative number to the eventfd. This triggers an immediate shutdown.
434 incrementEventFd(INT64_MIN);
435 }
Ben Schwartz62176fd2019-01-22 17:32:17 -0500436}
437
438bool DnsTlsSocket::incrementEventFd(const int64_t count) {
Bernie Innocenti97ee1092019-03-28 15:52:59 +0900439 if (mEventFd == -1) {
chenbruceaff85842019-05-31 15:46:42 +0800440 LOG(ERROR) << "eventfd is not initialized";
Ben Schwartz62176fd2019-01-22 17:32:17 -0500441 return false;
442 }
Bernie Innocenti97ee1092019-03-28 15:52:59 +0900443 ssize_t written = write(mEventFd.get(), &count, sizeof(count));
Ben Schwartz62176fd2019-01-22 17:32:17 -0500444 if (written != sizeof(count)) {
chenbruceaff85842019-05-31 15:46:42 +0800445 LOG(ERROR) << "Failed to increment eventfd by " << count;
Ben Schwartz62176fd2019-01-22 17:32:17 -0500446 return false;
447 }
448 return true;
Mike Yubab3daa2018-10-19 22:11:43 +0800449}
450
451// Read exactly len bytes into buffer or fail with an SSL error code
452int DnsTlsSocket::sslRead(const Slice buffer, bool wait) {
453 size_t remaining = buffer.size();
454 while (remaining > 0) {
455 int ret = SSL_read(mSsl.get(), buffer.limit() - remaining, remaining);
456 if (ret == 0) {
chenbruceaff85842019-05-31 15:46:42 +0800457 if (remaining < buffer.size())
458 LOG(WARNING) << "SSL closed with " << remaining << " of " << buffer.size()
459 << " bytes remaining";
Mike Yubab3daa2018-10-19 22:11:43 +0800460 return SSL_ERROR_ZERO_RETURN;
461 }
462
463 if (ret < 0) {
464 const int ssl_err = SSL_get_error(mSsl.get(), ret);
465 if (wait && ssl_err == SSL_ERROR_WANT_READ) {
466 if (waitForReading(mSslFd.get()) != 1) {
chenbruceaff85842019-05-31 15:46:42 +0800467 LOG(DEBUG) << "Poll failed in sslRead: " << errno;
Mike Yubab3daa2018-10-19 22:11:43 +0800468 return SSL_ERROR_SYSCALL;
469 }
470 continue;
471 } else {
chenbruceaff85842019-05-31 15:46:42 +0800472 LOG(DEBUG) << "SSL_read error " << ssl_err;
Mike Yubab3daa2018-10-19 22:11:43 +0800473 return ssl_err;
474 }
475 }
476
477 remaining -= ret;
478 wait = true; // Once a read is started, try to finish.
479 }
480 return SSL_ERROR_NONE;
481}
482
Ben Schwartz2187abe2019-01-10 14:30:46 -0500483bool DnsTlsSocket::sendQuery(const std::vector<uint8_t>& buf) {
Mike Yubab3daa2018-10-19 22:11:43 +0800484 if (!sslWrite(netdutils::makeSlice(buf))) {
485 return false;
486 }
chenbruceaff85842019-05-31 15:46:42 +0800487 LOG(DEBUG) << mMark << " SSL_write complete";
Mike Yubab3daa2018-10-19 22:11:43 +0800488 return true;
489}
490
491bool DnsTlsSocket::readResponse() {
chenbruceaff85842019-05-31 15:46:42 +0800492 LOG(DEBUG) << "reading response";
Mike Yubab3daa2018-10-19 22:11:43 +0800493 uint8_t responseHeader[2];
494 int err = sslRead(Slice(responseHeader, 2), false);
495 if (err == SSL_ERROR_WANT_READ) {
chenbruceaff85842019-05-31 15:46:42 +0800496 LOG(DEBUG) << "Ignoring spurious wakeup from server";
Mike Yubab3daa2018-10-19 22:11:43 +0800497 return true;
498 }
499 if (err != SSL_ERROR_NONE) {
500 return false;
501 }
502 // Truncate responses larger than MAX_SIZE. This is safe because a DNS packet is
503 // always invalid when truncated, so the response will be treated as an error.
504 constexpr uint16_t MAX_SIZE = 8192;
505 const uint16_t responseSize = (responseHeader[0] << 8) | responseHeader[1];
chenbruceaff85842019-05-31 15:46:42 +0800506 LOG(DEBUG) << mMark << " Expecting response of size " << responseSize;
Mike Yubab3daa2018-10-19 22:11:43 +0800507 std::vector<uint8_t> response(std::min(responseSize, MAX_SIZE));
508 if (sslRead(netdutils::makeSlice(response), true) != SSL_ERROR_NONE) {
chenbruceaff85842019-05-31 15:46:42 +0800509 LOG(DEBUG) << mMark << " Failed to read " << response.size() << " bytes";
Mike Yubab3daa2018-10-19 22:11:43 +0800510 return false;
511 }
512 uint16_t remainingBytes = responseSize - response.size();
513 while (remainingBytes > 0) {
514 constexpr uint16_t CHUNK_SIZE = 2048;
515 std::vector<uint8_t> discard(std::min(remainingBytes, CHUNK_SIZE));
516 if (sslRead(netdutils::makeSlice(discard), true) != SSL_ERROR_NONE) {
chenbruceaff85842019-05-31 15:46:42 +0800517 LOG(DEBUG) << mMark << " Failed to discard " << discard.size() << " bytes";
Mike Yubab3daa2018-10-19 22:11:43 +0800518 return false;
519 }
520 remainingBytes -= discard.size();
521 }
chenbruceaff85842019-05-31 15:46:42 +0800522 LOG(DEBUG) << mMark << " SSL_read complete";
Mike Yubab3daa2018-10-19 22:11:43 +0800523
524 mObserver->onResponse(std::move(response));
525 return true;
526}
527
528} // end of namespace net
529} // end of namespace android