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 <binder/IPCThreadState.h>
36 #include <binder/IServiceManager.h>
37 #include <libbpf_android.h>
38 #include <netdutils/Stopwatch.h>
39 
40 #include "Controllers.h"
41 #include "FwmarkServer.h"
42 #include "MDnsSdListener.h"
43 #include "NFLogListener.h"
44 #include "NetdConstants.h"
45 #include "NetdHwService.h"
46 #include "NetdNativeService.h"
47 #include "NetlinkManager.h"
48 #include "Process.h"
49 
50 #include "netd_resolv/resolv.h"
51 
52 using android::IPCThreadState;
53 using android::sp;
54 using android::status_t;
55 using android::String16;
56 using android::net::FwmarkServer;
57 using android::net::gCtls;
58 using android::net::gLog;
59 using android::net::makeNFLogListener;
60 using android::net::NetdHwService;
61 using android::net::NetdNativeService;
62 using android::net::NetlinkManager;
63 using android::net::NFLogListener;
64 using android::netdutils::Stopwatch;
65 
66 const char* const PID_FILE_PATH = "/data/misc/net/netd_pid";
67 constexpr const char DNSPROXYLISTENER_SOCKET_NAME[] = "dnsproxyd";
68 
69 std::mutex android::net::gBigNetdLock;
70 
71 namespace {
72 
getNetworkContextCallback(uint32_t netId,uint32_t uid,android_net_context * netcontext)73 void getNetworkContextCallback(uint32_t netId, uint32_t uid, android_net_context* netcontext) {
74     gCtls->netCtrl.getNetworkContext(netId, uid, netcontext);
75 }
76 
checkCallingPermissionCallback(const char * permission)77 bool checkCallingPermissionCallback(const char* permission) {
78     return checkCallingPermission(String16(permission));
79 }
80 
logCallback(const char * msg)81 void logCallback(const char* msg) {
82     gLog.info(std::string(msg));
83 }
84 
tagSocketCallback(int sockFd,uint32_t tag,uid_t uid,pid_t)85 int tagSocketCallback(int sockFd, uint32_t tag, uid_t uid, pid_t) {
86     // Workaround for secureVPN with VpnIsolation enabled, refer to b/159994981 for details.
87     if (tag == TAG_SYSTEM_DNS) uid = AID_DNS;
88     return gCtls->trafficCtrl.tagSocket(sockFd, tag, uid, geteuid());
89 }
90 
evaluateDomainNameCallback(const android_net_context &,const char *)91 bool evaluateDomainNameCallback(const android_net_context&, const char* /*name*/) {
92     return true;
93 }
94 
initDnsResolver()95 bool initDnsResolver() {
96     ResolverNetdCallbacks callbacks = {
97             .check_calling_permission = &checkCallingPermissionCallback,
98             .get_network_context = &getNetworkContextCallback,
99             .log = &logCallback,
100             .tagSocket = &tagSocketCallback,
101             .evaluate_domain_name = &evaluateDomainNameCallback,
102     };
103     return resolv_init(&callbacks);
104 }
105 
106 }  // namespace
107 
main()108 int main() {
109     Stopwatch s;
110     gLog.info("netd 1.0 starting");
111 
112     android::net::process::removePidFile(PID_FILE_PATH);
113     android::net::process::blockSigPipe();
114 
115     // Before we do anything that could fork, mark CLOEXEC the UNIX sockets that we get from init.
116     // FrameworkListener does this on initialization as well, but we only initialize these
117     // components after having initialized other subsystems that can fork.
118     for (const auto& sock :
119          {DNSPROXYLISTENER_SOCKET_NAME, FwmarkServer::SOCKET_NAME, MDnsSdListener::SOCKET_NAME}) {
120         setCloseOnExec(sock);
121     }
122 
123     // Make sure BPF programs are loaded before doing anything
124     android::bpf::waitForProgsLoaded();
125 
126     NetlinkManager *nm = NetlinkManager::Instance();
127     if (nm == nullptr) {
128         ALOGE("Unable to create NetlinkManager");
129         exit(1);
130     };
131 
132     gCtls = new android::net::Controllers();
133     gCtls->init();
134 
135     if (nm->start()) {
136         ALOGE("Unable to start NetlinkManager (%s)", strerror(errno));
137         exit(1);
138     }
139 
140     std::unique_ptr<NFLogListener> logListener;
141     {
142         auto result = makeNFLogListener();
143         if (!isOk(result)) {
144             ALOGE("Unable to create NFLogListener: %s", toString(result).c_str());
145             exit(1);
146         }
147         logListener = std::move(result.value());
148         auto status = gCtls->wakeupCtrl.init(logListener.get());
149         if (!isOk(result)) {
150             gLog.error("Unable to init WakeupController: %s", toString(result).c_str());
151             // We can still continue without wakeup packet logging.
152         }
153     }
154 
155     // Set local DNS mode, to prevent bionic from proxying
156     // back to this service, recursively.
157     // TODO: Check if we could remove it since resolver cache no loger
158     // checks this environment variable after aosp/838050.
159     setenv("ANDROID_DNS_MODE", "local", 1);
160     // Note that only call initDnsResolver after gCtls initializing.
161     if (!initDnsResolver()) {
162         ALOGE("Unable to init resolver");
163         exit(1);
164     }
165 
166     MDnsSdListener mdnsl;
167     if (mdnsl.startListener()) {
168         ALOGE("Unable to start MDnsSdListener (%s)", strerror(errno));
169         exit(1);
170     }
171 
172     FwmarkServer fwmarkServer(&gCtls->netCtrl, &gCtls->eventReporter, &gCtls->trafficCtrl);
173     if (fwmarkServer.startListener()) {
174         ALOGE("Unable to start FwmarkServer (%s)", strerror(errno));
175         exit(1);
176     }
177 
178     Stopwatch subTime;
179     status_t ret;
180     if ((ret = NetdNativeService::start()) != android::OK) {
181         ALOGE("Unable to start NetdNativeService: %d", ret);
182         exit(1);
183     }
184     gLog.info("Registering NetdNativeService: %" PRId64 "us", subTime.getTimeAndResetUs());
185 
186     android::net::process::ScopedPidFile pidFile(PID_FILE_PATH);
187 
188     // Now that netd is ready to process commands, advertise service availability for HAL clients.
189     sp<NetdHwService> mHwSvc(new NetdHwService());
190     if ((ret = mHwSvc->start()) != android::OK) {
191         ALOGE("Unable to start NetdHwService: %d", ret);
192         exit(1);
193     }
194     gLog.info("Registering NetdHwService: %" PRId64 "us", subTime.getTimeAndResetUs());
195     gLog.info("Netd started in %" PRId64 "us", s.timeTakenUs());
196 
197     IPCThreadState::self()->joinThreadPool();
198 
199     gLog.info("netd exiting");
200 
201     exit(0);
202 }
203