xref: /aosp_15_r20/system/netd/server/main.cpp (revision 8542734a0dd1db395a4d42aae09c37f3c3c3e7a1)
1 /*
2  * Copyright (C) 2008 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <dirent.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <signal.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <sys/wait.h>
27 #include <chrono>
28 #include <cinttypes>
29 #include <mutex>
30 
31 #define LOG_TAG "Netd"
32 
33 #include "log/log.h"
34 
35 #include <android/binder_manager.h>
36 #include <android/binder_process.h>
37 #include <binder/IPCThreadState.h>
38 #include <binder/IServiceManager.h>
39 #include <hidl/HidlTransportSupport.h>
40 #include <netdutils/Stopwatch.h>
41 #include <processgroup/processgroup.h>
42 
43 #include "Controllers.h"
44 #include "FwmarkServer.h"
45 #include "MDnsService.h"
46 #include "NFLogListener.h"
47 #include "NetdConstants.h"
48 #include "NetdHwAidlService.h"
49 #include "NetdHwService.h"
50 #include "NetdNativeService.h"
51 #include "NetlinkManager.h"
52 #include "Process.h"
53 
54 #include "NetdUpdatablePublic.h"
55 #include "netd_resolv/resolv.h"
56 
57 using android::IPCThreadState;
58 using android::sp;
59 using android::status_t;
60 using android::String16;
61 using android::net::FwmarkServer;
62 using android::net::gCtls;
63 using android::net::gLog;
64 using android::net::makeNFLogListener;
65 using android::net::MDnsService;
66 using android::net::NetdHwService;
67 using android::net::NetdNativeService;
68 using android::net::NetlinkManager;
69 using android::net::NFLogListener;
70 using android::net::aidl::NetdHwAidlService;
71 using android::netdutils::Stopwatch;
72 
73 const char* const PID_FILE_PATH = "/data/misc/net/netd_pid";
74 constexpr const char DNSPROXYLISTENER_SOCKET_NAME[] = "dnsproxyd";
75 
76 std::mutex android::net::gBigNetdLock;
77 
78 namespace {
79 
getNetworkContextCallback(uint32_t netId,uint32_t uid,android_net_context * netcontext)80 void getNetworkContextCallback(uint32_t netId, uint32_t uid, android_net_context* netcontext) {
81     gCtls->netCtrl.getNetworkContext(netId, uid, netcontext);
82 }
83 
checkCallingPermissionCallback(const char * permission)84 bool checkCallingPermissionCallback(const char* permission) {
85     return checkCallingPermission(String16(permission));
86 }
87 
logCallback(const char * msg)88 void logCallback(const char* msg) {
89     gLog.info(std::string(msg));
90 }
91 
tagSocketCallback(int sockFd,uint32_t tag,uid_t uid,pid_t)92 int tagSocketCallback(int sockFd, uint32_t tag, uid_t uid, pid_t) {
93     // Workaround for secureVPN with VpnIsolation enabled, refer to b/159994981 for details.
94     if (tag == TAG_SYSTEM_DNS) uid = AID_DNS;
95     return libnetd_updatable_tagSocket(sockFd, tag, uid, AID_DNS);
96 }
97 
evaluateDomainNameCallback(const android_net_context & netcontext,const char *)98 bool evaluateDomainNameCallback(const android_net_context& netcontext, const char* /*name*/) {
99     // OEMs should NOT modify IF statement, or DNS control provided by mainline modules may break.
100     if (!gCtls->netCtrl.isUidAllowed(netcontext.app_netid, netcontext.uid)) {
101         ALOGI("uid %d is not allowed to use netid %u", netcontext.uid, netcontext.app_netid);
102         return false;
103     }
104 
105     // Add OEM customization from here
106     // ...
107     return true;
108 }
109 
initDnsResolver()110 bool initDnsResolver() {
111     ResolverNetdCallbacks callbacks = {
112             .check_calling_permission = &checkCallingPermissionCallback,
113             .get_network_context = &getNetworkContextCallback,
114             .log = &logCallback,
115             .tagSocket = &tagSocketCallback,
116             .evaluate_domain_name = &evaluateDomainNameCallback,
117     };
118     return resolv_init(&callbacks);
119 }
120 
121 }  // namespace
122 
main()123 int main() {
124     Stopwatch s;
125     gLog.info("netd 1.0 starting");
126 
127     android::net::process::removePidFile(PID_FILE_PATH);
128     gLog.info("Pid file removed");
129     android::net::process::blockSigPipe();
130     gLog.info("SIGPIPE is blocked");
131 
132     // Before we do anything that could fork, mark CLOEXEC the UNIX sockets that we get from init.
133     // FrameworkListener does this on initialization as well, but we only initialize these
134     // components after having initialized other subsystems that can fork.
135     for (const auto& sock : {DNSPROXYLISTENER_SOCKET_NAME, FwmarkServer::SOCKET_NAME}) {
136         setCloseOnExec(sock);
137         gLog.info("setCloseOnExec(%s)", sock);
138     }
139 
140     std::string cg2_path;
141     if (!CgroupGetControllerPath(CGROUPV2_HIERARCHY_NAME, &cg2_path)) {
142         ALOGE("Failed to find cgroup v2 root %s", strerror(errno));
143         exit(1);
144     }
145 
146     if (libnetd_updatable_init(cg2_path.c_str())) {
147         ALOGE("libnetd_updatable_init failed");
148         exit(1);
149     }
150     gLog.info("libnetd_updatable_init success");
151 
152     NetlinkManager *nm = NetlinkManager::Instance();
153     if (nm == nullptr) {
154         ALOGE("Unable to create NetlinkManager");
155         exit(1);
156     };
157     gLog.info("NetlinkManager instanced");
158 
159     gCtls = new android::net::Controllers();
160     gCtls->init();
161 
162     if (nm->start()) {
163         ALOGE("Unable to start NetlinkManager (%s)", strerror(errno));
164         exit(1);
165     }
166 
167     std::unique_ptr<NFLogListener> logListener;
168     {
169         auto result = makeNFLogListener();
170         if (!isOk(result)) {
171             ALOGE("Unable to create NFLogListener: %s", toString(result).c_str());
172             exit(1);
173         }
174         logListener = std::move(result.value());
175         auto status = gCtls->wakeupCtrl.init(logListener.get());
176         if (!isOk(status)) {
177             gLog.error("Unable to init WakeupController: %s", toString(status).c_str());
178             // We can still continue without wakeup packet logging.
179         }
180     }
181 
182     // Set local DNS mode, to prevent bionic from proxying
183     // back to this service, recursively.
184     // TODO: Check if we could remove it since resolver cache no loger
185     // checks this environment variable after aosp/838050.
186     setenv("ANDROID_DNS_MODE", "local", 1);
187     // Note that only call initDnsResolver after gCtls initializing.
188     if (!initDnsResolver()) {
189         ALOGE("Unable to init resolver");
190         exit(1);
191     }
192 
193     FwmarkServer fwmarkServer(&gCtls->netCtrl, &gCtls->eventReporter);
194     if (fwmarkServer.startListener()) {
195         ALOGE("Unable to start FwmarkServer (%s)", strerror(errno));
196         exit(1);
197     }
198 
199     Stopwatch subTime;
200     status_t ret;
201     if ((ret = NetdNativeService::start()) != android::OK) {
202         ALOGE("Unable to start NetdNativeService: %d", ret);
203         exit(1);
204     }
205     gLog.info("Registering NetdNativeService: %" PRId64 "us", subTime.getTimeAndResetUs());
206 
207     if ((ret = MDnsService::start()) != android::OK) {
208         ALOGE("Unable to start MDnsService: %d", ret);
209         exit(1);
210     }
211     gLog.info("Registering MDnsService: %" PRId64 "us", subTime.getTimeAndResetUs());
212 
213     android::net::process::ScopedPidFile pidFile(PID_FILE_PATH);
214 
215     // Now that netd is ready to process commands, advertise service availability for HAL clients.
216     // Usage of this HAL is anticipated to be thin; one thread per HAL service should suffice,
217     // AIDL and HIDL.
218     android::hardware::configureRpcThreadpool(2, true /* callerWillJoin */);
219     IPCThreadState::self()->disableBackgroundScheduling(true);
220 
221     std::thread aidlService = std::thread(NetdHwAidlService::run);
222 
223     sp<NetdHwService> mHwSvc(new NetdHwService());
224     bool startedHidlService = true;
225     if ((ret = mHwSvc->start()) != android::OK) {
226         ALOGE("Unable to start HIDL NetdHwService: %d", ret);
227         startedHidlService = false;
228     }
229 
230     gLog.info("Registering NetdHwService: %" PRId64 "us", subTime.getTimeAndResetUs());
231     gLog.info("Netd started in %" PRId64 "us", s.timeTakenUs());
232     if (startedHidlService) {
233         IPCThreadState::self()->joinThreadPool();
234     }
235     aidlService.join();
236     gLog.info("netd exiting");
237 
238     exit(0);
239 }
240