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

Commit 53d3eb2a authored by Luke Huang's avatar Luke Huang
Browse files

Adjust the log mechanism for DoH and some minor changes.

1. Init the log level by device build.
2. Add TODO comment for aosp/1769446.
3. Higher the log level for sensitive log msgs.
4. Sort the input servers before processing it with DoH.

Test: atest
Bug: 193850030
Bug: 155855709
Change-Id: I67932699275354e7ebdb1636d7c8bf977d43cfbd
parent abd545bf
Loading
Loading
Loading
Loading
+2 −1
Original line number Diff line number Diff line
@@ -397,7 +397,8 @@ rust_ffi_static {
        "liburl",
    ],
    prefer_rlib: true,
    // For unit tests to run on the Android 10 platform, libunwind must be statically linked..
    // TODO(b/194022174), for unit tests to run on the Android 10 platform,
    // libunwind must be statically linked.
    whole_static_libs: ["libunwind"],
    apex_available: [
        "//apex_available:platform",  // Needed by doh_ffi_test
+3 −1
Original line number Diff line number Diff line
@@ -31,7 +31,9 @@ bool resolv_init(const ResolverNetdCallbacks* callbacks) {
    android::base::SetDefaultTag("libnetd_resolv");
    LOG(INFO) << __func__ << ": Initializing resolver";
    // TODO(b/170539625): restore log level to WARNING after clarifying flaky tests.
    resolv_set_log_severity(isUserDebugBuild() ? android::base::DEBUG : android::base::WARNING);
    const bool isDebug = isUserDebugBuild();
    resolv_set_log_severity(isDebug ? android::base::DEBUG : android::base::WARNING);
    doh_init_logger(isDebug ? LOG_LEVEL_DEBUG : LOG_LEVEL_WARN);
    using android::net::gApiLevel;
    gApiLevel = getApiLevel();
    using android::net::gResNetdCallbacks;
+13 −1
Original line number Diff line number Diff line
@@ -18,6 +18,8 @@

#include "PrivateDnsConfiguration.h"

#include <algorithm>

#include <android-base/format.h>
#include <android-base/logging.h>
#include <android-base/stringprintf.h>
@@ -35,6 +37,7 @@
using aidl::android::net::resolv::aidl::IDnsResolverUnsolicitedEventListener;
using aidl::android::net::resolv::aidl::PrivateDnsValidationEventParcel;
using android::base::StringPrintf;
using android::netdutils::IPAddress;
using android::netdutils::setThreadName;
using android::netdutils::Slice;
using std::chrono::milliseconds;
@@ -439,12 +442,21 @@ int PrivateDnsConfiguration::setDoh(int32_t netId, uint32_t mark,
               << std::dec << ", " << servers.size() << ", " << name << ")";
    std::lock_guard guard(mPrivateDnsLock);

    // Sort the input servers to ensure that we could get the server vector at the same order.
    std::vector<std::string> sortedServers = servers;
    // Prefer ipv6.
    std::sort(sortedServers.begin(), sortedServers.end(), [](std::string a, std::string b) {
        IPAddress ipa = IPAddress::forString(a);
        IPAddress ipb = IPAddress::forString(b);
        return ipa > ipb;
    });

    initDohLocked();

    // TODO: 1. Improve how to choose the server
    // TODO: 2. Support multiple servers
    for (const auto& entry : mAvailableDoHProviders) {
        const auto& doh = entry.getDohIdentity(servers, name);
        const auto& doh = entry.getDohIdentity(sortedServers, name);
        if (!doh.ok()) continue;

        auto it = mDohTracker.find(netId);
+22 −1
Original line number Diff line number Diff line
@@ -34,6 +34,21 @@ static const ssize_t RESULT_CAN_NOT_SEND = -2;
/// The return code of doh_query to indicate that the query timed out.
static const ssize_t RESULT_TIMEOUT = -255;

/// The error log level.
static const uint32_t LOG_LEVEL_ERROR = 0;

/// The warning log level.
static const uint32_t LOG_LEVEL_WARN = 1;

/// The info log level.
static const uint32_t LOG_LEVEL_INFO = 2;

/// The debug log level.
static const uint32_t LOG_LEVEL_DEBUG = 3;

/// The trace log level.
static const uint32_t LOG_LEVEL_TRACE = 4;

/// Context for a running DoH engine.
struct DohDispatcher;

@@ -42,7 +57,13 @@ using ValidationCallback = void (*)(uint32_t net_id, bool success, const char* i

extern "C" {

/// Performs static initialization for the DoH engine.
/// Performs static initialization for android logger.
void doh_init_logger(uint32_t level);

/// Set the log level.
void doh_set_log_level(uint32_t level);

/// Performs the initialization for the DoH engine.
/// Creates and returns a DoH engine instance.
DohDispatcher* doh_dispatcher_new(ValidationCallback ptr);

+45 −7
Original line number Diff line number Diff line
@@ -21,7 +21,7 @@ use futures::future::join_all;
use futures::stream::FuturesUnordered;
use futures::StreamExt;
use libc::{c_char, int32_t, size_t, ssize_t, uint32_t, uint64_t};
use log::{debug, error, info, warn};
use log::{debug, error, info, trace, warn};
use quiche::h3;
use ring::rand::SecureRandom;
use std::collections::HashMap;
@@ -31,7 +31,7 @@ use std::ops::Deref;
use std::os::unix::io::{AsRawFd, RawFd};
use std::pin::Pin;
use std::str::FromStr;
use std::sync::Arc;
use std::sync::{Arc, Once};
use std::{ptr, slice};
use tokio::net::UdpSocket;
use tokio::runtime::{Builder, Runtime};
@@ -40,12 +40,24 @@ use tokio::task;
use tokio::time::{timeout, Duration, Instant};
use url::Url;

static INIT: Once = Once::new();

/// The return code of doh_query means that there is no answer.
pub const RESULT_INTERNAL_ERROR: ssize_t = -1;
/// The return code of doh_query means that query can't be sent.
pub const RESULT_CAN_NOT_SEND: ssize_t = -2;
/// The return code of doh_query to indicate that the query timed out.
pub const RESULT_TIMEOUT: ssize_t = -255;
/// The error log level.
pub const LOG_LEVEL_ERROR: u32 = 0;
/// The warning log level.
pub const LOG_LEVEL_WARN: u32 = 1;
/// The info log level.
pub const LOG_LEVEL_INFO: u32 = 2;
/// The debug log level.
pub const LOG_LEVEL_DEBUG: u32 = 3;
/// The trace log level.
pub const LOG_LEVEL_TRACE: u32 = 4;

const MAX_BUFFERED_CMD_SIZE: usize = 400;
const MAX_INCOMING_BUFFER_SIZE_WHOLE: u64 = 10000000;
@@ -330,7 +342,7 @@ impl DohConnection {
                    debug!("quiche::h3::Event::Data");
                    let mut buf = vec![0; MAX_DATAGRAM_SIZE];
                    if let Ok(read) = h3_conn.recv_body(&mut self.quic_conn, stream_id, &mut buf) {
                        debug!(
                        trace!(
                            "got {} bytes of response data on stream {}: {:x?}",
                            read,
                            stream_id,
@@ -648,7 +660,7 @@ async fn doh_handler(
                info!("probe_futures remaining size: {}", probe_futures.len());
            },
            Some(cmd) = cmd_rx.recv() => {
                info!("recv {:?}", cmd);
                trace!("recv {:?}", cmd);
                match cmd {
                    DohCommand::Probe { info, timeout: t } => {
                        match make_connection_if_needed(&info, &mut doh_conn_map, &mut config_cache) {
@@ -714,7 +726,7 @@ fn make_doh_udp_socket(peer_addr: SocketAddr, mark: u32) -> Result<std::net::Udp
    }
    udp_sk.connect(peer_addr)?;

    info!("connecting to {:} from {:}", peer_addr, udp_sk.local_addr()?);
    debug!("connecting to {:} from {:}", peer_addr, udp_sk.local_addr()?);
    Ok(udp_sk)
}

@@ -784,11 +796,37 @@ fn make_probe_query() -> Result<String> {
    Ok(base64::encode_config(query, base64::URL_SAFE_NO_PAD))
}

/// Performs static initialization for the DoH engine.
/// Performs static initialization for android logger.
#[no_mangle]
pub extern "C" fn doh_init_logger(level: u32) {
    INIT.call_once(|| {
        let level = match level {
            LOG_LEVEL_WARN => log::Level::Warn,
            LOG_LEVEL_DEBUG => log::Level::Debug,
            _ => log::Level::Error,
        };
        android_logger::init_once(android_logger::Config::default().with_min_level(level));
    });
}

/// Set the log level.
#[no_mangle]
pub extern "C" fn doh_set_log_level(level: u32) {
    let level = match level {
        LOG_LEVEL_ERROR => log::LevelFilter::Error,
        LOG_LEVEL_WARN => log::LevelFilter::Warn,
        LOG_LEVEL_INFO => log::LevelFilter::Info,
        LOG_LEVEL_DEBUG => log::LevelFilter::Debug,
        LOG_LEVEL_TRACE => log::LevelFilter::Trace,
        _ => log::LevelFilter::Off,
    };
    log::set_max_level(level);
}

/// Performs the initialization for the DoH engine.
/// Creates and returns a DoH engine instance.
#[no_mangle]
pub extern "C" fn doh_dispatcher_new(ptr: ValidationCallback) -> *mut DohDispatcher {
    android_logger::init_once(android_logger::Config::default().with_min_level(log::Level::Info));
    match DohDispatcher::new(ptr) {
        Ok(c) => Box::into_raw(c),
        Err(e) => {
Loading