blob: a63d221c925e8b0824e726281d4d5d922efa5788 [file] [log] [blame]
Ben Schwartzded1b702017-10-25 14:41:02 -04001/*
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
17#define LOG_TAG "DnsTlsSocket"
Ben Schwartz33860762017-10-25 14:41:02 -040018//#define LOG_NDEBUG 0
Ben Schwartzded1b702017-10-25 14:41:02 -040019
Bernie Innocentiad4e26e2019-01-30 11:16:36 +090020#include "DnsTlsSocket.h"
Ben Schwartzded1b702017-10-25 14:41:02 -040021
Ben Schwartzded1b702017-10-25 14:41:02 -040022#include <arpa/inet.h>
23#include <arpa/nameser.h>
24#include <errno.h>
Erik Klined1503072018-02-22 23:55:40 -080025#include <linux/tcp.h>
Ben Schwartzded1b702017-10-25 14:41:02 -040026#include <openssl/err.h>
Mike Yu5ae61542018-10-19 22:11:43 +080027#include <openssl/sha.h>
Ben Schwartzbfc8d992019-01-10 14:30:46 -050028#include <sys/eventfd.h>
Bernie Innocentif944a9c2018-05-18 20:50:25 +090029#include <sys/poll.h>
Ben Schwartzbfc8d992019-01-10 14:30:46 -050030#include <algorithm>
Ben Schwartzded1b702017-10-25 14:41:02 -040031
Bernie Innocentiad4e26e2019-01-30 11:16:36 +090032#include "DnsTlsSessionCache.h"
33#include "IDnsTlsSocketObserver.h"
Ben Schwartzded1b702017-10-25 14:41:02 -040034
35#include "log/log.h"
Erik Klined1503072018-02-22 23:55:40 -080036#include "netdutils/SocketOption.h"
Ben Schwartzded1b702017-10-25 14:41:02 -040037
Ben Schwartzded1b702017-10-25 14:41:02 -040038namespace android {
Ben Schwartzded1b702017-10-25 14:41:02 -040039
Erik Klined1503072018-02-22 23:55:40 -080040using netdutils::enableSockopt;
41using netdutils::enableTcpKeepAlives;
42using netdutils::isOk;
Bernie Innocentiad4e26e2019-01-30 11:16:36 +090043using netdutils::Slice;
Ben Schwartzded1b702017-10-25 14:41:02 -040044using netdutils::Status;
45
Erik Klined1503072018-02-22 23:55:40 -080046namespace net {
Ben Schwartzded1b702017-10-25 14:41:02 -040047namespace {
48
49constexpr const char kCaCertDir[] = "/system/etc/security/cacerts";
Mike Yu5ae61542018-10-19 22:11:43 +080050constexpr size_t SHA256_SIZE = SHA256_DIGEST_LENGTH;
Ben Schwartzded1b702017-10-25 14:41:02 -040051
52int waitForReading(int fd) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +090053 struct pollfd fds = { .fd = fd, .events = POLLIN };
54 const int ret = TEMP_FAILURE_RETRY(poll(&fds, 1, -1));
Ben Schwartzded1b702017-10-25 14:41:02 -040055 return ret;
56}
57
58int waitForWriting(int fd) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +090059 struct pollfd fds = { .fd = fd, .events = POLLOUT };
60 const int ret = TEMP_FAILURE_RETRY(poll(&fds, 1, -1));
Ben Schwartzded1b702017-10-25 14:41:02 -040061 return ret;
62}
63
64} // namespace
65
66Status DnsTlsSocket::tcpConnect() {
67 ALOGV("%u connecting TCP socket", mMark);
68 int type = SOCK_NONBLOCK | SOCK_CLOEXEC;
69 switch (mServer.protocol) {
70 case IPPROTO_TCP:
71 type |= SOCK_STREAM;
72 break;
73 default:
74 return Status(EPROTONOSUPPORT);
75 }
76
77 mSslFd.reset(socket(mServer.ss.ss_family, type, mServer.protocol));
78 if (mSslFd.get() == -1) {
79 ALOGE("Failed to create socket");
80 return Status(errno);
81 }
82
83 const socklen_t len = sizeof(mMark);
84 if (setsockopt(mSslFd.get(), SOL_SOCKET, SO_MARK, &mMark, len) == -1) {
85 ALOGE("Failed to set socket mark");
86 mSslFd.reset();
87 return Status(errno);
88 }
Erik Klined1503072018-02-22 23:55:40 -080089
90 const Status tfo = enableSockopt(mSslFd.get(), SOL_TCP, TCP_FASTOPEN_CONNECT);
91 if (!isOk(tfo) && tfo.code() != ENOPROTOOPT) {
92 ALOGI("Failed to enable TFO: %s", tfo.msg().c_str());
93 }
94
95 // Send 5 keepalives, 3 seconds apart, after 15 seconds of inactivity.
Bernie Innocenti6f9fd902018-10-11 20:50:23 +090096 enableTcpKeepAlives(mSslFd.get(), 15U, 5U, 3U).ignoreError();
Erik Klined1503072018-02-22 23:55:40 -080097
Ben Schwartzded1b702017-10-25 14:41:02 -040098 if (connect(mSslFd.get(), reinterpret_cast<const struct sockaddr *>(&mServer.ss),
99 sizeof(mServer.ss)) != 0 &&
100 errno != EINPROGRESS) {
101 ALOGV("Socket failed to connect");
102 mSslFd.reset();
103 return Status(errno);
104 }
105
106 return netdutils::status::ok;
107}
108
109bool getSPKIDigest(const X509* cert, std::vector<uint8_t>* out) {
Yi Kongbdfd57e2018-07-25 13:26:10 -0700110 int spki_len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), nullptr);
Ben Schwartzded1b702017-10-25 14:41:02 -0400111 unsigned char spki[spki_len];
112 unsigned char* temp = spki;
113 if (spki_len != i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp)) {
114 ALOGW("SPKI length mismatch");
115 return false;
116 }
117 out->resize(SHA256_SIZE);
118 unsigned int digest_len = 0;
Yi Kongbdfd57e2018-07-25 13:26:10 -0700119 int ret = EVP_Digest(spki, spki_len, out->data(), &digest_len, EVP_sha256(), nullptr);
Ben Schwartzded1b702017-10-25 14:41:02 -0400120 if (ret != 1) {
121 ALOGW("Server cert digest extraction failed");
122 return false;
123 }
124 if (digest_len != out->size()) {
125 ALOGW("Wrong digest length: %d", digest_len);
126 return false;
127 }
128 return true;
129}
130
131bool DnsTlsSocket::initialize() {
132 // This method should only be called once, at the beginning, so locking should be
133 // unnecessary. This lock only serves to help catch bugs in code that calls this method.
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900134 std::lock_guard guard(mLock);
Ben Schwartzded1b702017-10-25 14:41:02 -0400135 if (mSslCtx) {
136 // This is a bug in the caller.
137 return false;
138 }
139 mSslCtx.reset(SSL_CTX_new(TLS_method()));
140 if (!mSslCtx) {
141 return false;
142 }
143
144 // Load system CA certs for hostname verification.
145 //
146 // For discussion of alternative, sustainable approaches see b/71909242.
147 if (SSL_CTX_load_verify_locations(mSslCtx.get(), nullptr, kCaCertDir) != 1) {
148 ALOGE("Failed to load CA cert dir: %s", kCaCertDir);
149 return false;
150 }
151
152 // Enable TLS false start
153 SSL_CTX_set_false_start_allowed_without_alpn(mSslCtx.get(), 1);
154 SSL_CTX_set_mode(mSslCtx.get(), SSL_MODE_ENABLE_FALSE_START);
155
156 // Enable session cache
157 mCache->prepareSslContext(mSslCtx.get());
158
159 // Connect
160 Status status = tcpConnect();
161 if (!status.ok()) {
162 return false;
163 }
164 mSsl = sslConnect(mSslFd.get());
165 if (!mSsl) {
166 return false;
167 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500168
169 mEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
Ben Schwartz33860762017-10-25 14:41:02 -0400170
171 // Start the I/O loop.
172 mLoopThread.reset(new std::thread(&DnsTlsSocket::loop, this));
Ben Schwartzded1b702017-10-25 14:41:02 -0400173
174 return true;
175}
176
177bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {
178 if (!mSslCtx) {
179 ALOGE("Internal error: context is null in sslConnect");
180 return nullptr;
181 }
182 if (!SSL_CTX_set_min_proto_version(mSslCtx.get(), TLS1_2_VERSION)) {
183 ALOGE("Failed to set minimum TLS version");
184 return nullptr;
185 }
186
187 bssl::UniquePtr<SSL> ssl(SSL_new(mSslCtx.get()));
188 // This file descriptor is owned by mSslFd, so don't let libssl close it.
189 bssl::UniquePtr<BIO> bio(BIO_new_socket(fd, BIO_NOCLOSE));
190 SSL_set_bio(ssl.get(), bio.get(), bio.get());
191 bio.release();
192
193 if (!mCache->prepareSsl(ssl.get())) {
194 return nullptr;
195 }
196
197 if (!mServer.name.empty()) {
198 if (SSL_set_tlsext_host_name(ssl.get(), mServer.name.c_str()) != 1) {
199 ALOGE("Failed to set SNI to %s", mServer.name.c_str());
200 return nullptr;
201 }
202 X509_VERIFY_PARAM* param = SSL_get0_param(ssl.get());
Erik Klineefc13632018-03-22 11:19:02 -0700203 if (X509_VERIFY_PARAM_set1_host(param, mServer.name.data(), mServer.name.size()) != 1) {
204 ALOGE("Failed to set verify host param to %s", mServer.name.c_str());
205 return nullptr;
206 }
Ben Schwartzded1b702017-10-25 14:41:02 -0400207 // This will cause the handshake to fail if certificate verification fails.
208 SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, nullptr);
209 }
210
211 bssl::UniquePtr<SSL_SESSION> session = mCache->getSession();
212 if (session) {
213 ALOGV("Setting session");
214 SSL_set_session(ssl.get(), session.get());
215 } else {
216 ALOGV("No session available");
217 }
218
219 for (;;) {
220 ALOGV("%u Calling SSL_connect", mMark);
221 int ret = SSL_connect(ssl.get());
222 ALOGV("%u SSL_connect returned %d", mMark, ret);
223 if (ret == 1) break; // SSL handshake complete;
224
225 const int ssl_err = SSL_get_error(ssl.get(), ret);
226 switch (ssl_err) {
227 case SSL_ERROR_WANT_READ:
228 if (waitForReading(fd) != 1) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900229 ALOGW("SSL_connect read error: %d", errno);
Ben Schwartzded1b702017-10-25 14:41:02 -0400230 return nullptr;
231 }
232 break;
233 case SSL_ERROR_WANT_WRITE:
234 if (waitForWriting(fd) != 1) {
235 ALOGW("SSL_connect write error");
236 return nullptr;
237 }
238 break;
239 default:
240 ALOGW("SSL_connect error %d, errno=%d", ssl_err, errno);
241 return nullptr;
242 }
243 }
244
245 // TODO: Call SSL_shutdown before discarding the session if validation fails.
246 if (!mServer.fingerprints.empty()) {
247 ALOGV("Checking DNS over TLS fingerprint");
248
249 // We only care that the chain is internally self-consistent, not that
250 // it chains to a trusted root, so we can ignore some kinds of errors.
251 // TODO: Add a CA root verification mode that respects these errors.
252 int verify_result = SSL_get_verify_result(ssl.get());
253 switch (verify_result) {
254 case X509_V_OK:
255 case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
256 case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
257 case X509_V_ERR_CERT_UNTRUSTED:
258 break;
259 default:
260 ALOGW("Invalid certificate chain, error %d", verify_result);
261 return nullptr;
262 }
263
264 STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl.get());
265 if (!chain) {
266 ALOGW("Server has null certificate");
267 return nullptr;
268 }
269 // Chain and its contents are owned by ssl, so we don't need to free explicitly.
270 bool matched = false;
271 for (size_t i = 0; i < sk_X509_num(chain); ++i) {
272 // This appears to be O(N^2), but there doesn't seem to be a straightforward
273 // way to walk a STACK_OF nondestructively in linear time.
274 X509* cert = sk_X509_value(chain, i);
275 std::vector<uint8_t> digest;
276 if (!getSPKIDigest(cert, &digest)) {
277 ALOGE("Digest computation failed");
278 return nullptr;
279 }
280
281 if (mServer.fingerprints.count(digest) > 0) {
282 matched = true;
283 break;
284 }
285 }
286
287 if (!matched) {
288 ALOGW("No matching fingerprint");
289 return nullptr;
290 }
291
292 ALOGV("DNS over TLS fingerprint is correct");
293 }
294
295 ALOGV("%u handshake complete", mMark);
296
297 return ssl;
298}
299
300void DnsTlsSocket::sslDisconnect() {
301 if (mSsl) {
302 SSL_shutdown(mSsl.get());
303 mSsl.reset();
304 }
305 mSslFd.reset();
306}
307
308bool DnsTlsSocket::sslWrite(const Slice buffer) {
309 ALOGV("%u Writing %zu bytes", mMark, buffer.size());
310 for (;;) {
311 int ret = SSL_write(mSsl.get(), buffer.base(), buffer.size());
312 if (ret == int(buffer.size())) break; // SSL write complete;
313
314 if (ret < 1) {
315 const int ssl_err = SSL_get_error(mSsl.get(), ret);
316 switch (ssl_err) {
317 case SSL_ERROR_WANT_WRITE:
318 if (waitForWriting(mSslFd.get()) != 1) {
319 ALOGV("SSL_write error");
320 return false;
321 }
322 continue;
323 case 0:
324 break; // SSL write complete;
325 default:
326 ALOGV("SSL_write error %d", ssl_err);
327 return false;
328 }
329 }
330 }
331 ALOGV("%u Wrote %zu bytes", mMark, buffer.size());
332 return true;
333}
334
Ben Schwartz33860762017-10-25 14:41:02 -0400335void DnsTlsSocket::loop() {
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900336 std::lock_guard guard(mLock);
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500337 std::deque<std::vector<uint8_t>> q;
Ben Schwartz33860762017-10-25 14:41:02 -0400338
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900339 const int timeout_msecs = DnsTlsSocket::kIdleTimeout.count() * 1000;
Ben Schwartz33860762017-10-25 14:41:02 -0400340 while (true) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900341 // poll() ignores negative fds
342 struct pollfd fds[2] = { { .fd = -1 }, { .fd = -1 } };
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500343 enum { SSLFD = 0, EVENTFD = 1 };
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900344
Ben Schwartz33860762017-10-25 14:41:02 -0400345 // Always listen for a response from server.
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900346 fds[SSLFD].fd = mSslFd.get();
347 fds[SSLFD].events = POLLIN;
348
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500349 // If we have pending queries, wait for space to write one.
350 // Otherwise, listen for new queries.
Ben Schwartz18329ec2019-01-22 17:32:17 -0500351 // Note: This blocks the destructor until q is empty, i.e. until all pending
352 // queries are sent or have failed to send.
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500353 if (!q.empty()) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900354 fds[SSLFD].events |= POLLOUT;
Ben Schwartz33860762017-10-25 14:41:02 -0400355 } else {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500356 fds[EVENTFD].fd = mEventFd.get();
357 fds[EVENTFD].events = POLLIN;
Ben Schwartz33860762017-10-25 14:41:02 -0400358 }
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900359
Mike Yu5ae61542018-10-19 22:11:43 +0800360 const int s = TEMP_FAILURE_RETRY(poll(fds, std::size(fds), timeout_msecs));
Ben Schwartz33860762017-10-25 14:41:02 -0400361 if (s == 0) {
362 ALOGV("Idle timeout");
363 break;
364 }
365 if (s < 0) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900366 ALOGV("Poll failed: %d", errno);
Ben Schwartz33860762017-10-25 14:41:02 -0400367 break;
368 }
Ben Schwartz18329ec2019-01-22 17:32:17 -0500369 if (fds[SSLFD].revents & (POLLIN | POLLERR | POLLHUP)) {
Ben Schwartz33860762017-10-25 14:41:02 -0400370 if (!readResponse()) {
371 ALOGV("SSL remote close or read error.");
372 break;
373 }
374 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500375 if (fds[EVENTFD].revents & (POLLIN | POLLERR)) {
376 int64_t num_queries;
377 ssize_t res = read(mEventFd.get(), &num_queries, sizeof(num_queries));
Ben Schwartz33860762017-10-25 14:41:02 -0400378 if (res < 0) {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500379 ALOGW("Error during eventfd read");
Ben Schwartz33860762017-10-25 14:41:02 -0400380 break;
381 } else if (res == 0) {
Ben Schwartz18329ec2019-01-22 17:32:17 -0500382 ALOGW("eventfd closed; disconnecting");
Ben Schwartz33860762017-10-25 14:41:02 -0400383 break;
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500384 } else if (res != sizeof(num_queries)) {
385 ALOGE("Int size mismatch: %zd != %zu", res, sizeof(num_queries));
386 break;
Ben Schwartz18329ec2019-01-22 17:32:17 -0500387 } else if (num_queries < 0) {
388 ALOGV("Negative eventfd read indicates destructor-initiated shutdown");
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500389 break;
390 }
391 // Take ownership of all pending queries. (q is always empty here.)
392 mQueue.swap(q);
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900393 } else if (fds[SSLFD].revents & POLLOUT) {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500394 // q cannot be empty here.
395 // Sending the entire queue here would risk a TCP flow control deadlock, so
396 // we only send a single query on each cycle of this loop.
397 // TODO: Coalesce multiple pending queries if there is enough space in the
398 // write buffer.
399 if (!sendQuery(q.front())) {
Ben Schwartz33860762017-10-25 14:41:02 -0400400 break;
401 }
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500402 q.pop_front();
Ben Schwartz33860762017-10-25 14:41:02 -0400403 }
Ben Schwartzded1b702017-10-25 14:41:02 -0400404 }
Ben Schwartz33860762017-10-25 14:41:02 -0400405 ALOGV("Disconnecting");
406 sslDisconnect();
407 ALOGV("Calling onClosed");
408 mObserver->onClosed();
409 ALOGV("Ending loop");
Ben Schwartzded1b702017-10-25 14:41:02 -0400410}
411
Ben Schwartz33860762017-10-25 14:41:02 -0400412DnsTlsSocket::~DnsTlsSocket() {
413 ALOGV("Destructor");
414 // This will trigger an orderly shutdown in loop().
Ben Schwartz18329ec2019-01-22 17:32:17 -0500415 requestLoopShutdown();
Ben Schwartz33860762017-10-25 14:41:02 -0400416 {
417 // Wait for the orderly shutdown to complete.
Bernie Innocentiabf8a342018-08-10 15:17:16 +0900418 std::lock_guard guard(mLock);
Ben Schwartz33860762017-10-25 14:41:02 -0400419 if (mLoopThread && std::this_thread::get_id() == mLoopThread->get_id()) {
420 ALOGE("Violation of re-entrance precondition");
421 return;
422 }
423 }
424 if (mLoopThread) {
425 ALOGV("Waiting for loop thread to terminate");
426 mLoopThread->join();
427 mLoopThread.reset();
428 }
429 ALOGV("Destructor completed");
430}
431
432bool DnsTlsSocket::query(uint16_t id, const Slice query) {
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500433 // Compose the entire message in a single buffer, so that it can be
434 // sent as a single TLS record.
435 std::vector<uint8_t> buf(query.size() + 4);
436 // Write 2-byte length
437 uint16_t len = query.size() + 2; // + 2 for the ID.
438 buf[0] = len >> 8;
439 buf[1] = len;
440 // Write 2-byte ID
441 buf[2] = id >> 8;
442 buf[3] = id;
443 // Copy body
444 std::memcpy(buf.data() + 4, query.base(), query.size());
445
446 mQueue.push(std::move(buf));
447 // Increment the mEventFd counter by 1.
Ben Schwartz18329ec2019-01-22 17:32:17 -0500448 return incrementEventFd(1);
449}
450
451void DnsTlsSocket::requestLoopShutdown() {
Bernie Innocenti2549ecc2019-03-28 15:52:59 +0900452 if (mEventFd != -1) {
453 // Write a negative number to the eventfd. This triggers an immediate shutdown.
454 incrementEventFd(INT64_MIN);
455 }
Ben Schwartz18329ec2019-01-22 17:32:17 -0500456}
457
458bool DnsTlsSocket::incrementEventFd(const int64_t count) {
Bernie Innocenti2549ecc2019-03-28 15:52:59 +0900459 if (mEventFd == -1) {
460 ALOGE("eventfd is not initialized");
Ben Schwartz18329ec2019-01-22 17:32:17 -0500461 return false;
462 }
Bernie Innocenti2549ecc2019-03-28 15:52:59 +0900463 ssize_t written = write(mEventFd.get(), &count, sizeof(count));
Ben Schwartz18329ec2019-01-22 17:32:17 -0500464 if (written != sizeof(count)) {
465 ALOGE("Failed to increment eventfd by %" PRId64, count);
466 return false;
467 }
468 return true;
Ben Schwartz33860762017-10-25 14:41:02 -0400469}
470
471// Read exactly len bytes into buffer or fail with an SSL error code
472int DnsTlsSocket::sslRead(const Slice buffer, bool wait) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400473 size_t remaining = buffer.size();
474 while (remaining > 0) {
475 int ret = SSL_read(mSsl.get(), buffer.limit() - remaining, remaining);
476 if (ret == 0) {
477 ALOGW_IF(remaining < buffer.size(), "SSL closed with %zu of %zu bytes remaining",
478 remaining, buffer.size());
Ben Schwartz33860762017-10-25 14:41:02 -0400479 return SSL_ERROR_ZERO_RETURN;
Ben Schwartzded1b702017-10-25 14:41:02 -0400480 }
481
482 if (ret < 0) {
483 const int ssl_err = SSL_get_error(mSsl.get(), ret);
Ben Schwartz33860762017-10-25 14:41:02 -0400484 if (wait && ssl_err == SSL_ERROR_WANT_READ) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400485 if (waitForReading(mSslFd.get()) != 1) {
Bernie Innocentif944a9c2018-05-18 20:50:25 +0900486 ALOGV("Poll failed in sslRead: %d", errno);
Ben Schwartz33860762017-10-25 14:41:02 -0400487 return SSL_ERROR_SYSCALL;
Ben Schwartzded1b702017-10-25 14:41:02 -0400488 }
489 continue;
490 } else {
491 ALOGV("SSL_read error %d", ssl_err);
Ben Schwartz33860762017-10-25 14:41:02 -0400492 return ssl_err;
Ben Schwartzded1b702017-10-25 14:41:02 -0400493 }
494 }
495
496 remaining -= ret;
Ben Schwartz33860762017-10-25 14:41:02 -0400497 wait = true; // Once a read is started, try to finish.
Ben Schwartzded1b702017-10-25 14:41:02 -0400498 }
Ben Schwartz33860762017-10-25 14:41:02 -0400499 return SSL_ERROR_NONE;
Ben Schwartzded1b702017-10-25 14:41:02 -0400500}
501
Ben Schwartzbfc8d992019-01-10 14:30:46 -0500502bool DnsTlsSocket::sendQuery(const std::vector<uint8_t>& buf) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400503 if (!sslWrite(netdutils::makeSlice(buf))) {
504 return false;
505 }
506 ALOGV("%u SSL_write complete", mMark);
507 return true;
508}
509
Ben Schwartz33860762017-10-25 14:41:02 -0400510bool DnsTlsSocket::readResponse() {
Ben Schwartzded1b702017-10-25 14:41:02 -0400511 ALOGV("reading response");
512 uint8_t responseHeader[2];
Ben Schwartz33860762017-10-25 14:41:02 -0400513 int err = sslRead(Slice(responseHeader, 2), false);
514 if (err == SSL_ERROR_WANT_READ) {
515 ALOGV("Ignoring spurious wakeup from server");
516 return true;
517 }
518 if (err != SSL_ERROR_NONE) {
519 return false;
Ben Schwartzded1b702017-10-25 14:41:02 -0400520 }
521 // Truncate responses larger than MAX_SIZE. This is safe because a DNS packet is
522 // always invalid when truncated, so the response will be treated as an error.
523 constexpr uint16_t MAX_SIZE = 8192;
524 const uint16_t responseSize = (responseHeader[0] << 8) | responseHeader[1];
525 ALOGV("%u Expecting response of size %i", mMark, responseSize);
526 std::vector<uint8_t> response(std::min(responseSize, MAX_SIZE));
Ben Schwartz33860762017-10-25 14:41:02 -0400527 if (sslRead(netdutils::makeSlice(response), true) != SSL_ERROR_NONE) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400528 ALOGV("%u Failed to read %zu bytes", mMark, response.size());
Ben Schwartz33860762017-10-25 14:41:02 -0400529 return false;
Ben Schwartzded1b702017-10-25 14:41:02 -0400530 }
531 uint16_t remainingBytes = responseSize - response.size();
532 while (remainingBytes > 0) {
533 constexpr uint16_t CHUNK_SIZE = 2048;
534 std::vector<uint8_t> discard(std::min(remainingBytes, CHUNK_SIZE));
Ben Schwartz33860762017-10-25 14:41:02 -0400535 if (sslRead(netdutils::makeSlice(discard), true) != SSL_ERROR_NONE) {
Ben Schwartzded1b702017-10-25 14:41:02 -0400536 ALOGV("%u Failed to discard %zu bytes", mMark, discard.size());
Ben Schwartz33860762017-10-25 14:41:02 -0400537 return false;
Ben Schwartzded1b702017-10-25 14:41:02 -0400538 }
539 remainingBytes -= discard.size();
540 }
541 ALOGV("%u SSL_read complete", mMark);
542
Ben Schwartz33860762017-10-25 14:41:02 -0400543 mObserver->onResponse(std::move(response));
544 return true;
Ben Schwartzded1b702017-10-25 14:41:02 -0400545}
546
547} // end of namespace net
548} // end of namespace android