• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2016, 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 #define LOG_TAG "Netd"
18 
19 #include <cinttypes>
20 #include <numeric>
21 #include <set>
22 #include <string>
23 #include <tuple>
24 #include <vector>
25 
26 #include <android-base/file.h>
27 #include <android-base/stringprintf.h>
28 #include <android-base/strings.h>
29 #include <binder/IPCThreadState.h>
30 #include <binder/IServiceManager.h>
31 #include <binder/Status.h>
32 #include <cutils/properties.h>
33 #include <log/log.h>
34 #include <netdutils/DumpWriter.h>
35 #include <netdutils/Utils.h>
36 #include <utils/Errors.h>
37 #include <utils/String16.h>
38 
39 #include "Controllers.h"
40 #include "Fwmark.h"
41 #include "InterfaceController.h"
42 #include "NetdNativeService.h"
43 #include "OemNetdListener.h"
44 #include "Permission.h"
45 #include "Process.h"
46 #include "RouteController.h"
47 #include "SockDiag.h"
48 #include "UidRanges.h"
49 #include "android/net/BnNetd.h"
50 #include "binder_utils/BinderUtil.h"
51 #include "binder_utils/NetdPermissions.h"
52 #include "netid_client.h"  // NETID_UNSET
53 
54 using android::base::StringPrintf;
55 using android::base::WriteStringToFile;
56 using android::net::TetherStatsParcel;
57 using android::net::UidRangeParcel;
58 using android::net::netd::aidl::NativeUidRangeConfig;
59 using android::netdutils::DumpWriter;
60 using android::netdutils::getIfaceNames;
61 using android::netdutils::ScopedIndent;
62 using android::os::ParcelFileDescriptor;
63 
64 namespace android {
65 namespace net {
66 
67 namespace {
68 const char OPT_SHORT[] = "--short";
69 
70 #define ENFORCE_ANY_PERMISSION(...)                                \
71     do {                                                           \
72         binder::Status status = checkAnyPermission({__VA_ARGS__}); \
73         if (!status.isOk()) {                                      \
74             return status;                                         \
75         }                                                          \
76     } while (0)
77 
78 #define NETD_LOCKING_RPC(lock, ... /* permissions */) \
79     ENFORCE_ANY_PERMISSION(__VA_ARGS__);              \
80     std::lock_guard _lock(lock);
81 
82 #define NETD_BIG_LOCK_RPC(... /* permissions */) NETD_LOCKING_RPC(gBigNetdLock, __VA_ARGS__)
83 
84 #define RETURN_BINDER_STATUS_IF_NOT_OK(logEntry, res) \
85     do {                                              \
86         if (!isOk((res))) {                           \
87             logErrorStatus((logEntry), (res));        \
88             return asBinderStatus((res));             \
89         }                                             \
90     } while (0)
91 
92 #define ENFORCE_NETWORK_STACK_PERMISSIONS() \
93     ENFORCE_ANY_PERMISSION(PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK)
94 
logErrorStatus(netdutils::LogEntry & logEntry,const netdutils::Status & status)95 void logErrorStatus(netdutils::LogEntry& logEntry, const netdutils::Status& status) {
96     gLog.log(logEntry.returns(status.code()).withAutomaticDuration());
97 }
98 
asBinderStatus(const netdutils::Status & status)99 binder::Status asBinderStatus(const netdutils::Status& status) {
100     if (isOk(status)) {
101         return binder::Status::ok();
102     }
103     return binder::Status::fromServiceSpecificError(status.code(), status.msg().c_str());
104 }
105 
106 template <typename T>
asBinderStatus(const base::Result<T> result)107 binder::Status asBinderStatus(const base::Result<T> result) {
108     if (result.ok()) return binder::Status::ok();
109 
110     return binder::Status::fromServiceSpecificError(result.error().code(),
111                                                     result.error().message().c_str());
112 }
113 
contains(const Vector<String16> & words,const String16 & word)114 bool contains(const Vector<String16>& words, const String16& word) {
115     for (const auto& w : words) {
116         if (w == word) return true;
117     }
118 
119     return false;
120 }
121 
122 }  // namespace
123 
NetdNativeService()124 NetdNativeService::NetdNativeService() {
125     // register log callback to BnNetd::logFunc
126     BnNetd::logFunc = [](const auto& log) {
127         binderCallLogFn(log, [](const std::string& msg) { gLog.info("%s", msg.c_str()); });
128     };
129 }
130 
start()131 status_t NetdNativeService::start() {
132     IPCThreadState::self()->disableBackgroundScheduling(true);
133     const status_t ret = BinderService<NetdNativeService>::publish();
134     if (ret != android::OK) {
135         return ret;
136     }
137     sp<ProcessState> ps(ProcessState::self());
138     ps->startThreadPool();
139     ps->giveThreadPoolName();
140 
141     return android::OK;
142 }
143 
dump(int fd,const Vector<String16> & args)144 status_t NetdNativeService::dump(int fd, const Vector<String16> &args) {
145     const binder::Status dump_permission = checkAnyPermission({PERM_DUMP});
146     if (!dump_permission.isOk()) {
147         const String8 msg(dump_permission.toString8());
148         write(fd, msg.string(), msg.size());
149         return PERMISSION_DENIED;
150     }
151 
152     // This method does not grab any locks. If individual classes need locking
153     // their dump() methods MUST handle locking appropriately.
154 
155     DumpWriter dw(fd);
156 
157     if (!args.isEmpty() && args[0] == TcpSocketMonitor::DUMP_KEYWORD) {
158       dw.blankline();
159       gCtls->tcpSocketMonitor.dump(dw);
160       dw.blankline();
161       return NO_ERROR;
162     }
163 
164     process::dump(dw);
165     dw.blankline();
166     gCtls->netCtrl.dump(dw);
167     dw.blankline();
168 
169     gCtls->xfrmCtrl.dump(dw);
170     dw.blankline();
171 
172     gCtls->tetherCtrl.dump(dw);
173     dw.blankline();
174 
175     {
176         ScopedIndent indentLog(dw);
177         if (contains(args, String16(OPT_SHORT))) {
178             dw.println("Log: <omitted>");
179         } else {
180             dw.println("Log:");
181             ScopedIndent indentLogEntries(dw);
182             gLog.forEachEntry([&dw](const std::string& entry) mutable { dw.println(entry); });
183         }
184         dw.blankline();
185     }
186 
187     {
188         ScopedIndent indentLog(dw);
189         if (contains(args, String16(OPT_SHORT))) {
190             dw.println("UnsolicitedLog: <omitted>");
191         } else {
192             dw.println("UnsolicitedLog:");
193             ScopedIndent indentLogEntries(dw);
194             gUnsolicitedLog.forEachEntry(
195                     [&dw](const std::string& entry) mutable { dw.println(entry); });
196         }
197         dw.blankline();
198     }
199 
200     return NO_ERROR;
201 }
202 
isAlive(bool * alive)203 binder::Status NetdNativeService::isAlive(bool *alive) {
204     NETD_BIG_LOCK_RPC(PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
205 
206     *alive = true;
207 
208     return binder::Status::ok();
209 }
210 
firewallReplaceUidChain(const std::string &,bool,const std::vector<int32_t> &,bool *)211 binder::Status NetdNativeService::firewallReplaceUidChain(const std::string&, bool,
212                                                           const std::vector<int32_t>&, bool*) {
213     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
214 }
215 
bandwidthEnableDataSaver(bool enable,bool * ret)216 binder::Status NetdNativeService::bandwidthEnableDataSaver(bool enable, bool *ret) {
217     NETD_LOCKING_RPC(gCtls->bandwidthCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
218     int err = gCtls->bandwidthCtrl.enableDataSaver(enable);
219     *ret = (err == 0);
220     return binder::Status::ok();
221 }
222 
bandwidthSetInterfaceQuota(const std::string & ifName,int64_t bytes)223 binder::Status NetdNativeService::bandwidthSetInterfaceQuota(const std::string& ifName,
224                                                              int64_t bytes) {
225     NETD_LOCKING_RPC(gCtls->bandwidthCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
226     int res = gCtls->bandwidthCtrl.setInterfaceQuota(ifName, bytes);
227     return statusFromErrcode(res);
228 }
229 
bandwidthRemoveInterfaceQuota(const std::string & ifName)230 binder::Status NetdNativeService::bandwidthRemoveInterfaceQuota(const std::string& ifName) {
231     NETD_LOCKING_RPC(gCtls->bandwidthCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
232     int res = gCtls->bandwidthCtrl.removeInterfaceQuota(ifName);
233     return statusFromErrcode(res);
234 }
235 
bandwidthSetInterfaceAlert(const std::string & ifName,int64_t bytes)236 binder::Status NetdNativeService::bandwidthSetInterfaceAlert(const std::string& ifName,
237                                                              int64_t bytes) {
238     NETD_LOCKING_RPC(gCtls->bandwidthCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
239     int res = gCtls->bandwidthCtrl.setInterfaceAlert(ifName, bytes);
240     return statusFromErrcode(res);
241 }
242 
bandwidthRemoveInterfaceAlert(const std::string & ifName)243 binder::Status NetdNativeService::bandwidthRemoveInterfaceAlert(const std::string& ifName) {
244     NETD_LOCKING_RPC(gCtls->bandwidthCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
245     int res = gCtls->bandwidthCtrl.removeInterfaceAlert(ifName);
246     return statusFromErrcode(res);
247 }
248 
bandwidthSetGlobalAlert(int64_t bytes)249 binder::Status NetdNativeService::bandwidthSetGlobalAlert(int64_t bytes) {
250     NETD_LOCKING_RPC(gCtls->bandwidthCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
251     int res = gCtls->bandwidthCtrl.setGlobalAlert(bytes);
252     return statusFromErrcode(res);
253 }
254 
bandwidthAddNaughtyApp(int32_t)255 binder::Status NetdNativeService::bandwidthAddNaughtyApp(int32_t) {
256     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
257 }
258 
bandwidthRemoveNaughtyApp(int32_t)259 binder::Status NetdNativeService::bandwidthRemoveNaughtyApp(int32_t) {
260     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
261 }
262 
bandwidthAddNiceApp(int32_t)263 binder::Status NetdNativeService::bandwidthAddNiceApp(int32_t) {
264     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
265 }
266 
bandwidthRemoveNiceApp(int32_t)267 binder::Status NetdNativeService::bandwidthRemoveNiceApp(int32_t) {
268     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
269 }
270 
271 // TODO: Remove this function when there are no users. Currently, it is still used by DNS resolver
272 // tests.
networkCreatePhysical(int32_t netId,int32_t permission)273 binder::Status NetdNativeService::networkCreatePhysical(int32_t netId, int32_t permission) {
274     ENFORCE_NETWORK_STACK_PERMISSIONS();
275     int ret = gCtls->netCtrl.createPhysicalNetwork(netId, convertPermission(permission));
276     return statusFromErrcode(ret);
277 }
278 
279 // TODO: Remove this function when there are no users. Currently, it is still used by DNS resolver
280 // tests.
networkCreateVpn(int32_t netId,bool secure)281 binder::Status NetdNativeService::networkCreateVpn(int32_t netId, bool secure) {
282     ENFORCE_NETWORK_STACK_PERMISSIONS();
283     // The value of vpnType does not matter here, because it is not used in AOSP and is only
284     // implemented by OEMs. Also, the RPC is going to deprecate. Just pick a value defined in INetd
285     // as default.
286     int ret = gCtls->netCtrl.createVirtualNetwork(netId, secure, NativeVpnType::LEGACY,
287                                                   false /* excludeLocalRoutes */);
288     return statusFromErrcode(ret);
289 }
290 
networkCreate(const NativeNetworkConfig & config)291 binder::Status NetdNativeService::networkCreate(const NativeNetworkConfig& config) {
292     ENFORCE_NETWORK_STACK_PERMISSIONS();
293     int ret = -EINVAL;
294     if (config.networkType == NativeNetworkType::PHYSICAL) {
295         ret = gCtls->netCtrl.createPhysicalNetwork(config.netId,
296                                                    convertPermission(config.permission));
297     } else if (config.networkType == NativeNetworkType::VIRTUAL) {
298         ret = gCtls->netCtrl.createVirtualNetwork(config.netId, config.secure, config.vpnType,
299                                                   config.excludeLocalRoutes);
300     }
301     return statusFromErrcode(ret);
302 }
303 
networkDestroy(int32_t netId)304 binder::Status NetdNativeService::networkDestroy(int32_t netId) {
305     ENFORCE_NETWORK_STACK_PERMISSIONS();
306     // NetworkController::destroyNetwork is thread-safe.
307     const int ret = gCtls->netCtrl.destroyNetwork(netId);
308     return statusFromErrcode(ret);
309 }
310 
networkAddInterface(int32_t netId,const std::string & iface)311 binder::Status NetdNativeService::networkAddInterface(int32_t netId, const std::string& iface) {
312     ENFORCE_NETWORK_STACK_PERMISSIONS();
313     int ret = gCtls->netCtrl.addInterfaceToNetwork(netId, iface.c_str());
314     return statusFromErrcode(ret);
315 }
316 
networkRemoveInterface(int32_t netId,const std::string & iface)317 binder::Status NetdNativeService::networkRemoveInterface(int32_t netId, const std::string& iface) {
318     ENFORCE_NETWORK_STACK_PERMISSIONS();
319     int ret = gCtls->netCtrl.removeInterfaceFromNetwork(netId, iface.c_str());
320     return statusFromErrcode(ret);
321 }
322 
networkAddUidRanges(int32_t netId,const std::vector<UidRangeParcel> & uidRangeArray)323 binder::Status NetdNativeService::networkAddUidRanges(
324         int32_t netId, const std::vector<UidRangeParcel>& uidRangeArray) {
325     // NetworkController::addUsersToNetwork is thread-safe.
326     ENFORCE_NETWORK_STACK_PERMISSIONS();
327     int ret = gCtls->netCtrl.addUsersToNetwork(netId, UidRanges(uidRangeArray),
328                                                UidRanges::SUB_PRIORITY_HIGHEST);
329     return statusFromErrcode(ret);
330 }
331 
networkRemoveUidRanges(int32_t netId,const std::vector<UidRangeParcel> & uidRangeArray)332 binder::Status NetdNativeService::networkRemoveUidRanges(
333         int32_t netId, const std::vector<UidRangeParcel>& uidRangeArray) {
334     // NetworkController::removeUsersFromNetwork is thread-safe.
335     ENFORCE_NETWORK_STACK_PERMISSIONS();
336     int ret = gCtls->netCtrl.removeUsersFromNetwork(netId, UidRanges(uidRangeArray),
337                                                     UidRanges::SUB_PRIORITY_HIGHEST);
338     return statusFromErrcode(ret);
339 }
340 
networkAddUidRangesParcel(const NativeUidRangeConfig & config)341 binder::Status NetdNativeService::networkAddUidRangesParcel(const NativeUidRangeConfig& config) {
342     ENFORCE_NETWORK_STACK_PERMISSIONS();
343     int ret = gCtls->netCtrl.addUsersToNetwork(config.netId, UidRanges(config.uidRanges),
344                                                config.subPriority);
345     return statusFromErrcode(ret);
346 }
347 
networkRemoveUidRangesParcel(const NativeUidRangeConfig & config)348 binder::Status NetdNativeService::networkRemoveUidRangesParcel(const NativeUidRangeConfig& config) {
349     ENFORCE_NETWORK_STACK_PERMISSIONS();
350     int ret = gCtls->netCtrl.removeUsersFromNetwork(config.netId, UidRanges(config.uidRanges),
351                                                     config.subPriority);
352     return statusFromErrcode(ret);
353 }
354 
networkRejectNonSecureVpn(bool add,const std::vector<UidRangeParcel> & uidRangeArray)355 binder::Status NetdNativeService::networkRejectNonSecureVpn(
356         bool add, const std::vector<UidRangeParcel>& uidRangeArray) {
357     // TODO: elsewhere RouteController is only used from the tethering and network controllers, so
358     // it should be possible to use the same lock as NetworkController. However, every call through
359     // the CommandListener "network" command will need to hold this lock too, not just the ones that
360     // read/modify network internal state (that is sufficient for ::dump() because it doesn't
361     // look at routes, but it's not enough here).
362     NETD_BIG_LOCK_RPC(PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
363     UidRanges uidRanges(uidRangeArray);
364 
365     int err;
366     if (add) {
367         err = RouteController::addUsersToRejectNonSecureNetworkRule(uidRanges);
368     } else {
369         err = RouteController::removeUsersFromRejectNonSecureNetworkRule(uidRanges);
370     }
371     return statusFromErrcode(err);
372 }
373 
socketDestroy(const std::vector<UidRangeParcel> & uids,const std::vector<int32_t> & skipUids)374 binder::Status NetdNativeService::socketDestroy(const std::vector<UidRangeParcel>& uids,
375                                                 const std::vector<int32_t>& skipUids) {
376     ENFORCE_NETWORK_STACK_PERMISSIONS();
377 
378     SockDiag sd;
379     if (!sd.open()) {
380         return binder::Status::fromServiceSpecificError(EIO,
381                 String8("Could not open SOCK_DIAG socket"));
382     }
383 
384     UidRanges uidRanges(uids);
385     int err = sd.destroySockets(uidRanges, std::set<uid_t>(skipUids.begin(), skipUids.end()),
386                                 true /* excludeLoopback */);
387     if (err) {
388         return binder::Status::fromServiceSpecificError(-err,
389                 String8::format("destroySockets: %s", strerror(-err)));
390     }
391     return binder::Status::ok();
392 }
393 
tetherApplyDnsInterfaces(bool * ret)394 binder::Status NetdNativeService::tetherApplyDnsInterfaces(bool *ret) {
395     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
396     *ret = gCtls->tetherCtrl.applyDnsInterfaces();
397     return binder::Status::ok();
398 }
399 
400 namespace {
401 
402 constexpr const int UNUSED_IFINDEX = 0;
403 
tetherAddStatsByInterface(TetherController::TetherStats * tetherStatsParcel,const TetherController::TetherStats & tetherStats)404 void tetherAddStatsByInterface(TetherController::TetherStats* tetherStatsParcel,
405                                const TetherController::TetherStats& tetherStats) {
406     if (tetherStatsParcel->extIface == tetherStats.extIface) {
407         tetherStatsParcel->rxBytes += tetherStats.rxBytes;
408         tetherStatsParcel->rxPackets += tetherStats.rxPackets;
409         tetherStatsParcel->txBytes += tetherStats.txBytes;
410         tetherStatsParcel->txPackets += tetherStats.txPackets;
411     }
412 }
413 
toTetherStatsParcel(const TetherController::TetherStats & stats)414 TetherStatsParcel toTetherStatsParcel(const TetherController::TetherStats& stats) {
415     TetherStatsParcel result;
416     result.iface = stats.extIface;
417     result.rxBytes = stats.rxBytes;
418     result.rxPackets = stats.rxPackets;
419     result.txBytes = stats.txBytes;
420     result.txPackets = stats.txPackets;
421     result.ifIndex = UNUSED_IFINDEX;
422     return result;
423 }
424 
setTetherStatsParcelVecByInterface(std::vector<TetherStatsParcel> * tetherStatsVec,const TetherController::TetherStatsList & statsList)425 void setTetherStatsParcelVecByInterface(std::vector<TetherStatsParcel>* tetherStatsVec,
426                                         const TetherController::TetherStatsList& statsList) {
427     std::map<std::string, TetherController::TetherStats> statsMap;
428     for (const auto& stats : statsList) {
429         auto iter = statsMap.find(stats.extIface);
430         if (iter != statsMap.end()) {
431             tetherAddStatsByInterface(&(iter->second), stats);
432         } else {
433             statsMap.insert(
434                     std::pair<std::string, TetherController::TetherStats>(stats.extIface, stats));
435         }
436     }
437     for (auto iter = statsMap.begin(); iter != statsMap.end(); iter++) {
438         tetherStatsVec->push_back(toTetherStatsParcel(iter->second));
439     }
440 }
441 
tetherStatsParcelVecToStringVec(std::vector<TetherStatsParcel> * tVec)442 std::vector<std::string> tetherStatsParcelVecToStringVec(std::vector<TetherStatsParcel>* tVec) {
443     std::vector<std::string> result;
444     for (const auto& t : *tVec) {
445         result.push_back(StringPrintf("%s:%" PRId64 ",%" PRId64 ",%" PRId64 ",%" PRId64,
446                                       t.iface.c_str(), t.rxBytes, t.rxPackets, t.txBytes,
447                                       t.txPackets));
448     }
449     return result;
450 }
451 
452 }  // namespace
453 
tetherGetStats(std::vector<TetherStatsParcel> * tetherStatsParcelVec)454 binder::Status NetdNativeService::tetherGetStats(
455         std::vector<TetherStatsParcel>* tetherStatsParcelVec) {
456     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
457     const auto& statsList = gCtls->tetherCtrl.getTetherStats();
458     if (!isOk(statsList)) {
459         return asBinderStatus(statsList);
460     }
461     setTetherStatsParcelVecByInterface(tetherStatsParcelVec, statsList.value());
462     auto statsResults = tetherStatsParcelVecToStringVec(tetherStatsParcelVec);
463     return binder::Status::ok();
464 }
465 
interfaceAddAddress(const std::string & ifName,const std::string & addrString,int prefixLength)466 binder::Status NetdNativeService::interfaceAddAddress(const std::string &ifName,
467         const std::string &addrString, int prefixLength) {
468     ENFORCE_NETWORK_STACK_PERMISSIONS();
469     const int err = InterfaceController::addAddress(
470             ifName.c_str(), addrString.c_str(), prefixLength);
471     if (err != 0) {
472         return binder::Status::fromServiceSpecificError(-err,
473                 String8::format("InterfaceController error: %s", strerror(-err)));
474     }
475     return binder::Status::ok();
476 }
477 
interfaceDelAddress(const std::string & ifName,const std::string & addrString,int prefixLength)478 binder::Status NetdNativeService::interfaceDelAddress(const std::string &ifName,
479         const std::string &addrString, int prefixLength) {
480     ENFORCE_NETWORK_STACK_PERMISSIONS();
481     const int err = InterfaceController::delAddress(
482             ifName.c_str(), addrString.c_str(), prefixLength);
483     if (err != 0) {
484         return binder::Status::fromServiceSpecificError(-err,
485                 String8::format("InterfaceController error: %s", strerror(-err)));
486     }
487     return binder::Status::ok();
488 }
489 
490 namespace {
491 
getPathComponents(int32_t ipversion,int32_t category)492 std::tuple<binder::Status, const char*, const char*> getPathComponents(int32_t ipversion,
493                                                                        int32_t category) {
494     const char* ipversionStr = nullptr;
495     switch (ipversion) {
496         case INetd::IPV4:
497             ipversionStr = "ipv4";
498             break;
499         case INetd::IPV6:
500             ipversionStr = "ipv6";
501             break;
502         default:
503             return {binder::Status::fromServiceSpecificError(EAFNOSUPPORT, "Bad IP version"),
504                     nullptr, nullptr};
505     }
506 
507     const char* whichStr = nullptr;
508     switch (category) {
509         case INetd::CONF:
510             whichStr = "conf";
511             break;
512         case INetd::NEIGH:
513             whichStr = "neigh";
514             break;
515         default:
516             return {binder::Status::fromServiceSpecificError(EINVAL, "Bad category"), nullptr,
517                     nullptr};
518     }
519 
520     return {binder::Status::ok(), ipversionStr, whichStr};
521 }
522 
523 }  // namespace
524 
getProcSysNet(int32_t ipversion,int32_t which,const std::string & ifname,const std::string & parameter,std::string * value)525 binder::Status NetdNativeService::getProcSysNet(int32_t ipversion, int32_t which,
526                                                 const std::string& ifname,
527                                                 const std::string& parameter, std::string* value) {
528     ENFORCE_NETWORK_STACK_PERMISSIONS();
529     const auto pathParts = getPathComponents(ipversion, which);
530     const auto& pathStatus = std::get<0>(pathParts);
531     if (!pathStatus.isOk()) {
532         return pathStatus;
533     }
534 
535     const int err = InterfaceController::getParameter(std::get<1>(pathParts),
536                                                       std::get<2>(pathParts), ifname.c_str(),
537                                                       parameter.c_str(), value);
538     return statusFromErrcode(err);
539 }
540 
setProcSysNet(int32_t ipversion,int32_t which,const std::string & ifname,const std::string & parameter,const std::string & value)541 binder::Status NetdNativeService::setProcSysNet(int32_t ipversion, int32_t which,
542                                                 const std::string& ifname,
543                                                 const std::string& parameter,
544                                                 const std::string& value) {
545     ENFORCE_NETWORK_STACK_PERMISSIONS();
546     const auto pathParts = getPathComponents(ipversion, which);
547     const auto& pathStatus = std::get<0>(pathParts);
548     if (!pathStatus.isOk()) {
549         return pathStatus;
550     }
551 
552     const int err = InterfaceController::setParameter(std::get<1>(pathParts),
553                                                       std::get<2>(pathParts), ifname.c_str(),
554                                                       parameter.c_str(), value.c_str());
555     return statusFromErrcode(err);
556 }
557 
ipSecSetEncapSocketOwner(const ParcelFileDescriptor & socket,int newUid)558 binder::Status NetdNativeService::ipSecSetEncapSocketOwner(const ParcelFileDescriptor& socket,
559                                                            int newUid) {
560     ENFORCE_NETWORK_STACK_PERMISSIONS();
561 
562     uid_t callerUid = IPCThreadState::self()->getCallingUid();
563     return asBinderStatus(
564             gCtls->xfrmCtrl.ipSecSetEncapSocketOwner(socket.get(), newUid, callerUid));
565 }
566 
ipSecAllocateSpi(int32_t transformId,const std::string & sourceAddress,const std::string & destinationAddress,int32_t inSpi,int32_t * outSpi)567 binder::Status NetdNativeService::ipSecAllocateSpi(
568         int32_t transformId,
569         const std::string& sourceAddress,
570         const std::string& destinationAddress,
571         int32_t inSpi,
572         int32_t* outSpi) {
573     // Necessary locking done in IpSecService and kernel
574     ENFORCE_NETWORK_STACK_PERMISSIONS();
575     return asBinderStatus(gCtls->xfrmCtrl.ipSecAllocateSpi(
576                     transformId,
577                     sourceAddress,
578                     destinationAddress,
579                     inSpi,
580                     outSpi));
581 }
582 
ipSecAddSecurityAssociation(int32_t transformId,int32_t mode,const std::string & sourceAddress,const std::string & destinationAddress,int32_t underlyingNetId,int32_t spi,int32_t markValue,int32_t markMask,const std::string & authAlgo,const std::vector<uint8_t> & authKey,int32_t authTruncBits,const std::string & cryptAlgo,const std::vector<uint8_t> & cryptKey,int32_t cryptTruncBits,const std::string & aeadAlgo,const std::vector<uint8_t> & aeadKey,int32_t aeadIcvBits,int32_t encapType,int32_t encapLocalPort,int32_t encapRemotePort,int32_t interfaceId)583 binder::Status NetdNativeService::ipSecAddSecurityAssociation(
584         int32_t transformId, int32_t mode, const std::string& sourceAddress,
585         const std::string& destinationAddress, int32_t underlyingNetId, int32_t spi,
586         int32_t markValue, int32_t markMask, const std::string& authAlgo,
587         const std::vector<uint8_t>& authKey, int32_t authTruncBits, const std::string& cryptAlgo,
588         const std::vector<uint8_t>& cryptKey, int32_t cryptTruncBits, const std::string& aeadAlgo,
589         const std::vector<uint8_t>& aeadKey, int32_t aeadIcvBits, int32_t encapType,
590         int32_t encapLocalPort, int32_t encapRemotePort, int32_t interfaceId) {
591     // Necessary locking done in IpSecService and kernel
592     ENFORCE_NETWORK_STACK_PERMISSIONS();
593     return asBinderStatus(gCtls->xfrmCtrl.ipSecAddSecurityAssociation(
594             transformId, mode, sourceAddress, destinationAddress, underlyingNetId, spi, markValue,
595             markMask, authAlgo, authKey, authTruncBits, cryptAlgo, cryptKey, cryptTruncBits,
596             aeadAlgo, aeadKey, aeadIcvBits, encapType, encapLocalPort, encapRemotePort,
597             interfaceId));
598 }
599 
ipSecDeleteSecurityAssociation(int32_t transformId,const std::string & sourceAddress,const std::string & destinationAddress,int32_t spi,int32_t markValue,int32_t markMask,int32_t interfaceId)600 binder::Status NetdNativeService::ipSecDeleteSecurityAssociation(
601         int32_t transformId, const std::string& sourceAddress,
602         const std::string& destinationAddress, int32_t spi, int32_t markValue, int32_t markMask,
603         int32_t interfaceId) {
604     // Necessary locking done in IpSecService and kernel
605     ENFORCE_NETWORK_STACK_PERMISSIONS();
606     return asBinderStatus(gCtls->xfrmCtrl.ipSecDeleteSecurityAssociation(
607             transformId, sourceAddress, destinationAddress, spi, markValue, markMask, interfaceId));
608 }
609 
ipSecApplyTransportModeTransform(const ParcelFileDescriptor & socket,int32_t transformId,int32_t direction,const std::string & sourceAddress,const std::string & destinationAddress,int32_t spi)610 binder::Status NetdNativeService::ipSecApplyTransportModeTransform(
611         const ParcelFileDescriptor& socket, int32_t transformId, int32_t direction,
612         const std::string& sourceAddress, const std::string& destinationAddress, int32_t spi) {
613     // Necessary locking done in IpSecService and kernel
614     ENFORCE_NETWORK_STACK_PERMISSIONS();
615     return asBinderStatus(gCtls->xfrmCtrl.ipSecApplyTransportModeTransform(
616             socket.get(), transformId, direction, sourceAddress, destinationAddress, spi));
617 }
618 
ipSecRemoveTransportModeTransform(const ParcelFileDescriptor & socket)619 binder::Status NetdNativeService::ipSecRemoveTransportModeTransform(
620         const ParcelFileDescriptor& socket) {
621     // Necessary locking done in IpSecService and kernel
622     ENFORCE_NETWORK_STACK_PERMISSIONS();
623     return asBinderStatus(gCtls->xfrmCtrl.ipSecRemoveTransportModeTransform(socket.get()));
624 }
625 
ipSecAddSecurityPolicy(int32_t transformId,int32_t selAddrFamily,int32_t direction,const std::string & tmplSrcAddress,const std::string & tmplDstAddress,int32_t spi,int32_t markValue,int32_t markMask,int32_t interfaceId)626 binder::Status NetdNativeService::ipSecAddSecurityPolicy(int32_t transformId, int32_t selAddrFamily,
627                                                          int32_t direction,
628                                                          const std::string& tmplSrcAddress,
629                                                          const std::string& tmplDstAddress,
630                                                          int32_t spi, int32_t markValue,
631                                                          int32_t markMask, int32_t interfaceId) {
632     // Necessary locking done in IpSecService and kernel
633     ENFORCE_NETWORK_STACK_PERMISSIONS();
634     return asBinderStatus(gCtls->xfrmCtrl.ipSecAddSecurityPolicy(
635             transformId, selAddrFamily, direction, tmplSrcAddress, tmplDstAddress, spi, markValue,
636             markMask, interfaceId));
637 }
638 
ipSecUpdateSecurityPolicy(int32_t transformId,int32_t selAddrFamily,int32_t direction,const std::string & tmplSrcAddress,const std::string & tmplDstAddress,int32_t spi,int32_t markValue,int32_t markMask,int32_t interfaceId)639 binder::Status NetdNativeService::ipSecUpdateSecurityPolicy(
640         int32_t transformId, int32_t selAddrFamily, int32_t direction,
641         const std::string& tmplSrcAddress, const std::string& tmplDstAddress, int32_t spi,
642         int32_t markValue, int32_t markMask, int32_t interfaceId) {
643     // Necessary locking done in IpSecService and kernel
644     ENFORCE_NETWORK_STACK_PERMISSIONS();
645     return asBinderStatus(gCtls->xfrmCtrl.ipSecUpdateSecurityPolicy(
646             transformId, selAddrFamily, direction, tmplSrcAddress, tmplDstAddress, spi, markValue,
647             markMask, interfaceId));
648 }
649 
ipSecDeleteSecurityPolicy(int32_t transformId,int32_t selAddrFamily,int32_t direction,int32_t markValue,int32_t markMask,int32_t interfaceId)650 binder::Status NetdNativeService::ipSecDeleteSecurityPolicy(int32_t transformId,
651                                                             int32_t selAddrFamily,
652                                                             int32_t direction, int32_t markValue,
653                                                             int32_t markMask, int32_t interfaceId) {
654     // Necessary locking done in IpSecService and kernel
655     ENFORCE_NETWORK_STACK_PERMISSIONS();
656     return asBinderStatus(gCtls->xfrmCtrl.ipSecDeleteSecurityPolicy(
657             transformId, selAddrFamily, direction, markValue, markMask, interfaceId));
658 }
659 
ipSecAddTunnelInterface(const std::string & deviceName,const std::string & localAddress,const std::string & remoteAddress,int32_t iKey,int32_t oKey,int32_t interfaceId)660 binder::Status NetdNativeService::ipSecAddTunnelInterface(const std::string& deviceName,
661                                                           const std::string& localAddress,
662                                                           const std::string& remoteAddress,
663                                                           int32_t iKey, int32_t oKey,
664                                                           int32_t interfaceId) {
665     // Necessary locking done in IpSecService and kernel
666     ENFORCE_NETWORK_STACK_PERMISSIONS();
667     netdutils::Status result = gCtls->xfrmCtrl.ipSecAddTunnelInterface(
668             deviceName, localAddress, remoteAddress, iKey, oKey, interfaceId, false);
669     return binder::Status::ok();
670 }
671 
ipSecUpdateTunnelInterface(const std::string & deviceName,const std::string & localAddress,const std::string & remoteAddress,int32_t iKey,int32_t oKey,int32_t interfaceId)672 binder::Status NetdNativeService::ipSecUpdateTunnelInterface(const std::string& deviceName,
673                                                              const std::string& localAddress,
674                                                              const std::string& remoteAddress,
675                                                              int32_t iKey, int32_t oKey,
676                                                              int32_t interfaceId) {
677     // Necessary locking done in IpSecService and kernel
678     ENFORCE_NETWORK_STACK_PERMISSIONS();
679     netdutils::Status result = gCtls->xfrmCtrl.ipSecAddTunnelInterface(
680             deviceName, localAddress, remoteAddress, iKey, oKey, interfaceId, true);
681     return binder::Status::ok();
682 }
683 
ipSecRemoveTunnelInterface(const std::string & deviceName)684 binder::Status NetdNativeService::ipSecRemoveTunnelInterface(const std::string& deviceName) {
685     // Necessary locking done in IpSecService and kernel
686     ENFORCE_NETWORK_STACK_PERMISSIONS();
687     netdutils::Status result = gCtls->xfrmCtrl.ipSecRemoveTunnelInterface(deviceName);
688     return binder::Status::ok();
689 }
690 
setIPv6AddrGenMode(const std::string & ifName,int32_t mode)691 binder::Status NetdNativeService::setIPv6AddrGenMode(const std::string& ifName,
692                                                      int32_t mode) {
693     ENFORCE_NETWORK_STACK_PERMISSIONS();
694     return asBinderStatus(InterfaceController::setIPv6AddrGenMode(ifName, mode));
695 }
696 
wakeupAddInterface(const std::string & ifName,const std::string & prefix,int32_t mark,int32_t mask)697 binder::Status NetdNativeService::wakeupAddInterface(const std::string& ifName,
698                                                      const std::string& prefix, int32_t mark,
699                                                      int32_t mask) {
700     ENFORCE_NETWORK_STACK_PERMISSIONS();
701     return asBinderStatus(gCtls->wakeupCtrl.addInterface(ifName, prefix, mark, mask));
702 }
703 
wakeupDelInterface(const std::string & ifName,const std::string & prefix,int32_t mark,int32_t mask)704 binder::Status NetdNativeService::wakeupDelInterface(const std::string& ifName,
705                                                      const std::string& prefix, int32_t mark,
706                                                      int32_t mask) {
707     ENFORCE_NETWORK_STACK_PERMISSIONS();
708     return asBinderStatus(gCtls->wakeupCtrl.delInterface(ifName, prefix, mark, mask));
709 }
710 
trafficSwapActiveStatsMap()711 binder::Status NetdNativeService::trafficSwapActiveStatsMap() {
712     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
713 }
714 
idletimerAddInterface(const std::string & ifName,int32_t timeout,const std::string & classLabel)715 binder::Status NetdNativeService::idletimerAddInterface(const std::string& ifName, int32_t timeout,
716                                                         const std::string& classLabel) {
717     NETD_LOCKING_RPC(gCtls->idletimerCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
718     int res =
719             gCtls->idletimerCtrl.addInterfaceIdletimer(ifName.c_str(), timeout, classLabel.c_str());
720     return statusFromErrcode(res);
721 }
722 
idletimerRemoveInterface(const std::string & ifName,int32_t timeout,const std::string & classLabel)723 binder::Status NetdNativeService::idletimerRemoveInterface(const std::string& ifName,
724                                                            int32_t timeout,
725                                                            const std::string& classLabel) {
726     NETD_LOCKING_RPC(gCtls->idletimerCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
727     int res = gCtls->idletimerCtrl.removeInterfaceIdletimer(ifName.c_str(), timeout,
728                                                             classLabel.c_str());
729     return statusFromErrcode(res);
730 }
731 
strictUidCleartextPenalty(int32_t uid,int32_t policyPenalty)732 binder::Status NetdNativeService::strictUidCleartextPenalty(int32_t uid, int32_t policyPenalty) {
733     NETD_LOCKING_RPC(gCtls->strictCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
734     StrictPenalty penalty;
735     switch (policyPenalty) {
736         case INetd::PENALTY_POLICY_REJECT:
737             penalty = REJECT;
738             break;
739         case INetd::PENALTY_POLICY_LOG:
740             penalty = LOG;
741             break;
742         case INetd::PENALTY_POLICY_ACCEPT:
743             penalty = ACCEPT;
744             break;
745         default:
746             return statusFromErrcode(-EINVAL);
747             break;
748     }
749     int res = gCtls->strictCtrl.setUidCleartextPenalty((uid_t) uid, penalty);
750     return statusFromErrcode(res);
751 }
752 
753 // TODO: remark @deprecated in INetd.aidl.
clatdStart(const std::string &,const std::string &,std::string *)754 binder::Status NetdNativeService::clatdStart(const std::string& /* ifName */,
755                                              const std::string& /* nat64Prefix */,
756                                              std::string* /* v6Addr */) {
757     ENFORCE_ANY_PERMISSION(PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
758     // deprecated
759     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
760 }
761 
762 // TODO: remark @deprecated in INetd.aidl.
clatdStop(const std::string &)763 binder::Status NetdNativeService::clatdStop(const std::string& /* ifName */) {
764     ENFORCE_ANY_PERMISSION(PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
765     // deprecated
766     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
767 }
768 
ipfwdEnabled(bool * status)769 binder::Status NetdNativeService::ipfwdEnabled(bool* status) {
770     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
771     *status = (gCtls->tetherCtrl.getIpfwdRequesterList().size() > 0) ? true : false;
772     return binder::Status::ok();
773 }
774 
ipfwdGetRequesterList(std::vector<std::string> * requesterList)775 binder::Status NetdNativeService::ipfwdGetRequesterList(std::vector<std::string>* requesterList) {
776     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
777     for (const auto& requester : gCtls->tetherCtrl.getIpfwdRequesterList()) {
778         requesterList->push_back(requester);
779     }
780     return binder::Status::ok();
781 }
782 
ipfwdEnableForwarding(const std::string & requester)783 binder::Status NetdNativeService::ipfwdEnableForwarding(const std::string& requester) {
784     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
785     int res = (gCtls->tetherCtrl.enableForwarding(requester.c_str())) ? 0 : -EREMOTEIO;
786     return statusFromErrcode(res);
787 }
788 
ipfwdDisableForwarding(const std::string & requester)789 binder::Status NetdNativeService::ipfwdDisableForwarding(const std::string& requester) {
790     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
791     int res = (gCtls->tetherCtrl.disableForwarding(requester.c_str())) ? 0 : -EREMOTEIO;
792     return statusFromErrcode(res);
793 }
794 
ipfwdAddInterfaceForward(const std::string & fromIface,const std::string & toIface)795 binder::Status NetdNativeService::ipfwdAddInterfaceForward(const std::string& fromIface,
796                                                            const std::string& toIface) {
797     ENFORCE_NETWORK_STACK_PERMISSIONS();
798     int res = RouteController::enableTethering(fromIface.c_str(), toIface.c_str());
799     return statusFromErrcode(res);
800 }
801 
ipfwdRemoveInterfaceForward(const std::string & fromIface,const std::string & toIface)802 binder::Status NetdNativeService::ipfwdRemoveInterfaceForward(const std::string& fromIface,
803                                                               const std::string& toIface) {
804     ENFORCE_NETWORK_STACK_PERMISSIONS();
805     int res = RouteController::disableTethering(fromIface.c_str(), toIface.c_str());
806     return statusFromErrcode(res);
807 }
808 
809 namespace {
810 
addCurlyBrackets(const std::string & s)811 std::string addCurlyBrackets(const std::string& s) {
812     return "{" + s + "}";
813 }
814 
815 }  // namespace
816 
interfaceGetList(std::vector<std::string> * interfaceListResult)817 binder::Status NetdNativeService::interfaceGetList(std::vector<std::string>* interfaceListResult) {
818     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
819     const auto& ifaceList = getIfaceNames();
820 
821     interfaceListResult->clear();
822     interfaceListResult->reserve(ifaceList.value().size());
823     interfaceListResult->insert(end(*interfaceListResult), begin(ifaceList.value()),
824                                 end(ifaceList.value()));
825 
826     return binder::Status::ok();
827 }
828 
interfaceConfigurationParcelToString(const InterfaceConfigurationParcel & cfg)829 std::string interfaceConfigurationParcelToString(const InterfaceConfigurationParcel& cfg) {
830     std::vector<std::string> result{cfg.ifName, cfg.hwAddr, cfg.ipv4Addr,
831                                     std::to_string(cfg.prefixLength)};
832     result.insert(end(result), begin(cfg.flags), end(cfg.flags));
833     return addCurlyBrackets(base::Join(result, ", "));
834 }
835 
interfaceGetCfg(const std::string & ifName,InterfaceConfigurationParcel * interfaceGetCfgResult)836 binder::Status NetdNativeService::interfaceGetCfg(
837         const std::string& ifName, InterfaceConfigurationParcel* interfaceGetCfgResult) {
838     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
839     auto entry = gLog.newEntry().prettyFunction(__PRETTY_FUNCTION__).arg(ifName);
840 
841     const auto& cfgRes = InterfaceController::getCfg(ifName);
842     RETURN_BINDER_STATUS_IF_NOT_OK(entry, cfgRes);
843 
844     *interfaceGetCfgResult = cfgRes.value();
845     gLog.log(entry.returns(interfaceConfigurationParcelToString(*interfaceGetCfgResult))
846                      .withAutomaticDuration());
847     return binder::Status::ok();
848 }
849 
interfaceSetCfg(const InterfaceConfigurationParcel & cfg)850 binder::Status NetdNativeService::interfaceSetCfg(const InterfaceConfigurationParcel& cfg) {
851     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
852     auto entry = gLog.newEntry()
853                          .prettyFunction(__PRETTY_FUNCTION__)
854                          .arg(interfaceConfigurationParcelToString(cfg));
855 
856     const auto& res = InterfaceController::setCfg(cfg);
857     RETURN_BINDER_STATUS_IF_NOT_OK(entry, res);
858 
859     gLog.log(entry.withAutomaticDuration());
860     return binder::Status::ok();
861 }
862 
interfaceSetIPv6PrivacyExtensions(const std::string & ifName,bool enable)863 binder::Status NetdNativeService::interfaceSetIPv6PrivacyExtensions(const std::string& ifName,
864                                                                     bool enable) {
865     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
866     int res = InterfaceController::setIPv6PrivacyExtensions(ifName.c_str(), enable);
867     return statusFromErrcode(res);
868 }
869 
interfaceClearAddrs(const std::string & ifName)870 binder::Status NetdNativeService::interfaceClearAddrs(const std::string& ifName) {
871     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
872     int res = InterfaceController::clearAddrs(ifName.c_str());
873     return statusFromErrcode(res);
874 }
875 
interfaceSetEnableIPv6(const std::string & ifName,bool enable)876 binder::Status NetdNativeService::interfaceSetEnableIPv6(const std::string& ifName, bool enable) {
877     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
878     int res = InterfaceController::setEnableIPv6(ifName.c_str(), enable);
879     return statusFromErrcode(res);
880 }
881 
interfaceSetMtu(const std::string & ifName,int32_t mtuValue)882 binder::Status NetdNativeService::interfaceSetMtu(const std::string& ifName, int32_t mtuValue) {
883     NETD_LOCKING_RPC(InterfaceController::mutex, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
884     std::string mtu = std::to_string(mtuValue);
885     int res = InterfaceController::setMtu(ifName.c_str(), mtu.c_str());
886     return statusFromErrcode(res);
887 }
888 
tetherStart(const std::vector<std::string> & dhcpRanges)889 binder::Status NetdNativeService::tetherStart(const std::vector<std::string>& dhcpRanges) {
890     TetherConfigParcel config;
891     config.usingLegacyDnsProxy = true;
892     config.dhcpRanges = dhcpRanges;
893     return tetherStartWithConfiguration(config);
894 }
895 
tetherStartWithConfiguration(const TetherConfigParcel & config)896 binder::Status NetdNativeService::tetherStartWithConfiguration(const TetherConfigParcel& config) {
897     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
898     if (config.dhcpRanges.size() % 2 == 1) {
899         return statusFromErrcode(-EINVAL);
900     }
901     // TODO: Pass TetherConfigParcel directly.
902     int res = gCtls->tetherCtrl.startTethering(config.usingLegacyDnsProxy, config.dhcpRanges);
903     return statusFromErrcode(res);
904 }
905 
tetherStop()906 binder::Status NetdNativeService::tetherStop() {
907     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
908     int res = gCtls->tetherCtrl.stopTethering();
909     return statusFromErrcode(res);
910 }
911 
tetherIsEnabled(bool * enabled)912 binder::Status NetdNativeService::tetherIsEnabled(bool* enabled) {
913     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
914     *enabled = gCtls->tetherCtrl.isTetheringStarted();
915     return binder::Status::ok();
916 }
917 
tetherInterfaceAdd(const std::string & ifName)918 binder::Status NetdNativeService::tetherInterfaceAdd(const std::string& ifName) {
919     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
920     int res = gCtls->tetherCtrl.tetherInterface(ifName.c_str());
921     return statusFromErrcode(res);
922 }
923 
tetherInterfaceRemove(const std::string & ifName)924 binder::Status NetdNativeService::tetherInterfaceRemove(const std::string& ifName) {
925     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
926     int res = gCtls->tetherCtrl.untetherInterface(ifName.c_str());
927     return statusFromErrcode(res);
928 }
929 
tetherInterfaceList(std::vector<std::string> * ifList)930 binder::Status NetdNativeService::tetherInterfaceList(std::vector<std::string>* ifList) {
931     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
932     for (const auto& ifname : gCtls->tetherCtrl.getTetheredInterfaceList()) {
933         ifList->push_back(ifname);
934     }
935     return binder::Status::ok();
936 }
937 
tetherDnsSet(int32_t netId,const std::vector<std::string> & dnsAddrs)938 binder::Status NetdNativeService::tetherDnsSet(int32_t netId,
939                                                const std::vector<std::string>& dnsAddrs) {
940     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
941     int res = gCtls->tetherCtrl.setDnsForwarders(netId, dnsAddrs);
942     return statusFromErrcode(res);
943 }
944 
tetherDnsList(std::vector<std::string> * dnsList)945 binder::Status NetdNativeService::tetherDnsList(std::vector<std::string>* dnsList) {
946     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
947     for (const auto& fwdr : gCtls->tetherCtrl.getDnsForwarders()) {
948         dnsList->push_back(fwdr);
949     }
950     return binder::Status::ok();
951 }
952 
networkAddRouteParcel(int32_t netId,const RouteInfoParcel & route)953 binder::Status NetdNativeService::networkAddRouteParcel(int32_t netId,
954                                                         const RouteInfoParcel& route) {
955     // Public methods of NetworkController are thread-safe.
956     ENFORCE_NETWORK_STACK_PERMISSIONS();
957     bool legacy = false;
958     uid_t uid = 0;  // UID is only meaningful for legacy routes.
959 
960     // convert Parcel to parameters
961     int res = gCtls->netCtrl.addRoute(netId, route.ifName.c_str(), route.destination.c_str(),
962                                       route.nextHop.empty() ? nullptr : route.nextHop.c_str(),
963                                       legacy, uid, route.mtu);
964     return statusFromErrcode(res);
965 }
966 
networkUpdateRouteParcel(int32_t netId,const RouteInfoParcel & route)967 binder::Status NetdNativeService::networkUpdateRouteParcel(int32_t netId,
968                                                            const RouteInfoParcel& route) {
969     // Public methods of NetworkController are thread-safe.
970     ENFORCE_NETWORK_STACK_PERMISSIONS();
971     bool legacy = false;
972     uid_t uid = 0;  // UID is only meaningful for legacy routes.
973 
974     // convert Parcel to parameters
975     int res = gCtls->netCtrl.updateRoute(netId, route.ifName.c_str(), route.destination.c_str(),
976                                          route.nextHop.empty() ? nullptr : route.nextHop.c_str(),
977                                          legacy, uid, route.mtu);
978     return statusFromErrcode(res);
979 }
980 
networkRemoveRouteParcel(int32_t netId,const RouteInfoParcel & route)981 binder::Status NetdNativeService::networkRemoveRouteParcel(int32_t netId,
982                                                            const RouteInfoParcel& route) {
983     return networkRemoveRoute(netId, route.ifName, route.destination, route.nextHop);
984 }
985 
networkAddRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop)986 binder::Status NetdNativeService::networkAddRoute(int32_t netId, const std::string& ifName,
987                                                   const std::string& destination,
988                                                   const std::string& nextHop) {
989     // Public methods of NetworkController are thread-safe.
990     ENFORCE_NETWORK_STACK_PERMISSIONS();
991     bool legacy = false;
992     uid_t uid = 0;  // UID is only meaningful for legacy routes.
993     int res = gCtls->netCtrl.addRoute(netId, ifName.c_str(), destination.c_str(),
994                                       nextHop.empty() ? nullptr : nextHop.c_str(), legacy, uid, 0);
995     return statusFromErrcode(res);
996 }
997 
networkRemoveRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop)998 binder::Status NetdNativeService::networkRemoveRoute(int32_t netId, const std::string& ifName,
999                                                      const std::string& destination,
1000                                                      const std::string& nextHop) {
1001     ENFORCE_NETWORK_STACK_PERMISSIONS();
1002     bool legacy = false;
1003     uid_t uid = 0;  // UID is only meaningful for legacy routes.
1004     int res = gCtls->netCtrl.removeRoute(netId, ifName.c_str(), destination.c_str(),
1005                                          nextHop.empty() ? nullptr : nextHop.c_str(), legacy, uid);
1006     return statusFromErrcode(res);
1007 }
1008 
networkAddLegacyRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop,int32_t uid)1009 binder::Status NetdNativeService::networkAddLegacyRoute(int32_t netId, const std::string& ifName,
1010                                                         const std::string& destination,
1011                                                         const std::string& nextHop, int32_t uid) {
1012     ENFORCE_NETWORK_STACK_PERMISSIONS();
1013     bool legacy = true;
1014     int res = gCtls->netCtrl.addRoute(netId, ifName.c_str(), destination.c_str(),
1015                                       nextHop.empty() ? nullptr : nextHop.c_str(), legacy,
1016                                       (uid_t)uid, 0);
1017     return statusFromErrcode(res);
1018 }
1019 
networkRemoveLegacyRoute(int32_t netId,const std::string & ifName,const std::string & destination,const std::string & nextHop,int32_t uid)1020 binder::Status NetdNativeService::networkRemoveLegacyRoute(int32_t netId, const std::string& ifName,
1021                                                            const std::string& destination,
1022                                                            const std::string& nextHop,
1023                                                            int32_t uid) {
1024     ENFORCE_NETWORK_STACK_PERMISSIONS();
1025     bool legacy = true;
1026     int res = gCtls->netCtrl.removeRoute(netId, ifName.c_str(), destination.c_str(),
1027                                          nextHop.empty() ? nullptr : nextHop.c_str(), legacy,
1028                                          (uid_t) uid);
1029     return statusFromErrcode(res);
1030 }
1031 
networkGetDefault(int32_t * netId)1032 binder::Status NetdNativeService::networkGetDefault(int32_t* netId) {
1033     ENFORCE_NETWORK_STACK_PERMISSIONS();
1034     *netId = gCtls->netCtrl.getDefaultNetwork();
1035     return binder::Status::ok();
1036 }
1037 
networkSetDefault(int32_t netId)1038 binder::Status NetdNativeService::networkSetDefault(int32_t netId) {
1039     ENFORCE_NETWORK_STACK_PERMISSIONS();
1040     int res = gCtls->netCtrl.setDefaultNetwork(netId);
1041     return statusFromErrcode(res);
1042 }
1043 
networkClearDefault()1044 binder::Status NetdNativeService::networkClearDefault() {
1045     ENFORCE_NETWORK_STACK_PERMISSIONS();
1046     unsigned netId = NETID_UNSET;
1047     int res = gCtls->netCtrl.setDefaultNetwork(netId);
1048     return statusFromErrcode(res);
1049 }
1050 
intsToUids(const std::vector<int32_t> & intUids)1051 std::vector<uid_t> NetdNativeService::intsToUids(const std::vector<int32_t>& intUids) {
1052     return {begin(intUids), end(intUids)};
1053 }
1054 
convertPermission(int32_t permission)1055 Permission NetdNativeService::convertPermission(int32_t permission) {
1056     switch (permission) {
1057         case INetd::PERMISSION_NETWORK:
1058             return Permission::PERMISSION_NETWORK;
1059         case INetd::PERMISSION_SYSTEM:
1060             return Permission::PERMISSION_SYSTEM;
1061         default:
1062             return Permission::PERMISSION_NONE;
1063     }
1064 }
1065 
networkSetPermissionForNetwork(int32_t netId,int32_t permission)1066 binder::Status NetdNativeService::networkSetPermissionForNetwork(int32_t netId,
1067                                                                  int32_t permission) {
1068     ENFORCE_NETWORK_STACK_PERMISSIONS();
1069     std::vector<unsigned> netIds = {(unsigned) netId};
1070     int res = gCtls->netCtrl.setPermissionForNetworks(convertPermission(permission), netIds);
1071     return statusFromErrcode(res);
1072 }
1073 
networkSetPermissionForUser(int32_t permission,const std::vector<int32_t> & uids)1074 binder::Status NetdNativeService::networkSetPermissionForUser(int32_t permission,
1075                                                               const std::vector<int32_t>& uids) {
1076     ENFORCE_NETWORK_STACK_PERMISSIONS();
1077     gCtls->netCtrl.setPermissionForUsers(convertPermission(permission), intsToUids(uids));
1078     return binder::Status::ok();
1079 }
1080 
networkClearPermissionForUser(const std::vector<int32_t> & uids)1081 binder::Status NetdNativeService::networkClearPermissionForUser(const std::vector<int32_t>& uids) {
1082     ENFORCE_NETWORK_STACK_PERMISSIONS();
1083     Permission permission = Permission::PERMISSION_NONE;
1084     gCtls->netCtrl.setPermissionForUsers(permission, intsToUids(uids));
1085     return binder::Status::ok();
1086 }
1087 
networkSetProtectAllow(int32_t uid)1088 binder::Status NetdNativeService::networkSetProtectAllow(int32_t uid) {
1089     ENFORCE_NETWORK_STACK_PERMISSIONS();
1090     std::vector<uid_t> uids = {(uid_t) uid};
1091     gCtls->netCtrl.allowProtect(uids);
1092     return binder::Status::ok();
1093 }
1094 
networkSetProtectDeny(int32_t uid)1095 binder::Status NetdNativeService::networkSetProtectDeny(int32_t uid) {
1096     ENFORCE_NETWORK_STACK_PERMISSIONS();
1097     std::vector<uid_t> uids = {(uid_t) uid};
1098     gCtls->netCtrl.denyProtect(uids);
1099     return binder::Status::ok();
1100 }
1101 
networkCanProtect(int32_t uid,bool * ret)1102 binder::Status NetdNativeService::networkCanProtect(int32_t uid, bool* ret) {
1103     ENFORCE_NETWORK_STACK_PERMISSIONS();
1104     *ret = gCtls->netCtrl.canProtect((uid_t) uid);
1105     return binder::Status::ok();
1106 }
1107 
trafficSetNetPermForUids(int32_t,const std::vector<int32_t> &)1108 binder::Status NetdNativeService::trafficSetNetPermForUids(int32_t, const std::vector<int32_t>&) {
1109     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
1110 }
1111 
firewallSetFirewallType(int32_t firewallType)1112 binder::Status NetdNativeService::firewallSetFirewallType(int32_t firewallType) {
1113     NETD_LOCKING_RPC(gCtls->firewallCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
1114     auto type = static_cast<FirewallType>(firewallType);
1115 
1116     int res = gCtls->firewallCtrl.setFirewallType(type);
1117     return statusFromErrcode(res);
1118 }
1119 
firewallSetInterfaceRule(const std::string & ifName,int32_t firewallRule)1120 binder::Status NetdNativeService::firewallSetInterfaceRule(const std::string& ifName,
1121                                                            int32_t firewallRule) {
1122     NETD_LOCKING_RPC(gCtls->firewallCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
1123     auto rule = static_cast<FirewallRule>(firewallRule);
1124 
1125     int res = gCtls->firewallCtrl.setInterfaceRule(ifName.c_str(), rule);
1126     return statusFromErrcode(res);
1127 }
1128 
firewallSetUidRule(int32_t,int32_t,int32_t)1129 binder::Status NetdNativeService::firewallSetUidRule(int32_t, int32_t, int32_t) {
1130     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
1131 }
1132 
firewallEnableChildChain(int32_t,bool)1133 binder::Status NetdNativeService::firewallEnableChildChain(int32_t, bool) {
1134     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
1135 }
1136 
firewallAddUidInterfaceRules(const std::string &,const std::vector<int32_t> &)1137 binder::Status NetdNativeService::firewallAddUidInterfaceRules(const std::string&,
1138                                                                const std::vector<int32_t>&) {
1139     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
1140 }
1141 
firewallRemoveUidInterfaceRules(const std::vector<int32_t> &)1142 binder::Status NetdNativeService::firewallRemoveUidInterfaceRules(const std::vector<int32_t>&) {
1143     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
1144 }
1145 
tetherAddForward(const std::string & intIface,const std::string & extIface)1146 binder::Status NetdNativeService::tetherAddForward(const std::string& intIface,
1147                                                    const std::string& extIface) {
1148     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
1149 
1150     int res = gCtls->tetherCtrl.enableNat(intIface.c_str(), extIface.c_str());
1151     return statusFromErrcode(res);
1152 }
1153 
tetherRemoveForward(const std::string & intIface,const std::string & extIface)1154 binder::Status NetdNativeService::tetherRemoveForward(const std::string& intIface,
1155                                                       const std::string& extIface) {
1156     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
1157     int res = gCtls->tetherCtrl.disableNat(intIface.c_str(), extIface.c_str());
1158     return statusFromErrcode(res);
1159 }
1160 
setTcpRWmemorySize(const std::string & rmemValues,const std::string & wmemValues)1161 binder::Status NetdNativeService::setTcpRWmemorySize(const std::string& rmemValues,
1162                                                      const std::string& wmemValues) {
1163     ENFORCE_NETWORK_STACK_PERMISSIONS();
1164     if (!WriteStringToFile(rmemValues, TCP_RMEM_PROC_FILE)) {
1165         int ret = -errno;
1166         return statusFromErrcode(ret);
1167     }
1168 
1169     if (!WriteStringToFile(wmemValues, TCP_WMEM_PROC_FILE)) {
1170         int ret = -errno;
1171         return statusFromErrcode(ret);
1172     }
1173     return binder::Status::ok();
1174 }
1175 
registerUnsolicitedEventListener(const android::sp<android::net::INetdUnsolicitedEventListener> & listener)1176 binder::Status NetdNativeService::registerUnsolicitedEventListener(
1177         const android::sp<android::net::INetdUnsolicitedEventListener>& listener) {
1178     ENFORCE_NETWORK_STACK_PERMISSIONS();
1179     gCtls->eventReporter.registerUnsolEventListener(listener);
1180     return binder::Status::ok();
1181 }
1182 
getOemNetd(android::sp<android::IBinder> * listener)1183 binder::Status NetdNativeService::getOemNetd(android::sp<android::IBinder>* listener) {
1184     ENFORCE_NETWORK_STACK_PERMISSIONS();
1185     *listener = com::android::internal::net::OemNetdListener::getListener();
1186 
1187     return binder::Status::ok();
1188 }
1189 
getFwmarkForNetwork(int32_t netId,MarkMaskParcel * markMask)1190 binder::Status NetdNativeService::getFwmarkForNetwork(int32_t netId, MarkMaskParcel* markMask) {
1191     ENFORCE_NETWORK_STACK_PERMISSIONS();
1192 
1193     Fwmark fwmark;
1194     fwmark.netId = netId;
1195     markMask->mask = FWMARK_NET_ID_MASK;
1196     markMask->mark = fwmark.intValue;
1197     return binder::Status::ok();
1198 }
1199 
1200 // TODO: remark @deprecated in INetd.aidl.
tetherOffloadRuleAdd(const TetherOffloadRuleParcel &)1201 binder::Status NetdNativeService::tetherOffloadRuleAdd(const TetherOffloadRuleParcel& /* rule */) {
1202     // deprecated
1203     ENFORCE_NETWORK_STACK_PERMISSIONS();
1204     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
1205 }
1206 
1207 // TODO: remark @deprecated in INetd.aidl.
tetherOffloadRuleRemove(const TetherOffloadRuleParcel &)1208 binder::Status NetdNativeService::tetherOffloadRuleRemove(
1209         const TetherOffloadRuleParcel& /* rule */) {
1210     // deprecated
1211     ENFORCE_NETWORK_STACK_PERMISSIONS();
1212     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
1213 }
1214 
1215 // TODO: remark @deprecated in INetd.aidl.
tetherOffloadGetStats(std::vector<TetherStatsParcel> *)1216 binder::Status NetdNativeService::tetherOffloadGetStats(
1217         std::vector<TetherStatsParcel>* /* tetherStatsParcelVec */) {
1218     // deprecated
1219     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
1220     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
1221 }
1222 
1223 // TODO: remark @deprecated in INetd.aidl.
tetherOffloadSetInterfaceQuota(int,int64_t)1224 binder::Status NetdNativeService::tetherOffloadSetInterfaceQuota(int /* ifIndex */,
1225                                                                  int64_t /* quotaBytes */) {
1226     // deprecated
1227     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
1228     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
1229 }
1230 
1231 // TODO: remark @deprecated in INetd.aidl.
tetherOffloadGetAndClearStats(int,android::net::TetherStatsParcel *)1232 binder::Status NetdNativeService::tetherOffloadGetAndClearStats(
1233         int /* ifIndex */, android::net::TetherStatsParcel* /* tetherStats */) {
1234     // deprecated
1235     NETD_LOCKING_RPC(gCtls->tetherCtrl.lock, PERM_NETWORK_STACK, PERM_MAINLINE_NETWORK_STACK);
1236     return binder::Status::fromExceptionCode(binder::Status::EX_UNSUPPORTED_OPERATION);
1237 }
1238 
1239 }  // namespace net
1240 }  // namespace android
1241