• 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 <stdlib.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <netdb.h>
21 #include <string.h>
22 
23 #include <sys/socket.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <sys/wait.h>
27 
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
30 
31 #define LOG_TAG "TetherController"
32 #include <cutils/log.h>
33 #include <cutils/properties.h>
34 
35 #include "Fwmark.h"
36 #include "NetdConstants.h"
37 #include "Permission.h"
38 #include "InterfaceController.h"
39 #include "NetworkController.h"
40 #include "TetherController.h"
41 
42 namespace {
43 
44 const char BP_TOOLS_MODE[] = "bp-tools";
45 const char IPV4_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv4/ip_forward";
46 const char IPV6_FORWARDING_PROC_FILE[] = "/proc/sys/net/ipv6/conf/all/forwarding";
47 const char SEPARATOR[] = "|";
48 constexpr const char kTcpBeLiberal[] = "/proc/sys/net/netfilter/nf_conntrack_tcp_be_liberal";
49 
writeToFile(const char * filename,const char * value)50 bool writeToFile(const char* filename, const char* value) {
51     int fd = open(filename, O_WRONLY | O_CLOEXEC);
52     if (fd < 0) {
53         ALOGE("Failed to open %s: %s", filename, strerror(errno));
54         return false;
55     }
56 
57     const ssize_t len = strlen(value);
58     if (write(fd, value, len) != len) {
59         ALOGE("Failed to write %s to %s: %s", value, filename, strerror(errno));
60         close(fd);
61         return false;
62     }
63     close(fd);
64     return true;
65 }
66 
67 // TODO: Consider altering TCP and UDP timeouts as well.
configureForTethering(bool enabled)68 void configureForTethering(bool enabled) {
69     writeToFile(kTcpBeLiberal, enabled ? "1" : "0");
70 }
71 
configureForIPv6Router(const char * interface)72 bool configureForIPv6Router(const char *interface) {
73     return (InterfaceController::setEnableIPv6(interface, 0) == 0)
74             && (InterfaceController::setAcceptIPv6Ra(interface, 0) == 0)
75             && (InterfaceController::setAcceptIPv6Dad(interface, 0) == 0)
76             && (InterfaceController::setIPv6DadTransmits(interface, "0") == 0)
77             && (InterfaceController::setEnableIPv6(interface, 1) == 0);
78 }
79 
configureForIPv6Client(const char * interface)80 void configureForIPv6Client(const char *interface) {
81     InterfaceController::setAcceptIPv6Ra(interface, 1);
82     InterfaceController::setAcceptIPv6Dad(interface, 1);
83     InterfaceController::setIPv6DadTransmits(interface, "1");
84     InterfaceController::setEnableIPv6(interface, 0);
85 }
86 
inBpToolsMode()87 bool inBpToolsMode() {
88     // In BP tools mode, do not disable IP forwarding
89     char bootmode[PROPERTY_VALUE_MAX] = {0};
90     property_get("ro.bootmode", bootmode, "unknown");
91     return !strcmp(BP_TOOLS_MODE, bootmode);
92 }
93 
94 }  // namespace
95 
96 namespace android {
97 namespace net {
98 
TetherController()99 TetherController::TetherController() {
100     mDnsNetId = 0;
101     mDaemonFd = -1;
102     mDaemonPid = 0;
103     if (inBpToolsMode()) {
104         enableForwarding(BP_TOOLS_MODE);
105     } else {
106         setIpFwdEnabled();
107     }
108 }
109 
~TetherController()110 TetherController::~TetherController() {
111     mInterfaces.clear();
112     mDnsForwarders.clear();
113     mForwardingRequests.clear();
114 }
115 
setIpFwdEnabled()116 bool TetherController::setIpFwdEnabled() {
117     bool success = true;
118     const char* value = mForwardingRequests.empty() ? "0" : "1";
119     ALOGD("Setting IP forward enable = %s", value);
120     success &= writeToFile(IPV4_FORWARDING_PROC_FILE, value);
121     success &= writeToFile(IPV6_FORWARDING_PROC_FILE, value);
122     return success;
123 }
124 
enableForwarding(const char * requester)125 bool TetherController::enableForwarding(const char* requester) {
126     // Don't return an error if this requester already requested forwarding. Only return errors for
127     // things that the caller caller needs to care about, such as "couldn't write to the file to
128     // enable forwarding".
129     mForwardingRequests.insert(requester);
130     return setIpFwdEnabled();
131 }
132 
disableForwarding(const char * requester)133 bool TetherController::disableForwarding(const char* requester) {
134     mForwardingRequests.erase(requester);
135     return setIpFwdEnabled();
136 }
137 
forwardingRequestCount()138 size_t TetherController::forwardingRequestCount() {
139     return mForwardingRequests.size();
140 }
141 
142 #define TETHER_START_CONST_ARG        10
143 
startTethering(int num_addrs,char ** dhcp_ranges)144 int TetherController::startTethering(int num_addrs, char **dhcp_ranges) {
145     if (mDaemonPid != 0) {
146         ALOGE("Tethering already started");
147         errno = EBUSY;
148         return -1;
149     }
150 
151     ALOGD("Starting tethering services");
152 
153     pid_t pid;
154     int pipefd[2];
155 
156     if (pipe(pipefd) < 0) {
157         ALOGE("pipe failed (%s)", strerror(errno));
158         return -1;
159     }
160 
161     /*
162      * TODO: Create a monitoring thread to handle and restart
163      * the daemon if it exits prematurely
164      */
165     if ((pid = fork()) < 0) {
166         ALOGE("fork failed (%s)", strerror(errno));
167         close(pipefd[0]);
168         close(pipefd[1]);
169         return -1;
170     }
171 
172     if (!pid) {
173         close(pipefd[1]);
174         if (pipefd[0] != STDIN_FILENO) {
175             if (dup2(pipefd[0], STDIN_FILENO) != STDIN_FILENO) {
176                 ALOGE("dup2 failed (%s)", strerror(errno));
177                 return -1;
178             }
179             close(pipefd[0]);
180         }
181 
182         Fwmark fwmark;
183         fwmark.netId = NetworkController::LOCAL_NET_ID;
184         fwmark.explicitlySelected = true;
185         fwmark.protectedFromVpn = true;
186         fwmark.permission = PERMISSION_SYSTEM;
187         char markStr[UINT32_HEX_STRLEN];
188         snprintf(markStr, sizeof(markStr), "0x%x", fwmark.intValue);
189 
190         int num_processed_args = TETHER_START_CONST_ARG + (num_addrs/2) + 1;
191         char **args = (char **)malloc(sizeof(char *) * num_processed_args);
192         args[num_processed_args - 1] = NULL;
193         args[0] = (char *)"/system/bin/dnsmasq";
194         args[1] = (char *)"--keep-in-foreground";
195         args[2] = (char *)"--no-resolv";
196         args[3] = (char *)"--no-poll";
197         args[4] = (char *)"--dhcp-authoritative";
198         // TODO: pipe through metered status from ConnService
199         args[5] = (char *)"--dhcp-option-force=43,ANDROID_METERED";
200         args[6] = (char *)"--pid-file";
201         args[7] = (char *)"--listen-mark";
202         args[8] = (char *)markStr;
203         args[9] = (char *)"";
204 
205         int nextArg = TETHER_START_CONST_ARG;
206         for (int addrIndex = 0; addrIndex < num_addrs; addrIndex += 2) {
207             asprintf(&(args[nextArg++]),"--dhcp-range=%s,%s,1h",
208                      dhcp_ranges[addrIndex], dhcp_ranges[addrIndex+1]);
209         }
210 
211         if (execv(args[0], args)) {
212             ALOGE("execl failed (%s)", strerror(errno));
213         }
214         ALOGE("Should never get here!");
215         _exit(-1);
216     } else {
217         close(pipefd[0]);
218         mDaemonPid = pid;
219         mDaemonFd = pipefd[1];
220         configureForTethering(true);
221         applyDnsInterfaces();
222         ALOGD("Tethering services running");
223     }
224 
225     return 0;
226 }
227 
stopTethering()228 int TetherController::stopTethering() {
229     configureForTethering(false);
230 
231     if (mDaemonPid == 0) {
232         ALOGE("Tethering already stopped");
233         return 0;
234     }
235 
236     ALOGD("Stopping tethering services");
237 
238     kill(mDaemonPid, SIGTERM);
239     waitpid(mDaemonPid, NULL, 0);
240     mDaemonPid = 0;
241     close(mDaemonFd);
242     mDaemonFd = -1;
243     ALOGD("Tethering services stopped");
244     return 0;
245 }
246 
isTetheringStarted()247 bool TetherController::isTetheringStarted() {
248     return (mDaemonPid == 0 ? false : true);
249 }
250 
251 #define MAX_CMD_SIZE 1024
252 
setDnsForwarders(unsigned netId,char ** servers,int numServers)253 int TetherController::setDnsForwarders(unsigned netId, char **servers, int numServers) {
254     int i;
255     char daemonCmd[MAX_CMD_SIZE];
256 
257     Fwmark fwmark;
258     fwmark.netId = netId;
259     fwmark.explicitlySelected = true;
260     fwmark.protectedFromVpn = true;
261     fwmark.permission = PERMISSION_SYSTEM;
262 
263     snprintf(daemonCmd, sizeof(daemonCmd), "update_dns%s0x%x", SEPARATOR, fwmark.intValue);
264     int cmdLen = strlen(daemonCmd);
265 
266     mDnsForwarders.clear();
267     for (i = 0; i < numServers; i++) {
268         ALOGD("setDnsForwarders(0x%x %d = '%s')", fwmark.intValue, i, servers[i]);
269 
270         addrinfo *res, hints = { .ai_flags = AI_NUMERICHOST };
271         int ret = getaddrinfo(servers[i], NULL, &hints, &res);
272         freeaddrinfo(res);
273         if (ret) {
274             ALOGE("Failed to parse DNS server '%s'", servers[i]);
275             mDnsForwarders.clear();
276             errno = EINVAL;
277             return -1;
278         }
279 
280         cmdLen += (strlen(servers[i]) + 1);
281         if (cmdLen + 1 >= MAX_CMD_SIZE) {
282             ALOGD("Too many DNS servers listed");
283             break;
284         }
285 
286         strcat(daemonCmd, SEPARATOR);
287         strcat(daemonCmd, servers[i]);
288         mDnsForwarders.push_back(servers[i]);
289     }
290 
291     mDnsNetId = netId;
292     if (mDaemonFd != -1) {
293         ALOGD("Sending update msg to dnsmasq [%s]", daemonCmd);
294         if (write(mDaemonFd, daemonCmd, strlen(daemonCmd) +1) < 0) {
295             ALOGE("Failed to send update command to dnsmasq (%s)", strerror(errno));
296             mDnsForwarders.clear();
297             errno = EREMOTEIO;
298             return -1;
299         }
300     }
301     return 0;
302 }
303 
getDnsNetId()304 unsigned TetherController::getDnsNetId() {
305     return mDnsNetId;
306 }
307 
getDnsForwarders() const308 const std::list<std::string> &TetherController::getDnsForwarders() const {
309     return mDnsForwarders;
310 }
311 
applyDnsInterfaces()312 bool TetherController::applyDnsInterfaces() {
313     char daemonCmd[MAX_CMD_SIZE];
314 
315     strcpy(daemonCmd, "update_ifaces");
316     int cmdLen = strlen(daemonCmd);
317     bool haveInterfaces = false;
318 
319     for (const auto &ifname : mInterfaces) {
320         cmdLen += (ifname.size() + 1);
321         if (cmdLen + 1 >= MAX_CMD_SIZE) {
322             ALOGD("Too many DNS ifaces listed");
323             break;
324         }
325 
326         strcat(daemonCmd, SEPARATOR);
327         strcat(daemonCmd, ifname.c_str());
328         haveInterfaces = true;
329     }
330 
331     if ((mDaemonFd != -1) && haveInterfaces) {
332         ALOGD("Sending update msg to dnsmasq [%s]", daemonCmd);
333         if (write(mDaemonFd, daemonCmd, strlen(daemonCmd) +1) < 0) {
334             ALOGE("Failed to send update command to dnsmasq (%s)", strerror(errno));
335             return false;
336         }
337     }
338     return true;
339 }
340 
tetherInterface(const char * interface)341 int TetherController::tetherInterface(const char *interface) {
342     ALOGD("tetherInterface(%s)", interface);
343     if (!isIfaceName(interface)) {
344         errno = ENOENT;
345         return -1;
346     }
347 
348     if (!configureForIPv6Router(interface)) {
349         configureForIPv6Client(interface);
350         return -1;
351     }
352     mInterfaces.push_back(interface);
353 
354     if (!applyDnsInterfaces()) {
355         mInterfaces.pop_back();
356         configureForIPv6Client(interface);
357         return -1;
358     } else {
359         return 0;
360     }
361 }
362 
untetherInterface(const char * interface)363 int TetherController::untetherInterface(const char *interface) {
364     ALOGD("untetherInterface(%s)", interface);
365 
366     for (auto it = mInterfaces.cbegin(); it != mInterfaces.cend(); ++it) {
367         if (!strcmp(interface, it->c_str())) {
368             mInterfaces.erase(it);
369 
370             configureForIPv6Client(interface);
371             return applyDnsInterfaces() ? 0 : -1;
372         }
373     }
374     errno = ENOENT;
375     return -1;
376 }
377 
getTetheredInterfaceList() const378 const std::list<std::string> &TetherController::getTetheredInterfaceList() const {
379     return mInterfaces;
380 }
381 
382 }  // namespace net
383 }  // namespace android
384