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