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