Updated documentation for 0.2 release
[mtetherd] / mtetherd.c
1 /*
2   mtetherd
3   (c) 2010 Gregor Riepl <onitake@gmail.com>
4   
5   Tethering utility for Maemo
6   
7   This program is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11   
12   This program is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16   
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <signal.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #include <sys/sysctl.h>
30 #include <sys/wait.h>
31 #include <dbus/dbus.h>
32 #include "device.h"
33
34 static const char *INETDEV = "gprs0";
35 static const char *DEVICES[] = {
36         "usb0",
37         "bnep0",
38         NULL
39 };
40 static const char *ADDRESSES[] = {
41         "192.168.253.254",
42         "192.168.254.254",
43         NULL
44 };
45 static const char *STARTADDRESSES[] = {
46         "192.168.253.1",
47         "192.168.254.1",
48         NULL
49 };
50 static const char *ENDADDRESSES[] = {
51         "192.168.253.254",
52         "192.168.254.254",
53         NULL
54 };
55 // Wait x seconds for process termination
56 static const unsigned int TERMINATE_WAIT = 5;
57 // Poll the main loop after x milliseconds
58 static const unsigned int POLL_MAINLOOP = 500;
59
60 // Run loop active flag
61 static int running;
62 // Number of active tethering connections
63 static unsigned int active;
64
65 static void siginthandler(int sig) {
66         if (running) {
67                 fprintf(stderr, "SIGINIT received, exiting\n");
68                 running = 0;
69         } else {
70                 fprintf(stderr, "Another SIGINIT received, aborting\n");
71                 if (kill(getpid(), SIGKILL) == -1) {
72                         fprintf(stderr, "PANIC! Error killing self: %s\n", strerror(errno));
73                 }
74         }
75 }
76
77 static int launch(const char *args[]) {
78         pid_t pid = fork();
79         if (pid == 0) {
80                 if (execv(args[0], (char **const) args) == -1) {
81                         fprintf(stderr, "Error launching external process %s: %s\n", args[0], strerror(errno));
82                         exit(1);
83                 }
84         } else if (pid == -1) {
85                 fprintf(stderr, "Can't fork external process %s: %s\n", args[0], strerror(errno));
86                 return -1;
87         } else {
88                 int status = 0;
89                 if (waitpid(pid, &status, WNOHANG) == -1) {
90                         fprintf(stderr, "Error waiting for child process completion: %s\n", strerror(errno));
91                         return -2;
92                 }
93                 size_t i;
94                 for (i = 0; i < TERMINATE_WAIT && !WIFEXITED(status); i++) {
95                         if (WIFEXITED(status)) {
96                                 if (WEXITSTATUS(status) != 0) {
97                                         fprintf(stderr, "Child process returned error: %d\n", WEXITSTATUS(status));
98                                         return -3;
99                                 }
100                         } else if (WIFSIGNALED(status)) {
101                                 fprintf(stderr, "Child process killed by signal: %d\n", WTERMSIG(status));
102                                 return -4;
103                         }
104                         sleep(1);
105                         if (waitpid(pid, &status, WNOHANG) == -1) {
106                                 fprintf(stderr, "Error waiting for child process completion: %s\n", strerror(errno));
107                                 return -2;
108                         }
109                 }
110                 if (i >= TERMINATE_WAIT) {
111                         fprintf(stderr, "Child process %s still running after %u seconds, ignoring.\n", args[0], TERMINATE_WAIT);
112                         return -5;
113                 }
114         }
115         return 0;
116 }
117
118 static void added(Device *device, const char *inetdev) {
119         printf("Got org.kernel.kevent.add on %s\n", device->name);
120         char *runfile = NULL;
121         if (asprintf(&runfile, "/var/run/tethering.%s.pid", device->name) == -1) {
122                 fprintf(stderr, "Can't construct PID file name for device %s: %s\n", device->name, strerror(errno));
123                 return;
124         }
125         char *range = NULL;
126         if (asprintf(&range, "%s,%s,3600", device->startaddress, device->endaddress) == -1) {
127                 fprintf(stderr, "Can't construct address range parameter for device %s: %s\n", device->name, strerror(errno));
128                 free(runfile);
129                 return;
130         }
131         const char *ifconfig[] = { "/sbin/ifconfig", device->name, device->address, "up", NULL };
132         const char *modprobe[] = { "/sbin/modprobe", "ipt_MASQUERADE", NULL };
133         const char *iptables[] = { "/usr/sbin/iptables", "-t", "nat", "-A", "POSTROUTING", "-o", inetdev, "-j", "MASQUERADE", NULL };
134         const char *dnsmasq[] = { "/sbin/start-stop-daemon", "-S", "-p", runfile, "-b", "-x", "/usr/sbin/dnsmasq", "--", "-x", runfile, "-k", "-I", "lo", "-i", device->name, "-a", device->address, "-z", "-F", range, NULL };
135         char *forwsysctl = NULL;
136         if (asprintf(&forwsysctl, "/proc/sys/net/ipv4/conf/%s/forwarding", device->name) == -1) {
137                 fprintf(stderr, "Can't construct sysctl path for device %s: %s\n", device->name, strerror(errno));
138                 free(runfile);
139                 free(range);
140                 return;
141         }
142         char *inetforwsysctl = NULL;
143         if (asprintf(&inetforwsysctl, "/proc/sys/net/ipv4/conf/%s/forwarding", inetdev) == -1) {
144                 fprintf(stderr, "Can't construct inet sysctl path for device %s: %s\n", inetdev, strerror(errno));
145                 free(runfile);
146                 free(range);
147                 free(forwsysctl);
148                 return;
149         }
150
151
152         if (launch(ifconfig) == 0) {
153                 if (launch(modprobe) == 0) {
154                         if (launch(iptables) == 0) {
155                                 if (launch(dnsmasq) == 0) {
156                                         int ffd = open(forwsysctl, O_WRONLY, 0666);
157                                         if (ffd < 0) {
158                                                 fprintf(stderr, "Can't enable forwarding on PAN device %s: %s\n", device->name, strerror(errno));
159                                         } else {
160                                                 if (write(ffd, "1", 1) == -1) {
161                                                         fprintf(stderr, "Can't enable forwarding on PAN device %s: %s\n", device->name, strerror(errno));
162                                                 } else {
163                                                         int ifd = open(inetforwsysctl, O_WRONLY, 0666);
164                                                         if (ifd < 0) {
165                                                                 fprintf(stderr, "Can't enable forwarding on WAN device %s (path %s): %s\n", inetdev, inetforwsysctl, strerror(errno));
166                                                         } else {
167                                                                 if (write(ifd, "1", 1) == -1) {
168                                                                         fprintf(stderr, "Can't enable forwarding on WAN device %s: %s\n", inetdev, strerror(errno));
169                                                                 }
170                                                                 close(ifd);
171                                                         }
172                                                 }
173                                                 close(ffd);
174                                         }
175                                 }
176                         }
177                 }
178         }
179
180         free(range);
181         free(runfile);
182         free(forwsysctl);
183         free(inetforwsysctl);
184
185         active++;
186 }
187
188 static void removed(Device *device, const char *inetdev) {
189         printf("Got org.kernel.kevent.remove on %s\n", device->name);
190
191         char *runfile = NULL;
192         if (asprintf(&runfile, "/var/run/tethering.%s.pid", device->name) == -1) {
193                 fprintf(stderr, "Can't construct PID file name for device %s: %s\n", device->name, strerror(errno));
194                 return;
195         }
196         const char *dnsmasq[] = { "/sbin/start-stop-daemon", "-K", "-p", runfile, "-x", "/usr/sbin/dnsmasq", NULL };
197         const char *iptables[] = { "/usr/sbin/iptables", "-t", "nat", "-D", "POSTROUTING", "-o", inetdev, "-j", "MASQUERADE", NULL };
198
199         // Errors are ignored here: we just disable as much as we can.
200         launch(dnsmasq);
201         if (unlink(runfile) == -1) {
202                 fprintf(stderr, "Error removing PID file for device %s: %s\n", device->name, strerror(errno));
203         }
204         launch(iptables);
205
206         free(runfile);
207
208         if (active > 0) active--;
209         if (active == 0) {
210                 char *inetforwsysctl = NULL;
211                 if (asprintf(&inetforwsysctl, "/proc/sys/net/ipv4/conf/%s/forwarding", inetdev) == -1) {
212                         fprintf(stderr, "Can't construct inet sysctl path for device %s: %s\n", inetdev, strerror(errno));
213                         return;
214                 }
215                 int fd = open(inetforwsysctl, O_WRONLY, 0666);
216                 if (fd < 0) {
217                         fprintf(stderr, "Can't enable forwarding on WAN device %s: %s\n", inetdev, strerror(errno));
218                 } else {
219                         if (write(fd, "0", 1) == -1) {
220                                 fprintf(stderr, "Can't enable forwarding on WAN device %s: %s\n", inetdev, strerror(errno));
221                         }
222                         close(fd);
223                 }
224                 free(inetforwsysctl);
225         }
226 }
227
228 int main(int argc, const char *argv[]) {
229         active = 0;
230
231         Device *devices = NULL;
232         Device *node = NULL;
233         size_t i;
234         for (i = 0; DEVICES[i]; i++) {
235                 Device *device = device_new(DEVICES[i]);
236                 if (device) {
237                         device_set_address(device, ADDRESSES[i]);
238                         device_set_startaddress(device, STARTADDRESSES[i]);
239                         device_set_endaddress(device, ENDADDRESSES[i]);
240                         if (device_validate(device)) {
241                                 node = device_append(node, device);
242                                 if (!devices) {
243                                         devices = node;
244                                 }
245                         } else {
246                                 device_delete(device);
247                         }
248                 }
249         }
250
251         if (!devices) {
252                 fprintf(stderr, "Warning, no devices configured. I will just sit here and wait for nicer weather.\n");
253         }
254
255         DBusError err;
256         dbus_error_init(&err);
257         DBusConnection *conn = dbus_bus_get(DBUS_BUS_SYSTEM, &err);
258         if (dbus_error_is_set(&err)) {
259                 fprintf(stderr, "Error %s occured: %s\n", err.name, err.message);
260                 dbus_error_free(&err);
261         }
262         if (!conn) {
263                 return 1;
264         }
265
266         for (node = devices; node; node = node->next) {
267                 char *filter = NULL;
268                 if (!asprintf(&filter, "type='signal',interface='org.kernel.kevent',path='/org/kernel/class/net/%s'", node->name)) {
269                         fprintf(stderr, "Can't construct filter rule for device %s: %s\n", node->name, strerror(errno));
270                 } else {
271                         dbus_bus_add_match(conn, filter, NULL);
272                         free(filter);
273                 }
274         }
275         dbus_connection_flush(conn);
276
277         running = 1;
278         signal(SIGINT, siginthandler);
279         while (running) {
280                 dbus_connection_read_write(conn, POLL_MAINLOOP);
281                 DBusMessage* msg = dbus_connection_pop_message(conn);
282                 if (msg) {
283                         if (dbus_message_is_signal(msg, "org.kernel.kevent", "add")) {
284                                 char **path = NULL;
285                                 if (!dbus_message_get_path_decomposed(msg, &path)) {
286                                         fprintf(stderr, "Can't get add message path!\n");
287                                 } else {
288                                         unsigned int last;
289                                         for (last = 0; path[last] && last <= 6; last++);
290                                         if (last == 0 || last > 6) {
291                                                 fprintf(stderr, "Add message has no path or path too long!\n");
292                                         } else {
293                                                 Device *device = device_search(devices, path[last - 1]);
294                                                 if (device) {
295                                                         added(device, INETDEV);
296                                                 }
297                                         }
298                                         dbus_free_string_array(path);
299                                 }
300                         } else if (dbus_message_is_signal(msg, "org.kernel.kevent", "remove")) {
301                                 char **path = NULL;
302                                 if (!dbus_message_get_path_decomposed(msg, &path)) {
303                                         fprintf(stderr, "Can't get remove message path!\n");
304                                 } else {
305                                         unsigned int last;
306                                         for (last = 0; path[last] && last <= 6; last++);
307                                         if (last == 0 || last > 6) {
308                                                 fprintf(stderr, "Remove message has no path or path too long!\n");
309                                         } else {
310                                                 Device *device = device_search(devices, path[last - 1]);
311                                                 if (device) {
312                                                         removed(device, INETDEV);
313                                                 }
314                                         }
315                                         dbus_free_string_array(path);
316                                 }
317                         }
318                         dbus_message_unref(msg);
319                 }
320         }
321
322         device_delete_all(devices);
323         dbus_connection_unref(conn);
324         return 0;
325 }