Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 熱點連接管理(一):追一個客戶端是怎麼被發現的

編輯:關於 Android 程式設計

手機上的 Wi-Fi 功能多半被當成客戶端在用,反過來做 AP 分享網路的場景少得多。

最近做了一個嘗試:把所有試圖連上 Android 便攜熱點的客戶端資訊,從底層一路往上報,最後開一個 API 給上層應用呼叫。出發點很簡單——原生 Android 裡雖然已經有 WifiDevice 這個類別來描述已連上熱點的客戶端,但它只覆蓋了「連成功」的那一群,像是以錯誤密碼嘗試過的裝置就完全看不到。

先看 WifiDevice 長什麼樣

/**
 * Describes information about a detected Wi-Fi STA.
 * {@hide}
 */
public class WifiDevice implements Parcelable {

    /** 裝置 MAC 位址,是 Wi-Fi STA 的唯一識別 */
    public String deviceAddress = "";

    /** 裝置名稱,人類可讀的字串 */
    public String deviceName = "";

    /** 裝置狀態 */
    public int deviceState = 0;

    public static final int DISCONNECTED = 0;
    public static final int CONNECTED = 1;
    public static final int BLACKLISTED = 2;

    private static final String AP_STA_CONNECTED_STR = "AP-STA-CONNECTED";
    private static final String AP_STA_DISCONNECTED_STR = "AP-STA-DISCONNECTED";
    private static final String AP_STA_REPORT_STR = "AP-STA-REPORT";

    /** {@hide} */
    public WifiDevice() {}

    /**
     * @param string 支援的格式包含
     *     AP-STA-CONNECTED 42:fc:89:a8:96:09
     *     AP-STA-DISCONNECTED 42:fc:89:a8:96:09
     * 註:這些事件格式可以在 hostapd 的程式碼中找到
     * @hide
     */
    public WifiDevice(String dataString) throws IllegalArgumentException {
        String[] tokens = dataString.split(" ");
        if (tokens.length < 2) {
            throw new IllegalArgumentException();
        }
        if (tokens[0].indexOf(AP_STA_CONNECTED_STR) != -1) {
            deviceState = CONNECTED;
        } else if (tokens[0].indexOf(AP_STA_DISCONNECTED_STR) != -1) {
            deviceState = DISCONNECTED;
        } else if (tokens[0].indexOf(AP_STA_REPORT_STR) != -1) {
            deviceState = BLACKLISTED;
        } else {
            throw new IllegalArgumentException();
        }
        deviceAddress = tokens[1];
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof WifiDevice)) {
            return false;
        }
        WifiDevice other = (WifiDevice) obj;
        if (deviceAddress == null) {
            return (other.deviceAddress == null);
        } else {
            return deviceAddress.equals(other.deviceAddress);
        }
    }

    /** Implement the Parcelable interface {@hide} */
    public int describeContents() {
        return 0;
    }

    /** Implement the Parcelable interface {@hide} */
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(deviceAddress);
        dest.writeString(deviceName);
        dest.writeInt(deviceState);
    }

    /** Implement the Parcelable interface {@hide} */
    public static final Creator<WifiDevice> CREATOR = new Creator<WifiDevice>() {
        public WifiDevice createFromParcel(Parcel in) {
            WifiDevice device = new WifiDevice();
            device.deviceAddress = in.readString();
            device.deviceName = in.readString();
            device.deviceState = in.readInt();
            return device;
        }

        public WifiDevice[] newArray(int size) {
            return new WifiDevice[size];
        }
    };
}

比起其它複雜的類別,WifiDevice.java 相當樸素,只有幾個成員變數與方法。它代表一個已接入熱點的客戶端,內容不外乎 MAC 位址、主機名與接入狀態——一般情況下我們需要知道的也就這些。

但問題來了:WifiDevice 只能描述「已經正常接入」的客戶端。那些曾經嘗試連線、卻因為密碼錯誤等原因失敗的裝置呢?如果我們希望掌握周邊所有曾和熱點打過照面的客戶端,資訊該從哪裡撈?

正常接入的客戶端是怎麼被發現的

先把上面的問題放一放,看看現有的機制怎麼運作。核心在 Tethering.java(\frameworks\base\services\core\java\com\android\server\connectivity\Tethering.java)。

tether 這個字本意是「拴繩、拴住」,在這裡可以理解成「分享」:WIFI_TETHERING 是用 Wi-Fi 分享網路,USB_TETHERING 是用 USB 分享網路。讀完 Tethering 的程式碼不難看出,這個類別就是負責網路共享服務,涵蓋 USB、藍牙與 Wi-Fi 三種。

要注意的是,直接談 Tethering 其實跳過了 ConnectivityService。上層取得客戶端資訊的路徑是:ConnectivityManager 呼叫 ConnectivityService 的方法,最終落到 Tethering 的 getTetherConnectedSta()。

public List<WifiDevice> getTetherConnectedSta() {
    Iterator it;
    List<WifiDevice> TetherConnectedStaList = new ArrayList<WifiDevice>();

    if (mContext.getResources().getBoolean(com.android.internal.R.bool.config_softap_extention)) {
        it = mConnectedDeviceMap.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            WifiDevice device = (WifiDevice) mConnectedDeviceMap.get(key);
            if (VDBG) {
                Log.d(TAG, "getTetherConnectedSta: addr=" + key + " name=" + device.deviceName);
            }
            TetherConnectedStaList.add(device);
        }
    }
    return TetherConnectedStaList;
}

仔細看,無非是在 Tethering 裡維護了一個 mConnectedDeviceMap,專門存放接入的客戶端:

private HashMap<String, WifiDevice> mConnectedDeviceMap = new HashMap<String, WifiDevice>();

更新這個 HashMap 的地方有兩處。邏輯其實一樣:一處是已經握有該裝置 IP 資訊的情況,另一處是還沒有、於是啟動 DnsmasqThread 去向 dnsmasq 撈 IP,撈到之後再把這個 WifiDevice 存進 HashMap。兩條路徑都源自 interfaceMessageRecevied(String message)。

先看 DnsmasqThread:

private static class DnsmasqThread extends Thread {
    private final Tethering mTethering;
    private int mInterval;
    private int mMaxTimes;
    private WifiDevice mDevice;

    public DnsmasqThread(Tethering tethering, WifiDevice device, int interval, int maxTimes) {
        super("Tethering");
        mTethering = tethering;
        mInterval = interval;
        mMaxTimes = maxTimes;
        mDevice = device;
    }

    public void run() {
        boolean result = false;
        try {
            while (mMaxTimes > 0) {
                result = mTethering.readDeviceInfoFromDnsmasq(mDevice);
                if (result) {
                    if (DBG) Log.d(TAG, "Successfully poll device info for " + mDevice.deviceAddress);
                    break;
                }
                mMaxTimes--;
                Thread.sleep(mInterval);
            }
        } catch (Exception ex) {
            result = false;
            Log.e(TAG, "Pulling " + mDevice.deviceAddress + " error " + ex);
        }

        if (!result) {
            if (DBG) Log.d(TAG, "Pulling timeout, suppose STA uses static ip " + mDevice.deviceAddress);
        }

        // STA 使用靜態 IP 時,dnsmasq 拿不到裝置資訊,
        // 因此無論成功或失敗都要送出廣播。
        // 但若裝置已不在 L2 連線狀態,代表 hostapd 連線在 dnsmasq 取得資訊前就斷了,
        // 這種情況就不該再送連線事件。
        WifiDevice other = mTethering.mL2ConnectedDeviceMap.get(mDevice.deviceAddress);
        if (other != null && other.deviceState == WifiDevice.CONNECTED) {
            mTethering.mConnectedDeviceMap.put(mDevice.deviceAddress, mDevice);
            mTethering.sendTetherConnectStateChangedBroadcast();
        } else {
            if (DBG) Log.d(TAG, "Device " + mDevice.deviceAddress + " already disconnected, ignoring");
        }
    }
}

再看 interfaceMessageRecevied:

public void interfaceMessageRecevied(String message) {
    // 若 softap extension 功能未啟用,直接返回
    if (!mContext.getResources().getBoolean(com.android.internal.R.bool.config_softap_extention)) {
        return;
    }
    if (DBG) Log.d(TAG, "interfaceMessageRecevied: message=" + message);

    try {
        WifiDevice device = new WifiDevice(message);
        if (device.deviceState == WifiDevice.CONNECTED) {
            mL2ConnectedDeviceMap.put(device.deviceAddress, device);

            // hostapd 報出 STA 連線事件時,裝置資訊有可能還無法從 dnsmasq 取得,
            // 此時啟動一個執行緒去輪詢,資訊可用後執行緒自行退出。
            // 靜態 IP 的情況下 dnsmasq 不持有裝置資訊,執行緒會在逾時後退出。
            if (readDeviceInfoFromDnsmasq(device)) {
                mConnectedDeviceMap.put(device.deviceAddress, device);
                sendTetherConnectStateChangedBroadcast();
            } else {
                if (DBG) Log.d(TAG, "Starting poll device info for " + device.deviceAddress);
                new DnsmasqThread(this, device, DNSMASQ_POLLING_INTERVAL, DNSMASQ_POLLING_MAX_TIMES).start();
            }
        } else if (device.deviceState == WifiDevice.DISCONNECTED) {
            mL2ConnectedDeviceMap.remove(device.deviceAddress);
            mConnectedDeviceMap.remove(device.deviceAddress);
            sendTetherConnectStateChangedBroadcast();
        }
        // ...

關鍵就在這裡:入參 message 本身就攜帶了客戶端資訊。那它是誰送來的?往上一層看,是 NetworkManagementService.java 的 notifyInterfaceMessage(String message)。

/**
 * Notify our observers of a change in the data activity state of the interface
 */
private void notifyInterfaceMessage(String message) {
    final int length = mObservers.beginBroadcast();
    for (int i = 0; i < length; i++) {
        try {
            mObservers.getBroadcastItem(i).interfaceMessageRecevied(message);
        } catch (RemoteException e) {
        } catch (RuntimeException e) {
        }
    }
    mObservers.finishBroadcast();
}

而它的上一層,同樣在 NetworkManagementService 中,是 NetdCallbackReceiver 收到 Event 之後依事件型別分派處理的。

case NetdResponseCode.InterfaceMessage:
    /*
     * An message arrived in network interface.
     * Format: "NNN IfaceMessage <3>AP-STA-CONNECTED 00:08:22:64:9d:84"
     */
    if (cooked.length < 3 || !cooked[1].equals("IfaceMessage")) {
        throw new IllegalStateException(errorMessage);
    }
    Slog.d(TAG, "onEvent: " + raw);
    if (cooked[4] != null) {
        notifyInterfaceMessage(cooked[3] + " " + cooked[4]);
    } else {
        notifyInterfaceMessage(cooked[3]);
    }
    return true;

從註解中的格式 "NNN IfaceMessage <3>AP-STA-CONNECTED 00:08:22:64:9d:84" 就能對上前面 WifiDevice 解析字串的方式。

再往下:InterfaceMessage 從哪來

這一層直接跳到 HAL 層的 Netd 進程。做過 Android 數據卡、啟動軟 AP 的人對 Netd 與 Softap 這些指令應該不陌生,都很好用。訊息的源頭是 SoftapController:

void *SoftapController::threadStart(void *obj) {
    SoftapController *me = reinterpret_cast<SoftapController>(obj);
    struct wpa_ctrl *ctrl;
    int count = 0;
    ALOGD("SoftapController::threadStart...");

    DIR *dir = NULL;
    dir = opendir(HOSTAPD_SOCKETS_DIR);
    if (NULL == dir && errno == ENOENT) {
        mkdir(HOSTAPD_SOCKETS_DIR, S_IRWXU|S_IRWXG|S_IRWXO);
        chown(HOSTAPD_SOCKETS_DIR, AID_WIFI, AID_WIFI);
        chmod(HOSTAPD_SOCKETS_DIR, S_IRWXU|S_IRWXG);
    } else {
        if (dir != NULL) {
            /* 目錄已存在 */
            ALOGD("%s already exists", HOSTAPD_SOCKETS_DIR);
            closedir(dir);
        }
        if (errno == EACCES) {
            ALOGE("Cant open %s , check permissions ", HOSTAPD_SOCKETS_DIR);
        }
    }
    chmod(HOSTAPD_DHCP_DIR, S_IRWXU|S_IRWXG|S_IRWXO);

    ctrl = wpa_ctrl_open(HOSTAPD_UNIX_FILE);
    while (ctrl == NULL) {
        /*
         * 嘗試透過 wpa_ctrl 介面連上 hostapd。
         * 連線過程中 hostapd 有可能已經有 STA 接進來了,
         * 這裡把 sleep 時間設成合適的值,降低漏接 STA-CONNECTED 訊息的機率。
         */
        usleep(20000);
        ctrl = wpa_ctrl_open(HOSTAPD_UNIX_FILE);
        if (ctrl != NULL || count >= 150) {
            break;
        }
        count++;
    }

    if (count == 150 && ctrl == NULL) {
        ALOGE("Connection to hostapd Error.");
        return NULL;
    }

    if (wpa_ctrl_attach(ctrl) != 0) {
        wpa_ctrl_close(ctrl);
        ALOGE("Attach to hostapd Error.");
        return NULL;
    }

    while (me->mHostapdFlag) {
        int res = 0;
        char buf[256];
        char dest_str[300];

        while (wpa_ctrl_pending(ctrl)) {
            size_t len = sizeof(buf) - 1;
            res = wpa_ctrl_recv(ctrl, buf, &len);
            if (res == 0) {
                buf[len] = '\0';
                ALOGD("Get event from hostapd (%s)", buf);
                memset(dest_str, 0x0, sizeof(dest_str));
                snprintf(dest_str, sizeof(dest_str), "IfaceMessage active %s", buf);
                me->mSpsl->sendBroadcast(ResponseCode::InterfaceMessage, dest_str, false);
            } else {
                break;
            }
        }
        if (res < 0) {
            break;
        }
        sleep(2);
    }

    wpa_ctrl_detach(ctrl);
    wpa_ctrl_close(ctrl);
    return NULL;
}

這一段到底怎麼和 Netd 溝通,我還沒徹底弄明白,但不影響理解整體流程——肯定是透過 socket 之類的方式把 InterfaceMessage 送出去,字串內容就存在 dest_str 裡。抓一段 logcat 就能看到實際格式是 "IfaceMessage active <3>AP-STA-CONNECTED 00:0a:f5:8a:be:58",和前面的格式說明完全對得上。

源頭:hostapd 的 ap_sta_set_authorized

再往前追,SoftapController 的訊息來自 hostapd。(hostapd 本身又是一個大分支,這裡略過,可以把它理解成樞紐:接收來自 Wi-Fi 驅動的底層訊息,處理後分類通知上層。)

訊息是從 sta_info.c 的 ap_sta_set_authorized(struct hostapd_data *hapd, struct sta_info *sta, int authorized) 發出的,主要負責送出 connect 與 disconnect。判斷依據是 sta->flags & WLAN_STA_AUTHORIZED:鑒權通過就送 connect,沒通過就送 disconnect。

void ap_sta_set_authorized(struct hostapd_data *hapd, struct sta_info *sta, int authorized) {
    const u8 *dev_addr = NULL;
    char buf[100];
#ifdef CONFIG_P2P
    u8 addr[ETH_ALEN];
#endif /* CONFIG_P2P */

    if (!!authorized == !!(sta->flags & WLAN_STA_AUTHORIZED))
        return;

#ifdef CONFIG_P2P
    if (hapd->p2p_group == NULL) {
        if (sta->p2p_ie != NULL && p2p_parse_dev_addr_in_p2p_ie(sta->p2p_ie, addr) == 0)
            dev_addr = addr;
    } else {
        dev_addr = p2p_group_get_dev_addr(hapd->p2p_group, sta->addr);
    }
#endif /* CONFIG_P2P */

    if (dev_addr)
        os_snprintf(buf, sizeof(buf), MACSTR " p2p_dev_addr=" MACSTR,
                    MAC2STR(sta->addr), MAC2STR(dev_addr));
    else
        os_snprintf(buf, sizeof(buf), MACSTR, MAC2STR(sta->addr));

    if (authorized) {
        wpa_msg(hapd->msg_ctx, MSG_INFO, AP_STA_CONNECTED "%s", buf);
        if (hapd->msg_ctx_parent && hapd->msg_ctx_parent != hapd->msg_ctx)
            wpa_msg_no_global(hapd->msg_ctx_parent, MSG_INFO, AP_STA_CONNECTED "%s", buf);
        sta->flags |= WLAN_STA_AUTHORIZED;
    } else {
        wpa_msg(hapd->msg_ctx, MSG_INFO, AP_STA_DISCONNECTED "%s", buf);
        if (hapd->msg_ctx_parent && hapd->msg_ctx_parent != hapd->msg_ctx)
            wpa_msg_no_global(hapd->msg_ctx_parent, MSG_INFO, AP_STA_DISCONNECTED "%s", buf);
        sta->flags &= ~WLAN_STA_AUTHORIZED;
    }

    if (hapd->sta_authorized_cb)
        hapd->sta_authorized_cb(hapd->sta_authorized_cb_ctx, sta->addr, authorized, dev_addr);
}

一開始只看到這裡會發訊息,卻不知道怎麼發,直到去翻了 wpa_msg() 的實作才弄清楚:

void wpa_msg(void *ctx, int level, const char *fmt, ...)
{
    va_list ap;
    char *buf;
    int buflen;
    int len;
    char prefix[130];

    va_start(ap, fmt);
    buflen = vsnprintf(NULL, 0, fmt, ap) + 1;
    va_end(ap);

    buf = os_malloc(buflen);
    if (buf == NULL) {
        wpa_printf(MSG_ERROR, "wpa_msg: Failed to allocate message buffer");
        return;
    }

    va_start(ap, fmt);
    prefix[0] = '\0';
    if (wpa_msg_ifname_cb) {
        const char *ifname = wpa_msg_ifname_cb(ctx);
        if (ifname) {
            int res = os_snprintf(prefix, sizeof(prefix), "%s: ", ifname);
            if (res < 0 || res >= (int) sizeof(prefix))
                prefix[0] = '\0';
        }
    }
    len = vsnprintf(buf, buflen, fmt, ap);
    va_end(ap);

    wpa_printf(level, "%s%s", prefix, buf);

    if (wpa_msg_cb) {
        wpa_msg_cb(ctx, level, 0, buf, len);
    }

    os_free(buf);
}

注意最後那個全域變數 wpa_msg_cb。在 hostapd_ctrl_iface_init(struct hostapd_data *hapd) 初始化的時候,會看到這兩行:

hapd->msg_ctx = hapd;
wpa_msg_register_cb(hostapd_ctrl_iface_msg_cb);

這裡註冊了一個回呼 hostapd_ctrl_iface_msg_cb(void *ctx, int level, int global, const char *txt, size_t len),而它內部又呼叫了 hostapd_ctrl_iface_send(...)。

那它和 wpa_msg_cb 又是什麼關係?看 wpa_msg_register_cb 就明白了——它做的事就是把註冊進來的函式指標賦給 wpa_msg_cb:

void wpa_msg_register_cb(wpa_msg_cb_func func)
{
    wpa_msg_cb = func;
}

於是整條鏈就串起來了:hostapd 判定鑒權結果 → wpa_msg 觸發回呼 → hostapd_ctrl_iface_send 把訊息送出去 → SoftapController 收到後包成 IfaceMessage 廣播 → Netd 轉發 → NetworkManagementService 分派 → Tethering.interfaceMessageRecevied 解析成 WifiDevice → 存入 mConnectedDeviceMap → 上層就能讀到。

以上是 framework 端接收到客戶端連線成功並取得資訊的完整流程。補充一句,我當初是反著看的——先讀 hostapd 送訊息那段,再回頭看上層,反而更容易把細節串起來。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved