OSDN Git Service

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