• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <stdarg.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <errno.h>
22 
23 #define LOG_TAG "Netd"
24 
25 #include <log/log.h>
26 
27 #include <android-base/parseint.h>
28 #include <android-base/strings.h>
29 #include <netutils/ifc.h>
30 #include <sysutils/NetlinkEvent.h>
31 #include "Controllers.h"
32 #include "NetlinkHandler.h"
33 #include "NetlinkManager.h"
34 #include "SockDiag.h"
35 
36 #include <charconv>
37 
38 #define BINDER_RETRY(exp)                                                       \
39     ({                                                                          \
40         bool res = true;                                                        \
41         for (int attempt = 0; /*nop*/; ++attempt) {                             \
42             auto _rc = (exp);                                                   \
43             if (_rc.exceptionCode() == binder::Status::EX_TRANSACTION_FAILED && \
44                 attempt < RETRY_ATTEMPTS) {                                     \
45                 usleep(RETRY_INTERVAL_MICRO_S);                                 \
46             } else {                                                            \
47                 res = _rc.isOk();                                               \
48                 break;                                                          \
49             }                                                                   \
50         }                                                                       \
51         res;                                                                    \
52     })
53 
54 #define LOG_EVENT_FUNC(retry, func, ...)                                                    \
55     do {                                                                                    \
56         const auto listenerMap = gCtls->eventReporter.getNetdUnsolicitedEventListenerMap(); \
57         for (auto& listener : listenerMap) {                                                \
58             auto entry = gUnsolicitedLog.newEntry().function(#func).args(__VA_ARGS__);      \
59             if (retry(listener.first->func(__VA_ARGS__))) {                                 \
60                 gUnsolicitedLog.log(entry.withAutomaticDuration());                         \
61             }                                                                               \
62         }                                                                                   \
63     } while (0)
64 
65 namespace android {
66 namespace net {
67 
68 constexpr int RETRY_ATTEMPTS = 2;
69 constexpr int RETRY_INTERVAL_MICRO_S = 100000;
70 
NetlinkHandler(NetlinkManager * nm,int listenerSocket,int format)71 NetlinkHandler::NetlinkHandler(NetlinkManager *nm, int listenerSocket,
72                                int format) :
73                         NetlinkListener(listenerSocket, format) {
74     mNm = nm;
75 }
76 
~NetlinkHandler()77 NetlinkHandler::~NetlinkHandler() {
78 }
79 
start()80 int NetlinkHandler::start() {
81     return this->startListener();
82 }
83 
stop()84 int NetlinkHandler::stop() {
85     return this->stopListener();
86 }
87 
parseIfIndex(const char * ifIndex)88 static long parseIfIndex(const char* ifIndex) {
89     if (ifIndex == nullptr) {
90         return 0;
91     }
92     long ifaceIndex = strtol(ifIndex, nullptr, 10);
93     // strtol returns 0 on error, which is fine because 0 is not a valid ifindex.
94     if (errno == ERANGE && (ifaceIndex == LONG_MAX || ifaceIndex == LONG_MIN)) {
95         return 0;
96     }
97     return ifaceIndex;
98 }
99 
onEvent(NetlinkEvent * evt)100 void NetlinkHandler::onEvent(NetlinkEvent *evt) {
101     const char *subsys = evt->getSubsystem();
102     if (!subsys) {
103         ALOGW("No subsystem found in netlink event");
104         return;
105     }
106 
107     if (!strcmp(subsys, "net")) {
108         NetlinkEvent::Action action = evt->getAction();
109         const char *iface = evt->findParam("INTERFACE") ?: "";
110         if (action == NetlinkEvent::Action::kAdd) {
111             notifyInterfaceAdded(iface);
112         } else if (action == NetlinkEvent::Action::kRemove) {
113             notifyInterfaceRemoved(iface);
114         } else if (action == NetlinkEvent::Action::kChange) {
115             evt->dump();
116             notifyInterfaceChanged("nana", true);
117         } else if (action == NetlinkEvent::Action::kLinkUp) {
118             notifyInterfaceLinkChanged(iface, true);
119         } else if (action == NetlinkEvent::Action::kLinkDown) {
120             notifyInterfaceLinkChanged(iface, false);
121         } else if (action == NetlinkEvent::Action::kAddressUpdated ||
122                    action == NetlinkEvent::Action::kAddressRemoved) {
123             const char *address = evt->findParam("ADDRESS");
124             const char *flags = evt->findParam("FLAGS");
125             const char *scope = evt->findParam("SCOPE");
126             const char *ifIndex = evt->findParam("IFINDEX");
127             char addrstr[INET6_ADDRSTRLEN + strlen("/128")];
128             strlcpy(addrstr, address, sizeof(addrstr));
129             char *slash = strchr(addrstr, '/');
130             if (slash) {
131                 *slash = '\0';
132             }
133 
134             long ifaceIndex = parseIfIndex(ifIndex);
135             if (!ifaceIndex) {
136                 ALOGE("invalid interface index: %s(%s)", iface, ifIndex);
137             }
138             const bool addrUpdated = (action == NetlinkEvent::Action::kAddressUpdated);
139             if (addrUpdated) {
140                 gCtls->netCtrl.addInterfaceAddress(ifaceIndex, address);
141             } else {  // action == NetlinkEvent::Action::kAddressRemoved
142                 bool shouldDestroy = gCtls->netCtrl.removeInterfaceAddress(ifaceIndex, address);
143                 if (shouldDestroy) {
144                     SockDiag sd;
145                     if (sd.open()) {
146                         // Pass the interface index iff. destroying sockets on a link-local address.
147                         // This cannot use an interface name as the interface might no longer exist.
148                         int destroyIfaceIndex =
149                                 std::string_view(addrstr).starts_with("fe80:") ? ifaceIndex : 0;
150                         int ret = sd.destroySockets(addrstr, destroyIfaceIndex);
151                         if (ret < 0) {
152                             ALOGE("Error destroying sockets: %s", strerror(-ret));
153                         }
154                     } else {
155                         ALOGE("Error opening NETLINK_SOCK_DIAG socket: %s", strerror(errno));
156                     }
157                 }
158             }
159             // Note: if this interface was deleted, iface is "" and we don't notify.
160             if (iface && iface[0] && address && flags && scope) {
161                 if (addrUpdated) {
162                     notifyAddressUpdated(address, iface, std::stoi(flags), std::stoi(scope));
163                 } else {
164                     notifyAddressRemoved(address, iface, std::stoi(flags), std::stoi(scope));
165                 }
166             }
167         } else if (action == NetlinkEvent::Action::kRdnss) {
168             const char *lifetime = evt->findParam("LIFETIME");
169             const char *servers = evt->findParam("SERVERS");
170             if (lifetime && servers) {
171                 notifyInterfaceDnsServers(iface, strtol(lifetime, nullptr, 10),
172                                           android::base::Split(servers, ","));
173             }
174         } else if (action == NetlinkEvent::Action::kRouteUpdated ||
175                    action == NetlinkEvent::Action::kRouteRemoved) {
176             const char *route = evt->findParam("ROUTE");
177             const char *gateway = evt->findParam("GATEWAY");
178             const char *iface = evt->findParam("INTERFACE");
179             if (route && (gateway || iface)) {
180                 notifyRouteChange((action == NetlinkEvent::Action::kRouteUpdated) ? true : false,
181                                   route, (gateway == nullptr) ? "" : gateway,
182                                   (iface == nullptr) ? "" : iface);
183             }
184         }
185 
186     } else if (!strcmp(subsys, "qlog") || !strcmp(subsys, "xt_quota2")) {
187         const char *alertName = evt->findParam("ALERT_NAME");
188         const char *iface = evt->findParam("INTERFACE");
189         if (alertName && iface) {
190             notifyQuotaLimitReached(alertName, iface);
191         }
192 
193     } else if (!strcmp(subsys, "strict")) {
194         const char *uid = evt->findParam("UID");
195         const char *hex = evt->findParam("HEX");
196         if (uid && hex) {
197             notifyStrictCleartext(strtol(uid, nullptr, 10), hex);
198         }
199 
200     } else if (!strcmp(subsys, "xt_idletimer")) {
201         const char *label = evt->findParam("INTERFACE");
202         const char *state = evt->findParam("STATE");
203         const char *timestamp = evt->findParam("TIME_NS");
204         const char *uid = evt->findParam("UID");
205         if (state) {
206             bool isActive = !strcmp("active", state);
207             int64_t processTimestamp = (timestamp == nullptr) ? 0 : strtoll(timestamp, nullptr, 10);
208             int intLabel;
209             // NMS only accepts interface class activity changes with integer labels, and only ever
210             // creates idletimers with integer labels.
211             if (android::base::ParseInt(label, &intLabel)) {
212                 const long reportedUid =
213                         (uid != nullptr && isActive) ? strtol(uid, nullptr, 10) : -1;
214                 notifyInterfaceClassActivityChanged(intLabel, isActive, processTimestamp,
215                                                     reportedUid);
216             }
217         }
218 
219 #if !LOG_NDEBUG
220     } else if (strcmp(subsys, "platform") && strcmp(subsys, "backlight")) {
221         /* It is not a VSYNC or a backlight event */
222         ALOGV("unexpected event from subsystem %s", subsys);
223 #endif
224     }
225 }
226 
notifyInterfaceAdded(const std::string & ifName)227 void NetlinkHandler::notifyInterfaceAdded(const std::string& ifName) {
228     LOG_EVENT_FUNC(BINDER_RETRY, onInterfaceAdded, ifName);
229 }
230 
notifyInterfaceRemoved(const std::string & ifName)231 void NetlinkHandler::notifyInterfaceRemoved(const std::string& ifName) {
232     LOG_EVENT_FUNC(BINDER_RETRY, onInterfaceRemoved, ifName);
233 }
234 
notifyInterfaceChanged(const std::string & ifName,bool up)235 void NetlinkHandler::notifyInterfaceChanged(const std::string& ifName, bool up) {
236     LOG_EVENT_FUNC(BINDER_RETRY, onInterfaceChanged, ifName, up);
237 }
238 
notifyInterfaceLinkChanged(const std::string & ifName,bool up)239 void NetlinkHandler::notifyInterfaceLinkChanged(const std::string& ifName, bool up) {
240     LOG_EVENT_FUNC(BINDER_RETRY, onInterfaceLinkStateChanged, ifName, up);
241 }
242 
notifyQuotaLimitReached(const std::string & labelName,const std::string & ifName)243 void NetlinkHandler::notifyQuotaLimitReached(const std::string& labelName,
244                                              const std::string& ifName) {
245     LOG_EVENT_FUNC(BINDER_RETRY, onQuotaLimitReached, labelName, ifName);
246 }
247 
notifyInterfaceClassActivityChanged(int label,bool isActive,int64_t timestamp,int uid)248 void NetlinkHandler::notifyInterfaceClassActivityChanged(int label, bool isActive,
249                                                          int64_t timestamp, int uid) {
250     LOG_EVENT_FUNC(BINDER_RETRY, onInterfaceClassActivityChanged, isActive, label, timestamp, uid);
251 }
252 
notifyAddressUpdated(const std::string & addr,const std::string & ifName,int flags,int scope)253 void NetlinkHandler::notifyAddressUpdated(const std::string& addr, const std::string& ifName,
254                                           int flags, int scope) {
255     LOG_EVENT_FUNC(BINDER_RETRY, onInterfaceAddressUpdated, addr, ifName, flags, scope);
256 }
257 
notifyAddressRemoved(const std::string & addr,const std::string & ifName,int flags,int scope)258 void NetlinkHandler::notifyAddressRemoved(const std::string& addr, const std::string& ifName,
259                                           int flags, int scope) {
260     LOG_EVENT_FUNC(BINDER_RETRY, onInterfaceAddressRemoved, addr, ifName, flags, scope);
261 }
262 
notifyInterfaceDnsServers(const std::string & ifName,int64_t lifetime,const std::vector<std::string> & servers)263 void NetlinkHandler::notifyInterfaceDnsServers(const std::string& ifName, int64_t lifetime,
264                                                const std::vector<std::string>& servers) {
265     LOG_EVENT_FUNC(BINDER_RETRY, onInterfaceDnsServerInfo, ifName, lifetime, servers);
266 }
267 
notifyRouteChange(bool updated,const std::string & route,const std::string & gateway,const std::string & ifName)268 void NetlinkHandler::notifyRouteChange(bool updated, const std::string& route,
269                                        const std::string& gateway, const std::string& ifName) {
270     LOG_EVENT_FUNC(BINDER_RETRY, onRouteChanged, updated, route, gateway, ifName);
271 }
272 
notifyStrictCleartext(uid_t uid,const std::string & hex)273 void NetlinkHandler::notifyStrictCleartext(uid_t uid, const std::string& hex) {
274     LOG_EVENT_FUNC(BINDER_RETRY, onStrictCleartextDetected, uid, hex);
275 }
276 
277 }  // namespace net
278 }  // namespace android
279