1 /*
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 "resolv"
18 
19 #include "DnsTlsSocket.h"
20 
21 #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>
27 #include <sys/eventfd.h>
28 #include <sys/poll.h>
29 #include <unistd.h>
30 #include <algorithm>
31 
32 #include "DnsTlsSessionCache.h"
33 #include "IDnsTlsSocketObserver.h"
34 
35 #include <android-base/logging.h>
36 #include <netdutils/SocketOption.h>
37 #include <netdutils/ThreadUtil.h>
38 
39 #include "Experiments.h"
40 #include "netd_resolv/resolv.h"
41 #include "private/android_filesystem_config.h"  // AID_DNS
42 #include "resolv_private.h"
43 
44 namespace android {
45 
46 using netdutils::enableSockopt;
47 using netdutils::enableTcpKeepAlives;
48 using netdutils::isOk;
49 using netdutils::setThreadName;
50 using netdutils::Slice;
51 using netdutils::Status;
52 
53 namespace net {
54 namespace {
55 
56 constexpr const char kCaCertDir[] = "/system/etc/security/cacerts";
57 
waitForReading(int fd,int timeoutMs=-1)58 int waitForReading(int fd, int timeoutMs = -1) {
59     pollfd fds = {.fd = fd, .events = POLLIN};
60     return TEMP_FAILURE_RETRY(poll(&fds, 1, timeoutMs));
61 }
62 
waitForWriting(int fd,int timeoutMs=-1)63 int waitForWriting(int fd, int timeoutMs = -1) {
64     pollfd fds = {.fd = fd, .events = POLLOUT};
65     return TEMP_FAILURE_RETRY(poll(&fds, 1, timeoutMs));
66 }
67 
68 }  // namespace
69 
tcpConnect()70 Status DnsTlsSocket::tcpConnect() {
71     if (mServer.protocol != IPPROTO_TCP) return Status(EPROTONOSUPPORT);
72 
73     LOG(INFO) << fmt::format("Connecting to {} with mark 0x{:x}", mServer.toString(), mMark);
74 
75     mSslFd.reset(socket(mServer.ss.ss_family, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0));
76     if (mSslFd.get() == -1) {
77         const int err = errno;
78         PLOG(ERROR) << "Failed to create socket, errno=" << err;
79         return Status(err);
80     }
81 
82     resolv_tag_socket(mSslFd.get(), AID_DNS, NET_CONTEXT_INVALID_PID);
83 
84     const socklen_t len = sizeof(mMark);
85     if (setsockopt(mSslFd.get(), SOL_SOCKET, SO_MARK, &mMark, len)) {
86         const int err = errno;
87         PLOG(ERROR) << "Failed to set socket mark, errno=" << err;
88         mSslFd.reset();
89         return Status(err);
90     }
91 
92     // Set TCP MSS to a suitably low value to be more reliable.
93     const int v = (mServer.ss.ss_family == AF_INET) ? 1212 : 1220;
94     if (setsockopt(mSslFd.get(), SOL_TCP, TCP_MAXSEG, &v, sizeof(v))) {
95         const int err = errno;
96         LOG(WARNING) << "Failed to set TCP_MAXSEG, errno=" << err;
97     }
98 
99     const Status tfo = enableSockopt(mSslFd.get(), SOL_TCP, TCP_FASTOPEN_CONNECT);
100     if (!isOk(tfo) && tfo.code() != ENOPROTOOPT) {
101         LOG(WARNING) << "Failed to enable TFO: " << tfo.msg();
102     }
103 
104     // Send 5 keepalives, 3 seconds apart, after 15 seconds of inactivity.
105     enableTcpKeepAlives(mSslFd.get(), 15U, 5U, 3U).ignoreError();
106 
107     if (connect(mSslFd.get(), reinterpret_cast<const struct sockaddr *>(&mServer.ss),
108                 sizeof(mServer.ss)) != 0 &&
109             errno != EINPROGRESS) {
110         const int err = errno;
111         PLOG(WARNING) << "Socket failed to connect, errno=" << err;
112         mSslFd.reset();
113         return Status(err);
114     }
115 
116     return netdutils::status::ok;
117 }
118 
setTestCaCertificate()119 bool DnsTlsSocket::setTestCaCertificate() {
120     bssl::UniquePtr<BIO> bio(
121             BIO_new_mem_buf(mServer.certificate.data(), mServer.certificate.size()));
122     bssl::UniquePtr<X509> cert(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));
123     if (!cert) {
124         LOG(ERROR) << "Failed to read cert";
125         return false;
126     }
127 
128     X509_STORE* cert_store = SSL_CTX_get_cert_store(mSslCtx.get());
129     if (!X509_STORE_add_cert(cert_store, cert.get())) {
130         LOG(ERROR) << "Failed to add cert";
131         return false;
132     }
133     return true;
134 }
135 
136 // TODO: Try to use static sSslCtx instead of mSslCtx
initialize()137 bool DnsTlsSocket::initialize() {
138     // This method is called every time when a new SSL connection is created.
139     // This lock only serves to help catch bugs in code that calls this method.
140     std::lock_guard guard(mLock);
141     if (mSslCtx) {
142         // This is a bug in the caller.
143         return false;
144     }
145     mSslCtx.reset(SSL_CTX_new(TLS_method()));
146     if (!mSslCtx) {
147         return false;
148     }
149 
150     // Load system CA certs from CAPath for hostname verification.
151     //
152     // For discussion of alternative, sustainable approaches see b/71909242.
153     if (!mServer.certificate.empty()) {
154         // Inject test CA certs from ResolverParamsParcel.caCertificate for INTERNAL TESTING ONLY.
155         // This is only allowed by DnsResolverService if the caller is AID_ROOT.
156         LOG(WARNING) << "Setting test CA certificate. This should never happen in production code.";
157         if (!setTestCaCertificate()) {
158             LOG(ERROR) << "Failed to set test CA certificate";
159             return false;
160         }
161     } else {
162         if (SSL_CTX_load_verify_locations(mSslCtx.get(), nullptr, kCaCertDir) != 1) {
163             LOG(ERROR) << "Failed to load CA cert dir: " << kCaCertDir;
164             return false;
165         }
166     }
167 
168     // Enable TLS false start
169     SSL_CTX_set_false_start_allowed_without_alpn(mSslCtx.get(), 1);
170     SSL_CTX_set_mode(mSslCtx.get(), SSL_MODE_ENABLE_FALSE_START);
171 
172     // Enable session cache
173     mCache->prepareSslContext(mSslCtx.get());
174 
175     mEventFd.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
176     mShutdownEvent.reset(eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC));
177 
178     const Experiments* const instance = Experiments::getInstance();
179     mConnectTimeoutMs = instance->getFlag("dot_connect_timeout_ms", kDotConnectTimeoutMs);
180     if (mConnectTimeoutMs < 1000) mConnectTimeoutMs = 1000;
181 
182     mAsyncHandshake = instance->getFlag("dot_async_handshake", 0);
183     LOG(DEBUG) << "DnsTlsSocket is initialized with { mConnectTimeoutMs: " << mConnectTimeoutMs
184                << ", mAsyncHandshake: " << mAsyncHandshake << " }";
185 
186     transitionState(State::UNINITIALIZED, State::INITIALIZED);
187 
188     return true;
189 }
190 
startHandshake()191 bool DnsTlsSocket::startHandshake() {
192     std::lock_guard guard(mLock);
193     if (mState != State::INITIALIZED) {
194         LOG(ERROR) << "Calling startHandshake in unexpected state " << static_cast<int>(mState);
195         return false;
196     }
197     transitionState(State::INITIALIZED, State::CONNECTING);
198 
199     if (!mAsyncHandshake) {
200         if (Status status = tcpConnect(); !status.ok()) {
201             transitionState(State::CONNECTING, State::WAIT_FOR_DELETE);
202             LOG(WARNING) << "TCP Handshake failed: " << status.code();
203             return false;
204         }
205         if (mSsl = sslConnect(mSslFd.get()); !mSsl) {
206             transitionState(State::CONNECTING, State::WAIT_FOR_DELETE);
207             LOG(WARNING) << "TLS Handshake failed";
208             return false;
209         }
210     }
211 
212     // Start the I/O loop.
213     mLoopThread.reset(new std::thread(&DnsTlsSocket::loop, this));
214 
215     return true;
216 }
217 
prepareForSslConnect(int fd)218 bssl::UniquePtr<SSL> DnsTlsSocket::prepareForSslConnect(int fd) {
219     if (!mSslCtx) {
220         LOG(ERROR) << "Internal error: context is null in sslConnect";
221         return nullptr;
222     }
223     if (!SSL_CTX_set_min_proto_version(mSslCtx.get(), TLS1_2_VERSION)) {
224         LOG(ERROR) << "Failed to set minimum TLS version";
225         return nullptr;
226     }
227 
228     bssl::UniquePtr<SSL> ssl(SSL_new(mSslCtx.get()));
229     // This file descriptor is owned by mSslFd, so don't let libssl close it.
230     bssl::UniquePtr<BIO> bio(BIO_new_socket(fd, BIO_NOCLOSE));
231     SSL_set_bio(ssl.get(), bio.get(), bio.get());
232     (void)bio.release();
233 
234     if (!mCache->prepareSsl(ssl.get())) {
235         return nullptr;
236     }
237 
238     if (!mServer.name.empty()) {
239         LOG(VERBOSE) << "Checking DNS over TLS hostname = " << mServer.name.c_str();
240         if (SSL_set_tlsext_host_name(ssl.get(), mServer.name.c_str()) != 1) {
241             LOG(ERROR) << "Failed to set SNI to " << mServer.name;
242             return nullptr;
243         }
244         X509_VERIFY_PARAM* param = SSL_get0_param(ssl.get());
245         if (X509_VERIFY_PARAM_set1_host(param, mServer.name.data(), mServer.name.size()) != 1) {
246             LOG(ERROR) << "Failed to set verify host param to " << mServer.name;
247             return nullptr;
248         }
249         // This will cause the handshake to fail if certificate verification fails.
250         SSL_set_verify(ssl.get(), SSL_VERIFY_PEER, nullptr);
251     }
252 
253     bssl::UniquePtr<SSL_SESSION> session = mCache->getSession();
254     if (session) {
255         LOG(DEBUG) << "Setting session";
256         SSL_set_session(ssl.get(), session.get());
257     } else {
258         LOG(DEBUG) << "No session available";
259     }
260 
261     return ssl;
262 }
263 
sslConnect(int fd)264 bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {
265     bssl::UniquePtr<SSL> ssl;
266     if (ssl = prepareForSslConnect(fd); !ssl) {
267         return nullptr;
268     }
269 
270     for (;;) {
271         LOG(DEBUG) << " Calling SSL_connect with mark 0x" << std::hex << mMark;
272         int ret = SSL_connect(ssl.get());
273         LOG(INFO) << " SSL_connect returned " << ret << " with mark 0x" << std::hex << mMark;
274         if (ret == 1) break;  // SSL handshake complete;
275 
276         const int ssl_err = SSL_get_error(ssl.get(), ret);
277         switch (ssl_err) {
278             case SSL_ERROR_WANT_READ:
279                 // SSL_ERROR_WANT_READ is returned because the application data has been sent during
280                 // the TCP connection handshake, the device is waiting for the SSL handshake reply
281                 // from the server.
282                 if (int err = waitForReading(fd, mConnectTimeoutMs); err <= 0) {
283                     PLOG(WARNING) << "SSL_connect read error " << err << ", mark 0x" << std::hex
284                                   << mMark;
285                     return nullptr;
286                 }
287                 break;
288             case SSL_ERROR_WANT_WRITE:
289                 // If no application data is sent during the TCP connection handshake, the
290                 // device is waiting for the connection established to perform SSL handshake.
291                 if (int err = waitForWriting(fd, mConnectTimeoutMs); err <= 0) {
292                     PLOG(WARNING) << "SSL_connect write error " << err << ", mark 0x" << std::hex
293                                   << mMark;
294                     return nullptr;
295                 }
296                 break;
297             default:
298                 PLOG(WARNING) << "SSL_connect ssl error =" << ssl_err << ", mark 0x" << std::hex
299                               << mMark;
300                 return nullptr;
301         }
302     }
303 
304     LOG(DEBUG) << mMark << " handshake complete";
305 
306     return ssl;
307 }
308 
sslConnectV2(int fd)309 bssl::UniquePtr<SSL> DnsTlsSocket::sslConnectV2(int fd) {
310     bssl::UniquePtr<SSL> ssl;
311     if (ssl = prepareForSslConnect(fd); !ssl) {
312         return nullptr;
313     }
314 
315     for (;;) {
316         LOG(DEBUG) << " Calling SSL_connect with mark 0x" << std::hex << mMark;
317         int ret = SSL_connect(ssl.get());
318         LOG(INFO) << " SSL_connect returned " << ret << " with mark 0x" << std::hex << mMark;
319         if (ret == 1) break;  // SSL handshake complete;
320 
321         enum { SSLFD = 0, EVENTFD = 1 };
322         pollfd fds[2] = {
323                 {.fd = mSslFd.get(), .events = 0},
324                 {.fd = mShutdownEvent.get(), .events = POLLIN},
325         };
326 
327         const int ssl_err = SSL_get_error(ssl.get(), ret);
328         switch (ssl_err) {
329             case SSL_ERROR_WANT_READ:
330                 fds[SSLFD].events = POLLIN;
331                 break;
332             case SSL_ERROR_WANT_WRITE:
333                 fds[SSLFD].events = POLLOUT;
334                 break;
335             default:
336                 PLOG(WARNING) << "SSL_connect ssl error =" << ssl_err << ", mark 0x" << std::hex
337                               << mMark;
338                 return nullptr;
339         }
340 
341         int n = TEMP_FAILURE_RETRY(poll(fds, std::size(fds), mConnectTimeoutMs));
342         if (n <= 0) {
343             PLOG(WARNING) << ((n == 0) ? "handshake timeout" : "Poll failed");
344             return nullptr;
345         }
346 
347         if (fds[EVENTFD].revents & (POLLIN | POLLERR)) {
348             LOG(WARNING) << "Got shutdown request during handshake";
349             return nullptr;
350         }
351         if (fds[SSLFD].revents & POLLERR) {
352             LOG(WARNING) << "Got POLLERR on SSLFD during handshake";
353             return nullptr;
354         }
355     }
356 
357     LOG(DEBUG) << mMark << " handshake complete";
358 
359     return ssl;
360 }
361 
sslDisconnect()362 void DnsTlsSocket::sslDisconnect() {
363     if (mSsl) {
364         SSL_shutdown(mSsl.get());
365         mSsl.reset();
366     }
367     mSslFd.reset();
368 }
369 
sslWrite(const Slice buffer)370 bool DnsTlsSocket::sslWrite(const Slice buffer) {
371     LOG(DEBUG) << mMark << " Writing " << buffer.size() << " bytes";
372     for (;;) {
373         int ret = SSL_write(mSsl.get(), buffer.base(), buffer.size());
374         if (ret == int(buffer.size())) break;  // SSL write complete;
375 
376         if (ret < 1) {
377             const int ssl_err = SSL_get_error(mSsl.get(), ret);
378             switch (ssl_err) {
379                 case SSL_ERROR_WANT_WRITE:
380                     if (int err = waitForWriting(mSslFd.get()); err <= 0) {
381                         PLOG(WARNING) << "Poll failed in sslWrite, error " << err;
382                         return false;
383                     }
384                     continue;
385                 case 0:
386                     break;  // SSL write complete;
387                 default:
388                     LOG(DEBUG) << "SSL_write error " << ssl_err;
389                     return false;
390             }
391         }
392     }
393     LOG(DEBUG) << mMark << " Wrote " << buffer.size() << " bytes";
394     return true;
395 }
396 
loop()397 void DnsTlsSocket::loop() {
398     std::lock_guard guard(mLock);
399     std::deque<std::vector<uint8_t>> q;
400     const int timeout_msecs = DnsTlsSocket::kIdleTimeout.count() * 1000;
401 
402     setThreadName(fmt::format("TlsListen_{}", mMark & 0xffff));
403 
404     if (mAsyncHandshake) {
405         if (Status status = tcpConnect(); !status.ok()) {
406             LOG(WARNING) << "TCP Handshake failed: " << status.code();
407             mObserver->onClosed();
408             transitionState(State::CONNECTING, State::WAIT_FOR_DELETE);
409             return;
410         }
411         if (mSsl = sslConnectV2(mSslFd.get()); !mSsl) {
412             LOG(WARNING) << "TLS Handshake failed";
413             mObserver->onClosed();
414             transitionState(State::CONNECTING, State::WAIT_FOR_DELETE);
415             return;
416         }
417         LOG(DEBUG) << "Handshaking succeeded";
418     }
419 
420     transitionState(State::CONNECTING, State::CONNECTED);
421 
422     while (true) {
423         // poll() ignores negative fds
424         struct pollfd fds[2] = { { .fd = -1 }, { .fd = -1 } };
425         enum { SSLFD = 0, EVENTFD = 1 };
426 
427         // Always listen for a response from server.
428         fds[SSLFD].fd = mSslFd.get();
429         fds[SSLFD].events = POLLIN;
430 
431         // If we have pending queries, wait for space to write one.
432         // Otherwise, listen for new queries.
433         // Note: This blocks the destructor until q is empty, i.e. until all pending
434         // queries are sent or have failed to send.
435         if (!q.empty()) {
436             fds[SSLFD].events |= POLLOUT;
437         } else {
438             fds[EVENTFD].fd = mEventFd.get();
439             fds[EVENTFD].events = POLLIN;
440         }
441 
442         const int s = TEMP_FAILURE_RETRY(poll(fds, std::size(fds), timeout_msecs));
443         if (s == 0) {
444             LOG(DEBUG) << "Idle timeout";
445             break;
446         }
447         if (s < 0) {
448             PLOG(WARNING) << "Poll failed";
449             break;
450         }
451         if (fds[SSLFD].revents & (POLLIN | POLLERR | POLLHUP)) {
452             bool readFailed = false;
453 
454             // readResponse() only reads one DNS (and consumes exact bytes) from ssl.
455             // Keep doing so until ssl has no pending data.
456             // TODO: readResponse() can block until it reads a complete DNS response. Consider
457             // refactoring it to not get blocked in any case.
458             do {
459                 if (!readResponse()) {
460                     LOG(INFO) << "SSL remote close or read error.";
461                     readFailed = true;
462                 }
463             } while (SSL_pending(mSsl.get()) > 0 && !readFailed);
464 
465             if (readFailed) {
466                 break;
467             }
468         }
469         if (fds[EVENTFD].revents & (POLLIN | POLLERR)) {
470             int64_t num_queries;
471             ssize_t res = read(mEventFd.get(), &num_queries, sizeof(num_queries));
472             if (res < 0) {
473                 LOG(WARNING) << "Error during eventfd read";
474                 break;
475             } else if (res == 0) {
476                 LOG(WARNING) << "eventfd closed; disconnecting";
477                 break;
478             } else if (res != sizeof(num_queries)) {
479                 LOG(ERROR) << "Int size mismatch: " << res << " != " << sizeof(num_queries);
480                 break;
481             } else if (num_queries < 0) {
482                 LOG(DEBUG) << "Negative eventfd read indicates destructor-initiated shutdown";
483                 break;
484             }
485             // Take ownership of all pending queries.  (q is always empty here.)
486             mQueue.swap(q);
487         } else if (fds[SSLFD].revents & POLLOUT) {
488             // q cannot be empty here.
489             // Sending the entire queue here would risk a TCP flow control deadlock, so
490             // we only send a single query on each cycle of this loop.
491             // TODO: Coalesce multiple pending queries if there is enough space in the
492             // write buffer.
493             if (!sendQuery(q.front())) {
494                 break;
495             }
496             q.pop_front();
497         }
498     }
499     LOG(INFO) << fmt::format("Disconnecting {}, mark 0x{:x}", mServer.toString(), mMark);
500     sslDisconnect();
501     LOG(DEBUG) << "Calling onClosed";
502     mObserver->onClosed();
503     transitionState(State::CONNECTED, State::WAIT_FOR_DELETE);
504     LOG(DEBUG) << "Ending loop";
505 }
506 
~DnsTlsSocket()507 DnsTlsSocket::~DnsTlsSocket() {
508     LOG(DEBUG) << "Destructor";
509     // This will trigger an orderly shutdown in loop().
510     requestLoopShutdown();
511     {
512         // Wait for the orderly shutdown to complete.
513         std::lock_guard guard(mLock);
514         if (mLoopThread && std::this_thread::get_id() == mLoopThread->get_id()) {
515             LOG(ERROR) << "Violation of re-entrance precondition";
516             return;
517         }
518     }
519     if (mLoopThread) {
520         LOG(DEBUG) << "Waiting for loop thread to terminate";
521         mLoopThread->join();
522         mLoopThread.reset();
523     }
524     LOG(DEBUG) << "Destructor completed";
525 }
526 
query(uint16_t id,const Slice query)527 bool DnsTlsSocket::query(uint16_t id, const Slice query) {
528     // Compose the entire message in a single buffer, so that it can be
529     // sent as a single TLS record.
530     std::vector<uint8_t> buf(query.size() + 4);
531     // Write 2-byte length
532     uint16_t len = query.size() + 2;  // + 2 for the ID.
533     buf[0] = len >> 8;
534     buf[1] = len;
535     // Write 2-byte ID
536     buf[2] = id >> 8;
537     buf[3] = id;
538     // Copy body
539     std::memcpy(buf.data() + 4, query.base(), query.size());
540 
541     mQueue.push(std::move(buf));
542     // Increment the mEventFd counter by 1.
543     return incrementEventFd(1);
544 }
545 
requestLoopShutdown()546 void DnsTlsSocket::requestLoopShutdown() {
547     if (mEventFd != -1) {
548         // Write a negative number to the eventfd.  This triggers an immediate shutdown.
549         incrementEventFd(INT64_MIN);
550     }
551     if (mShutdownEvent != -1) {
552         if (eventfd_write(mShutdownEvent.get(), INT64_MIN) == -1) {
553             PLOG(ERROR) << "Failed to write to mShutdownEvent";
554         }
555     }
556 }
557 
incrementEventFd(const int64_t count)558 bool DnsTlsSocket::incrementEventFd(const int64_t count) {
559     if (mEventFd == -1) {
560         LOG(ERROR) << "eventfd is not initialized";
561         return false;
562     }
563     ssize_t written = write(mEventFd.get(), &count, sizeof(count));
564     if (written != sizeof(count)) {
565         LOG(ERROR) << "Failed to increment eventfd by " << count;
566         return false;
567     }
568     return true;
569 }
570 
transitionState(State from,State to)571 void DnsTlsSocket::transitionState(State from, State to) {
572     if (mState != from) {
573         LOG(WARNING) << "BUG: transitioning from an unexpected state " << static_cast<int>(mState)
574                      << ", expect: from " << static_cast<int>(from) << " to "
575                      << static_cast<int>(to);
576     }
577     mState = to;
578 }
579 
580 // Read exactly len bytes into buffer or fail with an SSL error code
sslRead(const Slice buffer,bool wait)581 int DnsTlsSocket::sslRead(const Slice buffer, bool wait) {
582     size_t remaining = buffer.size();
583     while (remaining > 0) {
584         int ret = SSL_read(mSsl.get(), buffer.limit() - remaining, remaining);
585         if (ret == 0) {
586             if (remaining < buffer.size())
587                 LOG(WARNING) << "SSL closed with " << remaining << " of " << buffer.size()
588                              << " bytes remaining";
589             return SSL_ERROR_ZERO_RETURN;
590         }
591 
592         if (ret < 0) {
593             const int ssl_err = SSL_get_error(mSsl.get(), ret);
594             if (wait && ssl_err == SSL_ERROR_WANT_READ) {
595                 if (int err = waitForReading(mSslFd.get()); err <= 0) {
596                     PLOG(WARNING) << "Poll failed in sslRead, error " << err;
597                     return SSL_ERROR_SYSCALL;
598                 }
599                 continue;
600             } else {
601                 LOG(DEBUG) << "SSL_read error " << ssl_err;
602                 return ssl_err;
603             }
604         }
605 
606         remaining -= ret;
607         wait = true;  // Once a read is started, try to finish.
608     }
609     return SSL_ERROR_NONE;
610 }
611 
sendQuery(const std::vector<uint8_t> & buf)612 bool DnsTlsSocket::sendQuery(const std::vector<uint8_t>& buf) {
613     if (!sslWrite(netdutils::makeSlice(buf))) {
614         return false;
615     }
616     LOG(DEBUG) << mMark << " SSL_write complete";
617     return true;
618 }
619 
readResponse()620 bool DnsTlsSocket::readResponse() {
621     LOG(DEBUG) << "reading response";
622     uint8_t responseHeader[2];
623     int err = sslRead(Slice(responseHeader, 2), false);
624     if (err == SSL_ERROR_WANT_READ) {
625         LOG(DEBUG) << "Ignoring spurious wakeup from server";
626         return true;
627     }
628     if (err != SSL_ERROR_NONE) {
629         return false;
630     }
631     // Truncate responses larger than MAX_SIZE.  This is safe because a DNS packet is
632     // always invalid when truncated, so the response will be treated as an error.
633     constexpr uint16_t MAX_SIZE = 8192;
634     const uint16_t responseSize = (responseHeader[0] << 8) | responseHeader[1];
635     LOG(DEBUG) << mMark << " Expecting response of size " << responseSize;
636     std::vector<uint8_t> response(std::min(responseSize, MAX_SIZE));
637     if (sslRead(netdutils::makeSlice(response), true) != SSL_ERROR_NONE) {
638         LOG(DEBUG) << mMark << " Failed to read " << response.size() << " bytes";
639         return false;
640     }
641     uint16_t remainingBytes = responseSize - response.size();
642     while (remainingBytes > 0) {
643         constexpr uint16_t CHUNK_SIZE = 2048;
644         std::vector<uint8_t> discard(std::min(remainingBytes, CHUNK_SIZE));
645         if (sslRead(netdutils::makeSlice(discard), true) != SSL_ERROR_NONE) {
646             LOG(DEBUG) << mMark << " Failed to discard " << discard.size() << " bytes";
647             return false;
648         }
649         remainingBytes -= discard.size();
650     }
651     LOG(DEBUG) << mMark << " SSL_read complete";
652 
653     mObserver->onResponse(std::move(response));
654     return true;
655 }
656 
657 }  // end of namespace net
658 }  // end of namespace android
659