Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit aff8584c authored by chenbruce's avatar chenbruce
Browse files

Finish removing ALOG() from system/netd/resolv/

Change all the debug function to LOG(X) from ALOGx() for resolver module.

Bug: 134119725
Test: built, flashed, booted
Test: Checking logs for different level.
Test: Example:
Test: adb shell service call dnsresolver 10 i32 1 for DNS_RESOLVER_LOG_DEBUG
Change-Id: I20f8e284ffaf1cbeef8118b052686d3fa6fb8302
parent 0f20cddf
Loading
Loading
Loading
Loading
+11 −12
Original line number Original line Diff line number Diff line
@@ -19,7 +19,7 @@


#include "Dns64Configuration.h"
#include "Dns64Configuration.h"


#include <log/log.h>
#include <android-base/logging.h>
#include <netdb.h>
#include <netdb.h>
#include <thread>
#include <thread>
#include <utility>
#include <utility>
@@ -141,7 +141,8 @@ void Dns64Configuration::dump(DumpWriter& dw, unsigned netId) {
// currently assumes the DNS64 prefix is a /96.
// currently assumes the DNS64 prefix is a /96.
bool Dns64Configuration::doRfc7050PrefixDiscovery(const android_net_context& netcontext,
bool Dns64Configuration::doRfc7050PrefixDiscovery(const android_net_context& netcontext,
                                                  Dns64Config* cfg) {
                                                  Dns64Config* cfg) {
    ALOGW("(%u, %u) Detecting NAT64 prefix from DNS...", cfg->netId, cfg->discoveryId);
    LOG(WARNING) << "(" << cfg->netId << ", " << cfg->discoveryId
                 << ") Detecting NAT64 prefix from DNS...";


    const struct addrinfo hints = {
    const struct addrinfo hints = {
            .ai_family = AF_INET6,
            .ai_family = AF_INET6,
@@ -156,8 +157,8 @@ bool Dns64Configuration::doRfc7050PrefixDiscovery(const android_net_context& net
            android_getaddrinfofornetcontext(kIPv4OnlyHost, nullptr, &hints, &netcontext, &res);
            android_getaddrinfofornetcontext(kIPv4OnlyHost, nullptr, &hints, &netcontext, &res);
    ScopedAddrinfo result(res);
    ScopedAddrinfo result(res);
    if (status != 0) {
    if (status != 0) {
        ALOGW("(%u, %u) plat_prefix/dns(%s) status = %d/%s", cfg->netId, cfg->discoveryId,
        LOG(WARNING) << "(" << cfg->netId << ", " << cfg->discoveryId << ") plat_prefix/dns("
              kIPv4OnlyHost, status, gai_strerror(status));
                     << kIPv4OnlyHost << ") status = " << status << "/" << gai_strerror(status);
        return false;
        return false;
    }
    }


@@ -170,17 +171,15 @@ bool Dns64Configuration::doRfc7050PrefixDiscovery(const android_net_context& net
    //
    //
    // TODO: Consider remedying this.
    // TODO: Consider remedying this.
    if (result->ai_family != AF_INET6) {
    if (result->ai_family != AF_INET6) {
        ALOGW("(%u, %u) plat_prefix/unexpected address family: %d", cfg->netId, cfg->discoveryId,
        LOG(WARNING) << "(" << cfg->netId << ", " << cfg->discoveryId
              result->ai_family);
                     << ") plat_prefix/unexpected address family: " << result->ai_family;
        return false;
        return false;
    }
    }
    const IPAddress ipv6(reinterpret_cast<sockaddr_in6*>(result->ai_addr)->sin6_addr);
    const IPAddress ipv6(reinterpret_cast<sockaddr_in6*>(result->ai_addr)->sin6_addr);
    // Only /96 DNS64 prefixes are supported at this time.
    // Only /96 DNS64 prefixes are supported at this time.
    cfg->prefix64 = IPPrefix(ipv6, 96);
    cfg->prefix64 = IPPrefix(ipv6, 96);

    LOG(WARNING) << "(" << cfg->netId << ", " << cfg->discoveryId << ") Detected NAT64 prefix "
    ALOGW("(%u, %u) Detected NAT64 prefix %s", cfg->netId, cfg->discoveryId,
                 << cfg->prefix64.toString();
          cfg->prefix64.toString().c_str());

    return true;
    return true;
}
}


@@ -194,8 +193,8 @@ bool Dns64Configuration::isDiscoveryInProgress(const Dns64Config& cfg) const REQ


bool Dns64Configuration::reportNat64PrefixStatus(unsigned netId, bool added, const IPPrefix& pfx) {
bool Dns64Configuration::reportNat64PrefixStatus(unsigned netId, bool added, const IPPrefix& pfx) {
    if (pfx.ip().family() != AF_INET6 || pfx.ip().scope_id() != 0) {
    if (pfx.ip().family() != AF_INET6 || pfx.ip().scope_id() != 0) {
        ALOGW("Abort to send NAT64 prefix notification. Unexpected NAT64 prefix (%u, %d, %s).",
        LOG(WARNING) << "Abort to send NAT64 prefix notification. Unexpected NAT64 prefix ("
              netId, added, pfx.toString().c_str());
                     << netId << ", " << added << ", " << pfx.toString() << ").";
        return false;
        return false;
    }
    }
    Nat64PrefixInfo args = {netId, added, pfx.ip().toString(), (uint8_t)pfx.length()};
    Nat64PrefixInfo args = {netId, added, pfx.ip().toString(), (uint8_t)pfx.length()};
+7 −8
Original line number Original line Diff line number Diff line
@@ -15,12 +15,11 @@
 */
 */


#define LOG_TAG "resolv"
#define LOG_TAG "resolv"
//#define LOG_NDEBUG 0


#include "DnsTlsDispatcher.h"
#include "DnsTlsDispatcher.h"
#include "DnsTlsSocketFactory.h"
#include "DnsTlsSocketFactory.h"


#include "log/log.h"
#include <android-base/logging.h>


namespace android {
namespace android {
namespace net {
namespace net {
@@ -87,7 +86,7 @@ DnsTlsTransport::Response DnsTlsDispatcher::query(
        const Slice query, const Slice ans, int *resplen) {
        const Slice query, const Slice ans, int *resplen) {
    const std::list<DnsTlsServer> orderedServers(getOrderedServerList(tlsServers, mark));
    const std::list<DnsTlsServer> orderedServers(getOrderedServerList(tlsServers, mark));


    if (orderedServers.empty()) ALOGW("Empty DnsTlsServer list");
    if (orderedServers.empty()) LOG(WARNING) << "Empty DnsTlsServer list";


    DnsTlsTransport::Response code = DnsTlsTransport::Response::internal_error;
    DnsTlsTransport::Response code = DnsTlsTransport::Response::internal_error;
    for (const auto& server : orderedServers) {
    for (const auto& server : orderedServers) {
@@ -129,22 +128,22 @@ DnsTlsTransport::Response DnsTlsDispatcher::query(const DnsTlsServer& server, un
        ++xport->useCount;
        ++xport->useCount;
    }
    }


    ALOGV("Sending query of length %zu", query.size());
    LOG(DEBUG) << "Sending query of length " << query.size();
    auto res = xport->transport.query(query);
    auto res = xport->transport.query(query);
    ALOGV("Awaiting response");
    LOG(DEBUG) << "Awaiting response";
    const auto& result = res.get();
    const auto& result = res.get();
    DnsTlsTransport::Response code = result.code;
    DnsTlsTransport::Response code = result.code;
    if (code == DnsTlsTransport::Response::success) {
    if (code == DnsTlsTransport::Response::success) {
        if (result.response.size() > ans.size()) {
        if (result.response.size() > ans.size()) {
            ALOGV("Response too large: %zu > %zu", result.response.size(), ans.size());
            LOG(DEBUG) << "Response too large: " << result.response.size() << " > " << ans.size();
            code = DnsTlsTransport::Response::limit_error;
            code = DnsTlsTransport::Response::limit_error;
        } else {
        } else {
            ALOGV("Got response successfully");
            LOG(DEBUG) << "Got response successfully";
            *resplen = result.response.size();
            *resplen = result.response.size();
            netdutils::copy(ans, netdutils::makeSlice(result.response));
            netdutils::copy(ans, netdutils::makeSlice(result.response));
        }
        }
    } else {
    } else {
        ALOGV("Query failed: %u", (unsigned int) code);
        LOG(DEBUG) << "Query failed: " << (unsigned int)code;
    }
    }


    auto now = std::chrono::steady_clock::now();
    auto now = std::chrono::steady_clock::now();
+8 −9
Original line number Original line Diff line number Diff line
@@ -15,11 +15,10 @@
 */
 */


#define LOG_TAG "resolv"
#define LOG_TAG "resolv"
//#define LOG_NDEBUG 0


#include "DnsTlsQueryMap.h"
#include "DnsTlsQueryMap.h"


#include "log/log.h"
#include <android-base/logging.h>


namespace android {
namespace android {
namespace net {
namespace net {
@@ -30,12 +29,12 @@ std::unique_ptr<DnsTlsQueryMap::QueryFuture> DnsTlsQueryMap::recordQuery(


    // Store the query so it can be matched to the response or reissued.
    // Store the query so it can be matched to the response or reissued.
    if (query.size() < 2) {
    if (query.size() < 2) {
        ALOGW("Query is too short");
        LOG(WARNING) << "Query is too short";
        return nullptr;
        return nullptr;
    }
    }
    int32_t newId = getFreeId();
    int32_t newId = getFreeId();
    if (newId < 0) {
    if (newId < 0) {
        ALOGW("All query IDs are in use");
        LOG(WARNING) << "All query IDs are in use";
        return nullptr;
        return nullptr;
    }
    }
    Query q = { .newId = static_cast<uint16_t>(newId), .query = query };
    Query q = { .newId = static_cast<uint16_t>(newId), .query = query };
@@ -43,7 +42,7 @@ std::unique_ptr<DnsTlsQueryMap::QueryFuture> DnsTlsQueryMap::recordQuery(
    bool inserted;
    bool inserted;
    std::tie(it, inserted) = mQueries.emplace(newId, q);
    std::tie(it, inserted) = mQueries.emplace(newId, q);
    if (!inserted) {
    if (!inserted) {
        ALOGE("Failed to store pending query");
        LOG(ERROR) << "Failed to store pending query";
        return nullptr;
        return nullptr;
    }
    }
    return std::make_unique<QueryFuture>(q, it->second.result.get_future());
    return std::make_unique<QueryFuture>(q, it->second.result.get_future());
@@ -124,16 +123,16 @@ void DnsTlsQueryMap::clear() {
}
}


void DnsTlsQueryMap::onResponse(std::vector<uint8_t> response) {
void DnsTlsQueryMap::onResponse(std::vector<uint8_t> response) {
    ALOGV("Got response of size %zu", response.size());
    LOG(VERBOSE) << "Got response of size " << response.size();
    if (response.size() < 2) {
    if (response.size() < 2) {
        ALOGW("Response is too short");
        LOG(WARNING) << "Response is too short";
        return;
        return;
    }
    }
    uint16_t id = response[0] << 8 | response[1];
    uint16_t id = response[0] << 8 | response[1];
    std::lock_guard guard(mLock);
    std::lock_guard guard(mLock);
    auto it = mQueries.find(id);
    auto it = mQueries.find(id);
    if (it == mQueries.end()) {
    if (it == mQueries.end()) {
        ALOGW("Discarding response: unknown ID %d", id);
        LOG(WARNING) << "Discarding response: unknown ID " << id;
        return;
        return;
    }
    }
    Result r = { .code = Response::success, .response = std::move(response) };
    Result r = { .code = Response::success, .response = std::move(response) };
@@ -141,7 +140,7 @@ void DnsTlsQueryMap::onResponse(std::vector<uint8_t> response) {
    const uint8_t* data = it->second.query.query.base();
    const uint8_t* data = it->second.query.query.base();
    r.response[0] = data[0];
    r.response[0] = data[0];
    r.response[1] = data[1];
    r.response[1] = data[1];
    ALOGV("Sending result to dispatcher");
    LOG(DEBUG) << "Sending result to dispatcher";
    it->second.result.set_value(std::move(r));
    it->second.result.set_value(std::move(r));
    mQueries.erase(it);
    mQueries.erase(it);
}
}
+6 −7
Original line number Original line Diff line number Diff line
@@ -17,9 +17,8 @@
#include "DnsTlsSessionCache.h"
#include "DnsTlsSessionCache.h"


#define LOG_TAG "resolv"
#define LOG_TAG "resolv"
//#define LOG_NDEBUG 0


#include "log/log.h"
#include <android-base/logging.h>


namespace android {
namespace android {
namespace net {
namespace net {
@@ -39,16 +38,16 @@ void DnsTlsSessionCache::prepareSslContext(SSL_CTX* ssl_ctx) {
// static
// static
int DnsTlsSessionCache::newSessionCallback(SSL* ssl, SSL_SESSION* session) {
int DnsTlsSessionCache::newSessionCallback(SSL* ssl, SSL_SESSION* session) {
    if (!ssl || !session) {
    if (!ssl || !session) {
        ALOGE("Null SSL object in new session callback");
        LOG(ERROR) << "Null SSL object in new session callback";
        return 0;
        return 0;
    }
    }
    DnsTlsSessionCache* cache = reinterpret_cast<DnsTlsSessionCache*>(
    DnsTlsSessionCache* cache = reinterpret_cast<DnsTlsSessionCache*>(
            SSL_get_ex_data(ssl, 0));
            SSL_get_ex_data(ssl, 0));
    if (!cache) {
    if (!cache) {
        ALOGE("null transport in new session callback");
        LOG(ERROR) << "null transport in new session callback";
        return 0;
        return 0;
    }
    }
    ALOGV("Recording session");
    LOG(DEBUG) << "Recording session";
    cache->recordSession(session);
    cache->recordSession(session);
    return 1;  // Increment the refcount of session.
    return 1;  // Increment the refcount of session.
}
}
@@ -57,7 +56,7 @@ void DnsTlsSessionCache::recordSession(SSL_SESSION* session) {
    std::lock_guard guard(mLock);
    std::lock_guard guard(mLock);
    mSessions.emplace_front(session);
    mSessions.emplace_front(session);
    if (mSessions.size() > kMaxSize) {
    if (mSessions.size() > kMaxSize) {
        ALOGV("Too many sessions; trimming");
        LOG(DEBUG) << "Too many sessions; trimming";
        mSessions.pop_back();
        mSessions.pop_back();
    }
    }
}
}
@@ -65,7 +64,7 @@ void DnsTlsSessionCache::recordSession(SSL_SESSION* session) {
bssl::UniquePtr<SSL_SESSION> DnsTlsSessionCache::getSession() {
bssl::UniquePtr<SSL_SESSION> DnsTlsSessionCache::getSession() {
    std::lock_guard guard(mLock);
    std::lock_guard guard(mLock);
    if (mSessions.size() == 0) {
    if (mSessions.size() == 0) {
        ALOGV("No known sessions");
        LOG(DEBUG) << "No known sessions";
        return nullptr;
        return nullptr;
    }
    }
    bssl::UniquePtr<SSL_SESSION> ret = std::move(mSessions.front());
    bssl::UniquePtr<SSL_SESSION> ret = std::move(mSessions.front());
+61 −60
Original line number Original line Diff line number Diff line
@@ -15,7 +15,6 @@
 */
 */


#define LOG_TAG "resolv"
#define LOG_TAG "resolv"
//#define LOG_NDEBUG 0


#include "DnsTlsSocket.h"
#include "DnsTlsSocket.h"


@@ -32,7 +31,8 @@
#include "DnsTlsSessionCache.h"
#include "DnsTlsSessionCache.h"
#include "IDnsTlsSocketObserver.h"
#include "IDnsTlsSocketObserver.h"


#include "log/log.h"
#include <android-base/logging.h>

#include "netdutils/SocketOption.h"
#include "netdutils/SocketOption.h"


namespace android {
namespace android {
@@ -64,7 +64,7 @@ int waitForWriting(int fd) {
}  // namespace
}  // namespace


Status DnsTlsSocket::tcpConnect() {
Status DnsTlsSocket::tcpConnect() {
    ALOGV("%u connecting TCP socket", mMark);
    LOG(DEBUG) << mMark << " connecting TCP socket";
    int type = SOCK_NONBLOCK | SOCK_CLOEXEC;
    int type = SOCK_NONBLOCK | SOCK_CLOEXEC;
    switch (mServer.protocol) {
    switch (mServer.protocol) {
        case IPPROTO_TCP:
        case IPPROTO_TCP:
@@ -76,20 +76,20 @@ Status DnsTlsSocket::tcpConnect() {


    mSslFd.reset(socket(mServer.ss.ss_family, type, mServer.protocol));
    mSslFd.reset(socket(mServer.ss.ss_family, type, mServer.protocol));
    if (mSslFd.get() == -1) {
    if (mSslFd.get() == -1) {
        ALOGE("Failed to create socket");
        LOG(ERROR) << "Failed to create socket";
        return Status(errno);
        return Status(errno);
    }
    }


    const socklen_t len = sizeof(mMark);
    const socklen_t len = sizeof(mMark);
    if (setsockopt(mSslFd.get(), SOL_SOCKET, SO_MARK, &mMark, len) == -1) {
    if (setsockopt(mSslFd.get(), SOL_SOCKET, SO_MARK, &mMark, len) == -1) {
        ALOGE("Failed to set socket mark");
        LOG(ERROR) << "Failed to set socket mark";
        mSslFd.reset();
        mSslFd.reset();
        return Status(errno);
        return Status(errno);
    }
    }


    const Status tfo = enableSockopt(mSslFd.get(), SOL_TCP, TCP_FASTOPEN_CONNECT);
    const Status tfo = enableSockopt(mSslFd.get(), SOL_TCP, TCP_FASTOPEN_CONNECT);
    if (!isOk(tfo) && tfo.code() != ENOPROTOOPT) {
    if (!isOk(tfo) && tfo.code() != ENOPROTOOPT) {
        ALOGI("Failed to enable TFO: %s", tfo.msg().c_str());
        LOG(WARNING) << "Failed to enable TFO: " << tfo.msg();
    }
    }


    // Send 5 keepalives, 3 seconds apart, after 15 seconds of inactivity.
    // Send 5 keepalives, 3 seconds apart, after 15 seconds of inactivity.
@@ -98,7 +98,7 @@ Status DnsTlsSocket::tcpConnect() {
    if (connect(mSslFd.get(), reinterpret_cast<const struct sockaddr *>(&mServer.ss),
    if (connect(mSslFd.get(), reinterpret_cast<const struct sockaddr *>(&mServer.ss),
                sizeof(mServer.ss)) != 0 &&
                sizeof(mServer.ss)) != 0 &&
            errno != EINPROGRESS) {
            errno != EINPROGRESS) {
        ALOGV("Socket failed to connect");
        LOG(DEBUG) << "Socket failed to connect";
        mSslFd.reset();
        mSslFd.reset();
        return Status(errno);
        return Status(errno);
    }
    }
@@ -111,18 +111,18 @@ bool getSPKIDigest(const X509* cert, std::vector<uint8_t>* out) {
    unsigned char spki[spki_len];
    unsigned char spki[spki_len];
    unsigned char* temp = spki;
    unsigned char* temp = spki;
    if (spki_len != i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp)) {
    if (spki_len != i2d_X509_PUBKEY(X509_get_X509_PUBKEY(cert), &temp)) {
        ALOGW("SPKI length mismatch");
        LOG(WARNING) << "SPKI length mismatch";
        return false;
        return false;
    }
    }
    out->resize(SHA256_SIZE);
    out->resize(SHA256_SIZE);
    unsigned int digest_len = 0;
    unsigned int digest_len = 0;
    int ret = EVP_Digest(spki, spki_len, out->data(), &digest_len, EVP_sha256(), nullptr);
    int ret = EVP_Digest(spki, spki_len, out->data(), &digest_len, EVP_sha256(), nullptr);
    if (ret != 1) {
    if (ret != 1) {
        ALOGW("Server cert digest extraction failed");
        LOG(WARNING) << "Server cert digest extraction failed";
        return false;
        return false;
    }
    }
    if (digest_len != out->size()) {
    if (digest_len != out->size()) {
        ALOGW("Wrong digest length: %d", digest_len);
        LOG(WARNING) << "Wrong digest length: " << digest_len;
        return false;
        return false;
    }
    }
    return true;
    return true;
@@ -145,7 +145,7 @@ bool DnsTlsSocket::initialize() {
    //
    //
    // For discussion of alternative, sustainable approaches see b/71909242.
    // For discussion of alternative, sustainable approaches see b/71909242.
    if (SSL_CTX_load_verify_locations(mSslCtx.get(), nullptr, kCaCertDir) != 1) {
    if (SSL_CTX_load_verify_locations(mSslCtx.get(), nullptr, kCaCertDir) != 1) {
        ALOGE("Failed to load CA cert dir: %s", kCaCertDir);
        LOG(ERROR) << "Failed to load CA cert dir: " << kCaCertDir;
        return false;
        return false;
    }
    }


@@ -176,11 +176,11 @@ bool DnsTlsSocket::initialize() {


bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {
bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {
    if (!mSslCtx) {
    if (!mSslCtx) {
        ALOGE("Internal error: context is null in sslConnect");
        LOG(ERROR) << "Internal error: context is null in sslConnect";
        return nullptr;
        return nullptr;
    }
    }
    if (!SSL_CTX_set_min_proto_version(mSslCtx.get(), TLS1_2_VERSION)) {
    if (!SSL_CTX_set_min_proto_version(mSslCtx.get(), TLS1_2_VERSION)) {
        ALOGE("Failed to set minimum TLS version");
        LOG(ERROR) << "Failed to set minimum TLS version";
        return nullptr;
        return nullptr;
    }
    }


@@ -196,12 +196,12 @@ bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {


    if (!mServer.name.empty()) {
    if (!mServer.name.empty()) {
        if (SSL_set_tlsext_host_name(ssl.get(), mServer.name.c_str()) != 1) {
        if (SSL_set_tlsext_host_name(ssl.get(), mServer.name.c_str()) != 1) {
            ALOGE("Failed to set SNI to %s", mServer.name.c_str());
            LOG(ERROR) << "ailed to set SNI to " << mServer.name;
            return nullptr;
            return nullptr;
        }
        }
        X509_VERIFY_PARAM* param = SSL_get0_param(ssl.get());
        X509_VERIFY_PARAM* param = SSL_get0_param(ssl.get());
        if (X509_VERIFY_PARAM_set1_host(param, mServer.name.data(), mServer.name.size()) != 1) {
        if (X509_VERIFY_PARAM_set1_host(param, mServer.name.data(), mServer.name.size()) != 1) {
            ALOGE("Failed to set verify host param to %s", mServer.name.c_str());
            LOG(ERROR) << "Failed to set verify host param to " << mServer.name;
            return nullptr;
            return nullptr;
        }
        }
        // This will cause the handshake to fail if certificate verification fails.
        // This will cause the handshake to fail if certificate verification fails.
@@ -210,41 +210,41 @@ bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {


    bssl::UniquePtr<SSL_SESSION> session = mCache->getSession();
    bssl::UniquePtr<SSL_SESSION> session = mCache->getSession();
    if (session) {
    if (session) {
        ALOGV("Setting session");
        LOG(DEBUG) << "Setting session";
        SSL_set_session(ssl.get(), session.get());
        SSL_set_session(ssl.get(), session.get());
    } else {
    } else {
        ALOGV("No session available");
        LOG(DEBUG) << "No session available";
    }
    }


    for (;;) {
    for (;;) {
        ALOGV("%u Calling SSL_connect", mMark);
        LOG(DEBUG) << mMark << " Calling SSL_connect";
        int ret = SSL_connect(ssl.get());
        int ret = SSL_connect(ssl.get());
        ALOGV("%u SSL_connect returned %d", mMark, ret);
        LOG(DEBUG) << mMark << " SSL_connect returned " << ret;
        if (ret == 1) break;  // SSL handshake complete;
        if (ret == 1) break;  // SSL handshake complete;


        const int ssl_err = SSL_get_error(ssl.get(), ret);
        const int ssl_err = SSL_get_error(ssl.get(), ret);
        switch (ssl_err) {
        switch (ssl_err) {
            case SSL_ERROR_WANT_READ:
            case SSL_ERROR_WANT_READ:
                if (waitForReading(fd) != 1) {
                if (waitForReading(fd) != 1) {
                    ALOGW("SSL_connect read error: %d", errno);
                    LOG(WARNING) << "SSL_connect read error: " << errno;
                    return nullptr;
                    return nullptr;
                }
                }
                break;
                break;
            case SSL_ERROR_WANT_WRITE:
            case SSL_ERROR_WANT_WRITE:
                if (waitForWriting(fd) != 1) {
                if (waitForWriting(fd) != 1) {
                    ALOGW("SSL_connect write error");
                    LOG(WARNING) << "SSL_connect write error";
                    return nullptr;
                    return nullptr;
                }
                }
                break;
                break;
            default:
            default:
                ALOGW("SSL_connect error %d, errno=%d", ssl_err, errno);
                LOG(WARNING) << "SSL_connect error " << ssl_err << ", errno=" << errno;
                return nullptr;
                return nullptr;
        }
        }
    }
    }


    // TODO: Call SSL_shutdown before discarding the session if validation fails.
    // TODO: Call SSL_shutdown before discarding the session if validation fails.
    if (!mServer.fingerprints.empty()) {
    if (!mServer.fingerprints.empty()) {
        ALOGV("Checking DNS over TLS fingerprint");
        LOG(DEBUG) << "Checking DNS over TLS fingerprint";


        // We only care that the chain is internally self-consistent, not that
        // We only care that the chain is internally self-consistent, not that
        // it chains to a trusted root, so we can ignore some kinds of errors.
        // it chains to a trusted root, so we can ignore some kinds of errors.
@@ -257,13 +257,13 @@ bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {
            case X509_V_ERR_CERT_UNTRUSTED:
            case X509_V_ERR_CERT_UNTRUSTED:
                break;
                break;
            default:
            default:
                ALOGW("Invalid certificate chain, error %d", verify_result);
                LOG(WARNING) << "Invalid certificate chain, error " << verify_result;
                return nullptr;
                return nullptr;
        }
        }


        STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl.get());
        STACK_OF(X509) *chain = SSL_get_peer_cert_chain(ssl.get());
        if (!chain) {
        if (!chain) {
            ALOGW("Server has null certificate");
            LOG(WARNING) << "Server has null certificate";
            return nullptr;
            return nullptr;
        }
        }
        // Chain and its contents are owned by ssl, so we don't need to free explicitly.
        // Chain and its contents are owned by ssl, so we don't need to free explicitly.
@@ -274,7 +274,7 @@ bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {
            X509* cert = sk_X509_value(chain, i);
            X509* cert = sk_X509_value(chain, i);
            std::vector<uint8_t> digest;
            std::vector<uint8_t> digest;
            if (!getSPKIDigest(cert, &digest)) {
            if (!getSPKIDigest(cert, &digest)) {
                ALOGE("Digest computation failed");
                LOG(ERROR) << "Digest computation failed";
                return nullptr;
                return nullptr;
            }
            }


@@ -285,14 +285,14 @@ bssl::UniquePtr<SSL> DnsTlsSocket::sslConnect(int fd) {
        }
        }


        if (!matched) {
        if (!matched) {
            ALOGW("No matching fingerprint");
            LOG(WARNING) << "No matching fingerprint";
            return nullptr;
            return nullptr;
        }
        }


        ALOGV("DNS over TLS fingerprint is correct");
        LOG(DEBUG) << "DNS over TLS fingerprint is correct";
    }
    }


    ALOGV("%u handshake complete", mMark);
    LOG(DEBUG) << mMark << " handshake complete";


    return ssl;
    return ssl;
}
}
@@ -306,7 +306,7 @@ void DnsTlsSocket::sslDisconnect() {
}
}


bool DnsTlsSocket::sslWrite(const Slice buffer) {
bool DnsTlsSocket::sslWrite(const Slice buffer) {
    ALOGV("%u Writing %zu bytes", mMark, buffer.size());
    LOG(DEBUG) << mMark << " Writing " << buffer.size() << " bytes";
    for (;;) {
    for (;;) {
        int ret = SSL_write(mSsl.get(), buffer.base(), buffer.size());
        int ret = SSL_write(mSsl.get(), buffer.base(), buffer.size());
        if (ret == int(buffer.size())) break;  // SSL write complete;
        if (ret == int(buffer.size())) break;  // SSL write complete;
@@ -316,19 +316,19 @@ bool DnsTlsSocket::sslWrite(const Slice buffer) {
            switch (ssl_err) {
            switch (ssl_err) {
                case SSL_ERROR_WANT_WRITE:
                case SSL_ERROR_WANT_WRITE:
                    if (waitForWriting(mSslFd.get()) != 1) {
                    if (waitForWriting(mSslFd.get()) != 1) {
                        ALOGV("SSL_write error");
                        LOG(DEBUG) << "SSL_write error";
                        return false;
                        return false;
                    }
                    }
                    continue;
                    continue;
                case 0:
                case 0:
                    break;  // SSL write complete;
                    break;  // SSL write complete;
                default:
                default:
                    ALOGV("SSL_write error %d", ssl_err);
                    LOG(DEBUG) << "SSL_write error " << ssl_err;
                    return false;
                    return false;
            }
            }
        }
        }
    }
    }
    ALOGV("%u Wrote %zu bytes", mMark, buffer.size());
    LOG(DEBUG) << mMark << " Wrote " << buffer.size() << " bytes";
    return true;
    return true;
}
}


@@ -359,16 +359,16 @@ void DnsTlsSocket::loop() {


        const int s = TEMP_FAILURE_RETRY(poll(fds, std::size(fds), timeout_msecs));
        const int s = TEMP_FAILURE_RETRY(poll(fds, std::size(fds), timeout_msecs));
        if (s == 0) {
        if (s == 0) {
            ALOGV("Idle timeout");
            LOG(DEBUG) << "Idle timeout";
            break;
            break;
        }
        }
        if (s < 0) {
        if (s < 0) {
            ALOGV("Poll failed: %d", errno);
            LOG(DEBUG) << "Poll failed: " << errno;
            break;
            break;
        }
        }
        if (fds[SSLFD].revents & (POLLIN | POLLERR | POLLHUP)) {
        if (fds[SSLFD].revents & (POLLIN | POLLERR | POLLHUP)) {
            if (!readResponse()) {
            if (!readResponse()) {
                ALOGV("SSL remote close or read error.");
                LOG(DEBUG) << "SSL remote close or read error.";
                break;
                break;
            }
            }
        }
        }
@@ -376,16 +376,16 @@ void DnsTlsSocket::loop() {
            int64_t num_queries;
            int64_t num_queries;
            ssize_t res = read(mEventFd.get(), &num_queries, sizeof(num_queries));
            ssize_t res = read(mEventFd.get(), &num_queries, sizeof(num_queries));
            if (res < 0) {
            if (res < 0) {
                ALOGW("Error during eventfd read");
                LOG(WARNING) << "Error during eventfd read";
                break;
                break;
            } else if (res == 0) {
            } else if (res == 0) {
                ALOGW("eventfd closed; disconnecting");
                LOG(WARNING) << "eventfd closed; disconnecting";
                break;
                break;
            } else if (res != sizeof(num_queries)) {
            } else if (res != sizeof(num_queries)) {
                ALOGE("Int size mismatch: %zd != %zu", res, sizeof(num_queries));
                LOG(ERROR) << "Int size mismatch: " << res << " != " << sizeof(num_queries);
                break;
                break;
            } else if (num_queries < 0) {
            } else if (num_queries < 0) {
                ALOGV("Negative eventfd read indicates destructor-initiated shutdown");
                LOG(DEBUG) << "Negative eventfd read indicates destructor-initiated shutdown";
                break;
                break;
            }
            }
            // Take ownership of all pending queries.  (q is always empty here.)
            // Take ownership of all pending queries.  (q is always empty here.)
@@ -402,31 +402,31 @@ void DnsTlsSocket::loop() {
            q.pop_front();
            q.pop_front();
        }
        }
    }
    }
    ALOGV("Disconnecting");
    LOG(DEBUG) << "Disconnecting";
    sslDisconnect();
    sslDisconnect();
    ALOGV("Calling onClosed");
    LOG(DEBUG) << "Calling onClosed";
    mObserver->onClosed();
    mObserver->onClosed();
    ALOGV("Ending loop");
    LOG(DEBUG) << "Ending loop";
}
}


DnsTlsSocket::~DnsTlsSocket() {
DnsTlsSocket::~DnsTlsSocket() {
    ALOGV("Destructor");
    LOG(DEBUG) << "Destructor";
    // This will trigger an orderly shutdown in loop().
    // This will trigger an orderly shutdown in loop().
    requestLoopShutdown();
    requestLoopShutdown();
    {
    {
        // Wait for the orderly shutdown to complete.
        // Wait for the orderly shutdown to complete.
        std::lock_guard guard(mLock);
        std::lock_guard guard(mLock);
        if (mLoopThread && std::this_thread::get_id() == mLoopThread->get_id()) {
        if (mLoopThread && std::this_thread::get_id() == mLoopThread->get_id()) {
            ALOGE("Violation of re-entrance precondition");
            LOG(ERROR) << "Violation of re-entrance precondition";
            return;
            return;
        }
        }
    }
    }
    if (mLoopThread) {
    if (mLoopThread) {
        ALOGV("Waiting for loop thread to terminate");
        LOG(DEBUG) << "Waiting for loop thread to terminate";
        mLoopThread->join();
        mLoopThread->join();
        mLoopThread.reset();
        mLoopThread.reset();
    }
    }
    ALOGV("Destructor completed");
    LOG(DEBUG) << "Destructor completed";
}
}


bool DnsTlsSocket::query(uint16_t id, const Slice query) {
bool DnsTlsSocket::query(uint16_t id, const Slice query) {
@@ -457,12 +457,12 @@ void DnsTlsSocket::requestLoopShutdown() {


bool DnsTlsSocket::incrementEventFd(const int64_t count) {
bool DnsTlsSocket::incrementEventFd(const int64_t count) {
    if (mEventFd == -1) {
    if (mEventFd == -1) {
        ALOGE("eventfd is not initialized");
        LOG(ERROR) << "eventfd is not initialized";
        return false;
        return false;
    }
    }
    ssize_t written = write(mEventFd.get(), &count, sizeof(count));
    ssize_t written = write(mEventFd.get(), &count, sizeof(count));
    if (written != sizeof(count)) {
    if (written != sizeof(count)) {
        ALOGE("Failed to increment eventfd by %" PRId64, count);
        LOG(ERROR) << "Failed to increment eventfd by " << count;
        return false;
        return false;
    }
    }
    return true;
    return true;
@@ -474,8 +474,9 @@ int DnsTlsSocket::sslRead(const Slice buffer, bool wait) {
    while (remaining > 0) {
    while (remaining > 0) {
        int ret = SSL_read(mSsl.get(), buffer.limit() - remaining, remaining);
        int ret = SSL_read(mSsl.get(), buffer.limit() - remaining, remaining);
        if (ret == 0) {
        if (ret == 0) {
            ALOGW_IF(remaining < buffer.size(), "SSL closed with %zu of %zu bytes remaining",
            if (remaining < buffer.size())
                     remaining, buffer.size());
                LOG(WARNING) << "SSL closed with " << remaining << " of " << buffer.size()
                             << " bytes remaining";
            return SSL_ERROR_ZERO_RETURN;
            return SSL_ERROR_ZERO_RETURN;
        }
        }


@@ -483,12 +484,12 @@ int DnsTlsSocket::sslRead(const Slice buffer, bool wait) {
            const int ssl_err = SSL_get_error(mSsl.get(), ret);
            const int ssl_err = SSL_get_error(mSsl.get(), ret);
            if (wait && ssl_err == SSL_ERROR_WANT_READ) {
            if (wait && ssl_err == SSL_ERROR_WANT_READ) {
                if (waitForReading(mSslFd.get()) != 1) {
                if (waitForReading(mSslFd.get()) != 1) {
                    ALOGV("Poll failed in sslRead: %d", errno);
                    LOG(DEBUG) << "Poll failed in sslRead: " << errno;
                    return SSL_ERROR_SYSCALL;
                    return SSL_ERROR_SYSCALL;
                }
                }
                continue;
                continue;
            } else {
            } else {
                ALOGV("SSL_read error %d", ssl_err);
                LOG(DEBUG) << "SSL_read error " << ssl_err;
                return ssl_err;
                return ssl_err;
            }
            }
        }
        }
@@ -503,16 +504,16 @@ bool DnsTlsSocket::sendQuery(const std::vector<uint8_t>& buf) {
    if (!sslWrite(netdutils::makeSlice(buf))) {
    if (!sslWrite(netdutils::makeSlice(buf))) {
        return false;
        return false;
    }
    }
    ALOGV("%u SSL_write complete", mMark);
    LOG(DEBUG) << mMark << " SSL_write complete";
    return true;
    return true;
}
}


bool DnsTlsSocket::readResponse() {
bool DnsTlsSocket::readResponse() {
    ALOGV("reading response");
    LOG(DEBUG) << "reading response";
    uint8_t responseHeader[2];
    uint8_t responseHeader[2];
    int err = sslRead(Slice(responseHeader, 2), false);
    int err = sslRead(Slice(responseHeader, 2), false);
    if (err == SSL_ERROR_WANT_READ) {
    if (err == SSL_ERROR_WANT_READ) {
        ALOGV("Ignoring spurious wakeup from server");
        LOG(DEBUG) << "Ignoring spurious wakeup from server";
        return true;
        return true;
    }
    }
    if (err != SSL_ERROR_NONE) {
    if (err != SSL_ERROR_NONE) {
@@ -522,10 +523,10 @@ bool DnsTlsSocket::readResponse() {
    // always invalid when truncated, so the response will be treated as an error.
    // always invalid when truncated, so the response will be treated as an error.
    constexpr uint16_t MAX_SIZE = 8192;
    constexpr uint16_t MAX_SIZE = 8192;
    const uint16_t responseSize = (responseHeader[0] << 8) | responseHeader[1];
    const uint16_t responseSize = (responseHeader[0] << 8) | responseHeader[1];
    ALOGV("%u Expecting response of size %i", mMark, responseSize);
    LOG(DEBUG) << mMark << " Expecting response of size " << responseSize;
    std::vector<uint8_t> response(std::min(responseSize, MAX_SIZE));
    std::vector<uint8_t> response(std::min(responseSize, MAX_SIZE));
    if (sslRead(netdutils::makeSlice(response), true) != SSL_ERROR_NONE) {
    if (sslRead(netdutils::makeSlice(response), true) != SSL_ERROR_NONE) {
        ALOGV("%u Failed to read %zu bytes", mMark, response.size());
        LOG(DEBUG) << mMark << " Failed to read " << response.size() << " bytes";
        return false;
        return false;
    }
    }
    uint16_t remainingBytes = responseSize - response.size();
    uint16_t remainingBytes = responseSize - response.size();
@@ -533,12 +534,12 @@ bool DnsTlsSocket::readResponse() {
        constexpr uint16_t CHUNK_SIZE = 2048;
        constexpr uint16_t CHUNK_SIZE = 2048;
        std::vector<uint8_t> discard(std::min(remainingBytes, CHUNK_SIZE));
        std::vector<uint8_t> discard(std::min(remainingBytes, CHUNK_SIZE));
        if (sslRead(netdutils::makeSlice(discard), true) != SSL_ERROR_NONE) {
        if (sslRead(netdutils::makeSlice(discard), true) != SSL_ERROR_NONE) {
            ALOGV("%u Failed to discard %zu bytes", mMark, discard.size());
            LOG(DEBUG) << mMark << " Failed to discard " << discard.size() << " bytes";
            return false;
            return false;
        }
        }
        remainingBytes -= discard.size();
        remainingBytes -= discard.size();
    }
    }
    ALOGV("%u SSL_read complete", mMark);
    LOG(DEBUG) << mMark << " SSL_read complete";


    mObserver->onResponse(std::move(response));
    mObserver->onResponse(std::move(response));
    return true;
    return true;
Loading