当前位置: 首页 > article >正文

Android10 rk3399 以太网接入流程分析

Netd守护进程服务

  • Netd模块是Android中专门负责网络管理和控制的后台守护进程
  • 开发板路径./etc/init/netd.rc
service netd /system/bin/netd
    class main
    socket dnsproxyd stream 0660 root inet
    socket mdns stream 0660 root system
    socket fwmarkd stream 0660 root inet
    onrestart restart zygote
    onrestart restart zygote_secondary
    # b/121354779: netd itself is not updatable, but on startup it dlopen()s the resolver library
    # from the DNS resolver APEX. Mark it as updatable so init won't start it until all APEX
    # packages are ready.
    updatable
~

Netd源码分析

system\netd\server\main.cpp

int main() {
    Stopwatch s;
    gLog.info("netd 1.0 starting");

    android::net::process::removePidFile(PID_FILE_PATH);
    android::net::process::blockSigPipe();

    // Before we do anything that could fork, mark CLOEXEC the UNIX sockets that we get from init.
    // FrameworkListener does this on initialization as well, but we only initialize these
    // components after having initialized other subsystems that can fork.
    for (const auto& sock :
         {DNSPROXYLISTENER_SOCKET_NAME, FwmarkServer::SOCKET_NAME, MDnsSdListener::SOCKET_NAME}) {
        setCloseOnExec(sock);
    }

    // Before we start any threads, populate the resolver stub pointers.
    resolv_stub_init();

    // Make sure BPF programs are loaded before doing anything
    while (!android::base::WaitForProperty("bpf.progs_loaded", "1",
           std::chrono::seconds(5))) {
        ALOGD("netd waited 5s for bpf.progs_loaded, still waiting...");
    }

    NetlinkManager *nm = NetlinkManager::Instance();
    if (nm == nullptr) {
        ALOGE("Unable to create NetlinkManager");
        exit(1);
    };

这里会实例NetlinkManager,用来管理网络,同时会实例NetlinkHandler 用于处理网络消息
/system/netd/server/NetlinkManager.cpp

NetlinkHandler *NetlinkManager::setupSocket(int *sock, int netlinkFamily,
    int groups, int format, bool configNflog) {

·········
·········
    NetlinkHandler *handler = new NetlinkHandler(this, *sock, format);
    if (handler->start()) {
        ALOGE("Unable to start NetlinkHandler: %s", strerror(errno));
        close(*sock);
        return nullptr;
    }

    return handler;
}

NetlinkHandler 网络的变化都会在onEvent里处理

system/netd/server/NetlinkHandler.cpp

····
····
void NetlinkHandler::onEvent(NetlinkEvent *evt) {
    const char *subsys = evt->getSubsystem();
    if (!subsys) {
        ALOGW("No subsystem found in netlink event");
        return;
    }

    if (!strcmp(subsys, "net")) {
        NetlinkEvent::Action action = evt->getAction();
        const char *iface = evt->findParam("INTERFACE");
        if ((action == NetlinkEvent::Action::kAdd) ||
            (action == NetlinkEvent::Action::kLinkUp) ||
            (action == NetlinkEvent::Action::kLinkDown)) {
            const char *ifIndex = evt->findParam("IFINDEX");
            long ifaceIndex = parseIfIndex(ifIndex);
            if (ifaceIndex) {
                gCtls->trafficCtrl.addInterface(iface, ifaceIndex);
            } else {
                ALOGE("invalid interface index: %s(%s)", iface, ifIndex);
            }
        }

        if (action == NetlinkEvent::Action::kAdd) {
            notifyInterfaceAdded(iface);
        } else if (action == NetlinkEvent::Action::kRemove) {
            notifyInterfaceRemoved(iface);
        } else if (action == NetlinkEvent::Action::kChange) {
            evt->dump();
            notifyInterfaceChanged("nana", true);
        } else if (action == NetlinkEvent::Action::kLinkUp) {
        ALOGW("zzz klinkup");
            notifyInterfaceLinkChanged(iface, true);
        } else if (action == NetlinkEvent::Action::kLinkDown) {
        ALOGW("zzz klinkdown");
            notifyInterfaceLinkChanged(iface, false);
····
····
            }

./system/netd/server/binder/android/net/INetdUnsolicitedEventListener.aidl

void NetlinkHandler::notifyInterfaceLinkChanged(const std::string& ifName, bool up) {
    LOG_EVENT_FUNC(BINDER_RETRY, onInterfaceLinkStateChanged, ifName, up);
}

./frameworks/base/services/core/java/com/android/server/NetworkManagementService.java
onInterfaceLinkStateChanged

   public void onInterfaceLinkStateChanged(String ifName, boolean up)
 		throws RemoteException {
 		Slog.e(TAG, "zzz onInterfaceLinkStateChanged    " + ifName + up);
 		mDaemonHandler.post(() -> notifyInterfaceLinkStateChanged(ifName, up));
 }

system/netd/server/NetlinkHandler.cpp

//LOG_EVENT_FUNC 宏是一个灵活的工具,用于记录网络事件相关的日志,并结合重试机制来决定是否执行日志记录。
//它通过遍历事件监听器,调用指定的函数,并根据执行结果决定是否记录日志,支持动态的日志内容和自动的执行时间计算。
void NetlinkHandler::notifyInterfaceLinkChanged(const std::string& ifName, bool up) {
    LOG_EVENT_FUNC(BINDER_RETRY, onInterfaceLinkStateChanged, ifName, up);
}

system/netd/server/binder/android/net/INetdUnsolicitedEventListener.aidl

oneway interface INetdUnsolicitedEventListener {
··········
/**
¦* Notifies that the link state of the specific interface has changed.
¦*
¦* @param ifName the name of the interface whose link state has changed
¦* @param up true for interface link state up, false for link state down
¦*/
void onInterfaceLinkStateChanged(@utf8InCpp String ifName, boolean up);
······
·····
public class NetworkManagementService extends INetworkManagementService.Stub {
·····
private void invokeForAllObservers(NetworkManagementEventCallback eventCallback) {
.........
/**
 ¦* Notify our observers of an interface link state change
 ¦* (typically, an Ethernet cable has been plugged-in or unplugged).
 ¦*/
 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
 ¦   invokeForAllObservers(o -> o.interfaceLinkStateChanged(iface, up));
 }
.........

frameworks/opt/net/ethernet/java/com/android/server/ethernet/EthernetTracker.java

   private class InterfaceObserver extends BaseNetworkObserver {

        @Override
        public void interfaceLinkStateChanged(String iface, boolean up) {
            if (DBG) {
                Log.i(TAG, "interfaceLinkStateChanged, iface: " + iface + ", up: " + up);
            }
            if(isEthernetInterfaceActive())
                mHandler.post(() -> updateInterfaceState(iface, up));
            mHandler.post(() -> mEthernetNetworkFactoryExt.interfaceLinkStateChanged(iface, up));
        }

        @Override
        public void interfaceAdded(String iface) {
            mHandler.post(() -> maybeTrackInterface(iface));
            mHandler.post(() -> mEthernetNetworkFactoryExt.interfaceAdded(iface));
        }

        @Override
        public void interfaceRemoved(String iface) {
            mHandler.post(() -> removeInterface(iface));
            mHandler.post(() -> mEthernetNetworkFactoryExt.interfaceRemoved(iface));
        }
    }

这段代码定义了一个名为 InterfaceObserver 的类,它继承自 BaseNetworkObserver
并重写了 BaseNetworkObserver 中的三个方法:interfaceLinkStateChanged、interfaceAdded 和 interfaceRemoved。这些方法用于监听网络接口的状态变化,并根据变化做相应的处理。
具体来说,这些方法会在网络接口状态发生变化时调用,并通过 mHandler 将相应的操作(如更新接口状态、添加或移除接口)异步地提交到主线程进行处理


http://www.kler.cn/a/450211.html

相关文章:

  • 软件测试之测试用例
  • 完整微服务设计 功能实现
  • Windows、CentOS环境下搭建自己的版本管理资料库:GitBlit
  • 【uni-app】2025最新uni-app一键登录保姆级教程(包含前后端获取手机号方法)(超强避坑指南)
  • Redis篇--常见问题篇6--缓存一致性1(Mysql和Redis缓存一致,更新数据库删除缓存策略)
  • 华为EC6108V9/C 通刷固件包,内含高安版及详细教程
  • Pyqt6的tableWidget填充数据
  • 《Python 解释器和 PyCharm 详解》
  • 不写一行代码,通义灵码 5 分钟“手撕”年会抽奖程序
  • 新纪天工 开物焕彩:重大科技成就发布会参会感
  • 【Ubuntu 20.04】notepad++的安装与汉化
  • Pytorch | 利用FGSM针对CIFAR10上的ResNet分类器进行对抗攻击
  • 【汇编语言】端口 —— 「从端口到时间:一文了解CMOS RAM与汇编指令的交汇」
  • 一文解释清楚OpenHarmony面向全场景的分布式操作系统
  • Java重要面试名词整理(一):MySQLJVMTomcat
  • RunCam WiFiLink连接手机图传测试
  • 深度剖析CRM系统:什么是CRM系统?有什么用?企业该如何选择?
  • 【读书笔记】《论语别裁》爱与罪
  • (补)算法刷题Day25:BM62 斐波那契数列
  • Python结合一些常见的自然语言处理库来实现根据提示生成作文
  • 基于单片机的噪音检测系统(论文+源码)
  • nodejs创建ws服务器,前端浏览器用websocket接收信息和发送信息给服务端
  • LeetCode 206. 反转链表 (C++实现)
  • Yolo11改进策略:Block改进|使用FastVit的RepMixerBlock改进Yolo11,重参数重构助力Yolo11涨点(全网首发)
  • 系统思考—全局思维
  • 深度学习-77-大模型量化之Post Training Quantization训练后量化PTQ