編輯:關於 Android 程式設計
目標很明確:在 Android 4.4 以上、okhttp 3.2 的環境下,不依賴 root,純粹在應用層取得 DNS 維度的底層數據。
思路則是:以 JNI 搭配 hook,攔截 libc.so 中的 DNS 關鍵函式 getaddrinfo。
人為讓 DNS 解析失敗,就能從堆疊追蹤看見完整路徑:

java.net.InetAddress.lookupHostByName(InetAddress.java:424) java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) java.net.InetAddress.getAllByName(InetAddress.java:214) okhttp3.Dns$1.lookup(Dns.java:39) okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173) okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139) okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81) okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174) okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:127) okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:97) okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:289) okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:241) okhttp3.RealCall.getResponse(RealCall.java:240) okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:198) okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:160) okhttp3.RealCall.execute(RealCall.java:57)
okhttp3 把 DNS 抽象成一個介面,預設實作只有短短幾行,最終就是轉手交給 InetAddress:
Dns SYSTEM = new Dns() {
@Override
public List<InetAddress> lookup(String hostname) throws UnknownHostException {
if (hostname == null) throw new UnknownHostException("hostname == null");
return Arrays.asList(InetAddress.getAllByName(hostname));
}
};
往下走是 getAllByName → getAllByNameImpl → lookupHostByName。這段程式碼有兩個值得注意的細節:一是先嘗試把字串當成數字位址解析(parseNumericAddressNoThrow),二是 lookupHostByName 裡帶有 addressCache 的正負向快取。
public static InetAddress[] getAllByName(String host) throws UnknownHostException {
return getAllByNameImpl(host).clone();
}
private static InetAddress[] getAllByNameImpl(String host) throws UnknownHostException {
if (host == null || host.isEmpty()) {
return loopbackAddresses();
}
// 先看是不是數字位址(含被中括號包住的 IPv6)
InetAddress result = parseNumericAddressNoThrow(host);
if (result != null) {
result = disallowDeprecatedFormats(host, result);
if (result == null) {
throw new UnknownHostException("Deprecated IPv4 address format: " + host);
}
return new InetAddress[] { result };
}
return lookupHostByName(host).clone();
}
private static InetAddress parseNumericAddressNoThrow(String address) {
if (address.startsWith("[") && address.endsWith("]") && address.indexOf(':') != -1) {
address = address.substring(1, address.length() - 1);
}
StructAddrinfo hints = new StructAddrinfo();
hints.ai_flags = AI_NUMERICHOST;
InetAddress[] addresses = null;
try {
addresses = Libcore.os.getaddrinfo(address, hints);
} catch (GaiException ignored) {
}
return (addresses != null) ? addresses[0] : null;
}
private static InetAddress[] lookupHostByName(String host) throws UnknownHostException {
BlockGuard.getThreadPolicy().onNetwork();
// 有快取就直接回傳(正負向結果都會被快取)
Object cachedResult = addressCache.get(host);
if (cachedResult != null) {
if (cachedResult instanceof InetAddress[]) {
return (InetAddress[]) cachedResult;
} else {
throw new UnknownHostException((String) cachedResult);
}
}
try {
StructAddrinfo hints = new StructAddrinfo();
hints.ai_flags = AI_ADDRCONFIG;
hints.ai_family = AF_UNSPEC;
// 不指定 socket type 的話,每個位址會出現兩次(SOCK_STREAM 與 SOCK_DGRAM 各一),
// 既然不打算回傳 family,乾脆只挑一種。
hints.ai_socktype = SOCK_STREAM;
InetAddress[] addresses = Libcore.os.getaddrinfo(host, hints);
for (InetAddress address : addresses) {
address.hostName = host;
}
addressCache.put(host, addresses);
return addresses;
} catch (GaiException gaiException) {
// 若失敗原因是缺少 INTERNET 權限,丟出清楚的 SecurityException 便於除錯
if (gaiException.getCause() instanceof ErrnoException) {
if (((ErrnoException) gaiException.getCause()).errno == EACCES) {
throw new SecurityException("Permission denied (missing INTERNET permission?)", gaiException);
}
}
String detailMessage = "Unable to resolve host \"" + host + "\": "
+ Libcore.os.gai_strerror(gaiException.error);
addressCache.putUnknownHost(host, detailMessage);
throw gaiException.rethrowAsUnknownHostException(detailMessage);
}
}
在應用層寫一段最直白的 okhttp 呼叫:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(ipaddr)
.build();
Response response = client.newCall(request).execute();
它會觸發 Libcore.os.getaddrinfo(host, hints) 兩次。第一次的 hints.ai_flags 是 AI_NUMERICHOST(純數字位址探測),第二次才是真正要解析網域的那次:
hints.ai_flags = AI_ADDRCONFIG; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM;
結論:在 C 層可以靠 ai_flags 與 ai_socktype 的組合,把這兩次呼叫區分開,只攔真正的 DNS 請求。
libcore/io/ForwardingOs.java 只是轉發:
public InetAddress[] getaddrinfo(String node, StructAddrinfo hints) throws GaiException {
return os.getaddrinfo(node, hints);
}
libcore/io/Posix.java 宣告成 native:
public native InetAddress[] getaddrinfo(String node, StructAddrinfo hints) throws GaiException;
而 libcore_io_Posix.cpp 中的 Posix_getaddrinfo 就是 Java 層的代理。它把 Java 的 StructAddrinfo 欄位逐一讀進 C 的 addrinfo 結構,然後才真正呼叫 libc:
static jobjectArray Posix_getaddrinfo(JNIEnv* env, jobject, jstring javaNode, jobject javaHints) {
ScopedUtfChars node(env, javaNode);
if (node.c_str() == NULL) {
return NULL;
}
static jfieldID flagsFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_flags", "I");
static jfieldID familyFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_family", "I");
static jfieldID socktypeFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_socktype", "I");
static jfieldID protocolFid = env->GetFieldID(JniConstants::structAddrinfoClass, "ai_protocol", "I");
addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = env->GetIntField(javaHints, flagsFid);
hints.ai_family = env->GetIntField(javaHints, familyFid);
hints.ai_socktype = env->GetIntField(javaHints, socktypeFid);
hints.ai_protocol = env->GetIntField(javaHints, protocolFid);
addrinfo* addressList = NULL;
errno = 0;
int rc = getaddrinfo(node.c_str(), NULL, &hints, &addressList);
UniquePtr addressListDeleter(addressList);
if (rc != 0) {
throwGaiException(env, "getaddrinfo", rc);
return NULL;
}
// 先數一遍結果數量,才知道該配置多大的輸出陣列
int addressCount = 0;
for (addrinfo* ai = addressList; ai != NULL; ai = ai->ai_next) {
if (ai->ai_family == AF_INET || ai->ai_family == AF_INET6) {
++addressCount;
} else {
ALOGE("getaddrinfo unexpected ai_family %i", ai->ai_family);
}
}
if (addressCount == 0) {
return NULL;
}
jobjectArray result = env->NewObjectArray(addressCount, JniConstants::inetAddressClass, NULL);
if (result == NULL) {
return NULL;
}
// 逐一轉成 Java 的 InetAddress
int index = 0;
for (addrinfo* ai = addressList; ai != NULL; ai = ai->ai_next) {
if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) {
ALOGE("getaddrinfo unexpected ai_family %i", ai->ai_family);
continue;
}
sockaddr_storage& address = *reinterpret_cast<sockaddr_storage*>(ai->ai_addr);
ScopedLocalRef<jobject> inetAddress(env, sockaddrToInetAddress(env, address, NULL));
if (inetAddress.get() == NULL) {
return NULL;
}
env->SetObjectArrayElement(result, index, inetAddress.get());
++index;
}
return result;
}
最後 getaddrinfo 走進 Bionic 的標準庫。這裡有個對 hook 相當重要的分支:在非 "local" 模式下,請求會被轉交給 android_getaddrinfo_proxy,也就是走系統的 DNS 代理;只有 ANDROID_DNS_MODE=local 時才在本行程內自己查。
int getaddrinfo(const char *hostname, const char *servname,
const struct addrinfo *hints, struct addrinfo **res) {
return android_getaddrinfoforiface(hostname, servname, hints, NULL, 0, res);
}
int android_getaddrinfoforiface(const char *hostname, const char *servname,
const struct addrinfo *hints,
const char *iface, int mark,
struct addrinfo **res) {
struct addrinfo sentinel;
struct addrinfo *cur;
int error = 0;
struct addrinfo ai, ai0;
struct addrinfo *pai;
const struct explore *ex;
const char* cache_mode = getenv("ANDROID_DNS_MODE");
/* hostname / servname / hints 都允許為 NULL */
assert(res != NULL);
memset(&sentinel, 0, sizeof(sentinel));
cur = &sentinel;
pai = &ai;
pai->ai_flags = 0;
pai->ai_family = PF_UNSPEC;
pai->ai_socktype = ANY;
pai->ai_protocol = ANY;
pai->ai_addrlen = 0;
pai->ai_canonname = NULL;
pai->ai_addr = NULL;
pai->ai_next = NULL;
if (hostname == NULL && servname == NULL) return EAI_NONAME;
if (hints) {
if (hints->ai_addrlen || hints->ai_canonname || hints->ai_addr || hints->ai_next)
ERR(EAI_BADHINTS);
if (hints->ai_flags & ~AI_MASK) ERR(EAI_BADFLAGS);
switch (hints->ai_family) {
case PF_UNSPEC:
case PF_INET:
#ifdef INET6
case PF_INET6:
#endif
break;
default:
ERR(EAI_FAMILY);
}
memcpy(pai, hints, sizeof(*pai));
}
/* 特殊情況檢查:未指定 socktype/protocol 時不允許數字 servname 等 */
if (MATCH_FAMILY(pai->ai_family, PF_INET, 1)
#ifdef PF_INET6
|| MATCH_FAMILY(pai->ai_family, PF_INET6, 1)
#endif
) {
ai0 = *pai;
if (pai->ai_family == PF_UNSPEC) {
#ifdef PF_INET6
pai->ai_family = PF_INET6;
#else
pai->ai_family = PF_INET;
#endif
}
error = get_portmatch(pai, servname);
if (error) ERR(error);
*pai = ai0;
}
/* hostname 為 NULL 或已是數字形式 */
ai0 = *pai;
for (ex = explore; ex->e_af >= 0; ex++) {
*pai = ai0;
if (ex->e_af == PF_UNSPEC) continue;
if (!MATCH_FAMILY(pai->ai_family, ex->e_af, WILD_AF(ex))) continue;
if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex))) continue;
if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex))) continue;
if (pai->ai_family == PF_UNSPEC) pai->ai_family = ex->e_af;
if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
pai->ai_socktype = ex->e_socktype;
if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
pai->ai_protocol = ex->e_protocol;
if (hostname == NULL)
error = explore_null(pai, servname, &cur->ai_next);
else
error = explore_numeric_scope(pai, hostname, servname, &cur->ai_next);
if (error) goto free;
while (cur->ai_next) cur = cur->ai_next;
}
if (sentinel.ai_next) goto good;
if (hostname == NULL) ERR(EAI_NODATA);
if (pai->ai_flags & AI_NUMERICHOST) ERR(EAI_NONAME);
/* ANDROID CHANGES: 若非 local 模式,把請求轉給 DNS 代理 */
if (cache_mode == NULL || strcmp(cache_mode, "local") != 0) {
return android_getaddrinfo_proxy(hostname, servname, hints, res, iface);
}
/* hostname 是字母名稱,偏好 AF_INET6 優先於 AF_INET */
for (ex = explore; ex->e_af >= 0; ex++) {
*pai = ai0;
if (pai->ai_family != ex->e_af) continue;
if (!MATCH(pai->ai_socktype, ex->e_socktype, WILD_SOCKTYPE(ex))) continue;
if (!MATCH(pai->ai_protocol, ex->e_protocol, WILD_PROTOCOL(ex))) continue;
if (pai->ai_socktype == ANY && ex->e_socktype != ANY)
pai->ai_socktype = ex->e_socktype;
if (pai->ai_protocol == ANY && ex->e_protocol != ANY)
pai->ai_protocol = ex->e_protocol;
error = explore_fqdn(pai, hostname, servname, &cur->ai_next, iface, mark);
while (cur && cur->ai_next) cur = cur->ai_next;
}
if (sentinel.ai_next) error = 0;
if (error) goto free;
if (error == 0) {
if (sentinel.ai_next) {
good:
*res = sentinel.ai_next;
return SUCCESS;
} else {
error = EAI_FAIL;
}
}
free:
bad:
if (sentinel.ai_next) freeaddrinfo(sentinel.ai_next);
*res = NULL;
return error;
}
只要 hook 住 libc.so 的 getaddrinfo,就能拿到完整的 DNS 維度數據:解析耗時、網域名稱解析到哪幾個 IP、是否命中快取,以及解析失敗時的錯誤資訊。而要在眾多呼叫中挑出「真正的 DNS 請求」,判斷依據就是 hints 裡的 ai_flags 與 ai_socktype 組合。
Android 自訂縮放式側滑菜單完整實作
前言 剛接觸 Android 時,我對側滑菜單非常感興趣,也很好奇它的實作原理。隨著技術不斷精進,我也能自己封裝側滑菜單了。網路上雖有眾多現成方案,但本著學習與分享的精神
Android 自定義 Adapter 打造 ListView 的思路與完整程式碼
在開發中,我們經常使用 ListView 這個控制項。Android API 也提供了許多建立適配器的快捷方式,例如 ArrayAdapter、SimpleAdapter
Android Canvas 練習(8):自己繪製環形圖
繼續研究常見圖表的繪製。這次做的是環形圖(Doughnut Chart),原理很單純——大圓套小圓,中間挖空就完成了。 程式碼 package com.xcl.ch
Android 動態佈局實作:在執行期動態加入 TextView 與 ListView
本文以一個完整實例說明如何在 Android 中透過程式碼動態配置介面,重點示範執行期動態加入 TextView 與 ListView 的做法,供需要的朋友參考。核心思路