f6614b29a0b5e13e309fc2b9578e04d745a06b93
[tinc] / src / bsd / device.c
1 /*
2     device.c -- Interaction BSD tun/tap device
3     Copyright (C) 2001-2005 Ivo Timmermans,
4                   2001-2016 Guus Sliepen <guus@tinc-vpn.org>
5                   2009      Grzegorz Dymarek <gregd72002@googlemail.com>
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 2 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 along
18     with this program; if not, write to the Free Software Foundation, Inc.,
19     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 */
21
22 #include "../system.h"
23
24 #include "../conf.h"
25 #include "../device.h"
26 #include "../logger.h"
27 #include "../net.h"
28 #include "../route.h"
29 #include "../utils.h"
30 #include "../xalloc.h"
31
32 #ifdef ENABLE_TUNEMU
33 #include "tunemu.h"
34 #endif
35
36 #ifdef HAVE_NET_IF_UTUN_H
37 #include <sys/sys_domain.h>
38 #include <sys/kern_control.h>
39 #include <net/if_utun.h>
40 #endif
41
42 #define DEFAULT_TUN_DEVICE "/dev/tun0"
43 #define DEFAULT_TAP_DEVICE "/dev/tap0"
44
45 typedef enum device_type {
46         DEVICE_TYPE_TUN,
47         DEVICE_TYPE_TUNIFHEAD,
48         DEVICE_TYPE_TAP,
49 #ifdef ENABLE_TUNEMU
50         DEVICE_TYPE_TUNEMU,
51 #endif
52         DEVICE_TYPE_UTUN,
53 } device_type_t;
54
55 int device_fd = -1;
56 char *device = NULL;
57 char *iface = NULL;
58 static char *device_info = NULL;
59 static uint64_t device_total_in = 0;
60 static uint64_t device_total_out = 0;
61 #if defined(ENABLE_TUNEMU)
62 static device_type_t device_type = DEVICE_TYPE_TUNEMU;
63 #elif defined(HAVE_OPENBSD) || defined(HAVE_FREEBSD) || defined(HAVE_DRAGONFLY)
64 static device_type_t device_type = DEVICE_TYPE_TUNIFHEAD;
65 #else
66 static device_type_t device_type = DEVICE_TYPE_TUN;
67 #endif
68
69 #ifdef HAVE_NET_IF_UTUN_H
70 static bool setup_utun(void) {
71         device_fd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
72         if(device_fd == -1) {
73                 logger(LOG_ERR, "Could not open PF_SYSTEM socket: %s\n", strerror(errno));
74                 return false;
75         }
76
77         struct ctl_info info = {};
78         strlcpy(info.ctl_name, UTUN_CONTROL_NAME, sizeof(info.ctl_name));
79
80         if(ioctl(device_fd, CTLIOCGINFO, &info) == -1) {
81                 logger(LOG_ERR, "ioctl(CTLIOCGINFO) failed: %s", strerror(errno));
82                 return false;
83         }
84
85         int unit = -1;
86         char *p = strstr(device, "utun"), *e = NULL;
87         if(p) {
88                 unit = strtol(p + 4, &e, 10);
89                 if(!e)
90                         unit = -1;
91         }
92
93         struct sockaddr_ctl sc = {
94                 .sc_id = info.ctl_id,
95                 .sc_len = sizeof(sc),
96                 .sc_family = AF_SYSTEM,
97                 .ss_sysaddr = AF_SYS_CONTROL,
98                 .sc_unit = unit + 1,
99         };
100
101         if(connect(device_fd, (struct sockaddr *)&sc, sizeof(sc)) == -1) {
102                 logger(LOG_ERR, "Could not connect utun socket: %s\n", strerror(errno));
103                 return false;
104         }
105
106         char name[64] = "";
107         socklen_t len = sizeof(name);
108         if(getsockopt(device_fd, SYSPROTO_CONTROL, UTUN_OPT_IFNAME, name, &len)) {
109                 iface = xstrdup(device);
110         } else {
111                 iface = xstrdup(name);
112         }
113
114         device_info = "OS X utun device";
115
116         logger(LOG_INFO, "%s is a %s", device, device_info);
117
118         return true;
119 }
120 #endif
121
122 static bool setup_device(void) {
123         // Find out which device file to open
124
125         if(!get_config_string(lookup_config(config_tree, "Device"), &device)) {
126                 if(routing_mode == RMODE_ROUTER)
127                         device = xstrdup(DEFAULT_TUN_DEVICE);
128                 else
129                         device = xstrdup(DEFAULT_TAP_DEVICE);
130         }
131
132         // Find out if it's supposed to be a tun or a tap device
133
134         char *type;
135
136         if(get_config_string(lookup_config(config_tree, "DeviceType"), &type)) {
137                 if(!strcasecmp(type, "tun"))
138                         /* use default */;      
139 #ifdef ENABLE_TUNEMU
140                 else if(!strcasecmp(type, "tunemu"))
141                         device_type = DEVICE_TYPE_TUNEMU;
142 #endif
143 #ifdef HAVE_NET_IF_UTUN_H
144                 else if(!strcasecmp(type, "utun"))
145                         device_type = DEVICE_TYPE_UTUN;
146 #endif
147                 else if(!strcasecmp(type, "tunnohead"))
148                         device_type = DEVICE_TYPE_TUN;
149                 else if(!strcasecmp(type, "tunifhead"))
150                         device_type = DEVICE_TYPE_TUNIFHEAD;
151                 else if(!strcasecmp(type, "tap"))
152                         device_type = DEVICE_TYPE_TAP;
153                 else {
154                         logger(LOG_ERR, "Unknown device type %s!", type);
155                         return false;
156                 }
157         } else {
158 #ifdef HAVE_NET_IF_UTUN_H
159                 if(strncmp(device, "utun", 4) == 0 || strncmp(device, "/dev/utun", 9) == 0)
160                         device_type = DEVICE_TYPE_UTUN;
161                 else
162 #endif
163                 if(strstr(device, "tap") || routing_mode != RMODE_ROUTER)
164                         device_type = DEVICE_TYPE_TAP;
165         }
166
167         if(routing_mode == RMODE_SWITCH && device_type != DEVICE_TYPE_TAP) {
168                 logger(LOG_ERR, "Only tap devices support switch mode!");
169                 return false;
170         }
171
172         // Open the device
173
174         switch(device_type) {
175 #ifdef ENABLE_TUNEMU
176                 case DEVICE_TYPE_TUNEMU: {
177                         char dynamic_name[256] = "";
178                         device_fd = tunemu_open(dynamic_name);
179                 }
180                         break;
181 #endif
182 #ifdef HAVE_NET_IF_UTUN_H
183                 case DEVICE_TYPE_UTUN:
184                         return setup_utun();
185 #endif
186                 default:
187                         device_fd = open(device, O_RDWR | O_NONBLOCK);
188         }
189
190         if(device_fd < 0) {
191                 logger(LOG_ERR, "Could not open %s: %s", device, strerror(errno));
192                 return false;
193         }
194
195 #ifdef FD_CLOEXEC
196         fcntl(device_fd, F_SETFD, FD_CLOEXEC);
197 #endif
198
199         // Guess what the corresponding interface is called
200
201         char *realname = NULL;
202
203 #if defined(HAVE_FDEVNAME)
204         realname = fdevname(device_fd);
205 #elif defined(HAVE_DEVNAME)
206         struct stat buf;
207         if(!fstat(device_fd, &buf))
208                 realname = devname(buf.st_rdev, S_IFCHR);
209 #endif
210
211         if(!realname)
212                 realname = device;
213
214         if(!get_config_string(lookup_config(config_tree, "Interface"), &iface))
215                 iface = xstrdup(strrchr(realname, '/') ? strrchr(realname, '/') + 1 : realname);
216         else if(strcmp(iface, strrchr(realname, '/') ? strrchr(realname, '/') + 1 : realname))
217                 logger(LOG_WARNING, "Warning: Interface does not match Device. $INTERFACE might be set incorrectly.");
218
219         // Configure the device as best as we can
220
221         switch(device_type) {
222                 default:
223                         device_type = DEVICE_TYPE_TUN;
224                 case DEVICE_TYPE_TUN:
225 #ifdef TUNSIFHEAD
226                 {       
227                         const int zero = 0;
228                         if(ioctl(device_fd, TUNSIFHEAD, &zero, sizeof(zero)) == -1) {
229                                 logger(LOG_ERR, "System call `%s' failed: %s", "ioctl", strerror(errno));
230                                 return false;
231                         }
232                 }
233 #endif
234 #if defined(TUNSIFMODE) && defined(IFF_BROADCAST) && defined(IFF_MULTICAST)
235                 {
236                         const int mode = IFF_BROADCAST | IFF_MULTICAST;
237                         ioctl(device_fd, TUNSIFMODE, &mode, sizeof(mode));
238                 }
239 #endif
240
241                         device_info = "Generic BSD tun device";
242                         break;
243                 case DEVICE_TYPE_TUNIFHEAD:
244 #ifdef TUNSIFHEAD
245                 {
246                         const int one = 1;
247                         if(ioctl(device_fd, TUNSIFHEAD, &one, sizeof(one)) == -1) {
248                                 logger(LOG_ERR, "System call `%s' failed: %s", "ioctl", strerror(errno));
249                                 return false;
250                         }
251                 }
252 #endif
253 #if defined(TUNSIFMODE) && defined(IFF_BROADCAST) && defined(IFF_MULTICAST)
254                 {
255                                 const int mode = IFF_BROADCAST | IFF_MULTICAST;
256                                 ioctl(device_fd, TUNSIFMODE, &mode, sizeof(mode));
257                 }
258 #endif
259
260                         device_info = "Generic BSD tun device";
261                         break;
262                 case DEVICE_TYPE_TAP:
263                         if(routing_mode == RMODE_ROUTER)
264                                 overwrite_mac = true;
265                         device_info = "Generic BSD tap device";
266 #ifdef TAPGIFNAME
267                         {
268                                 struct ifreq ifr;
269                                 if(ioctl(device_fd, TAPGIFNAME, (void*)&ifr) == 0) {
270                                         if(iface)
271                                                 free(iface);
272                                         iface = xstrdup(ifr.ifr_name);
273                                 }
274                         }
275                         
276 #endif
277                         break;
278 #ifdef ENABLE_TUNEMU
279                 case DEVICE_TYPE_TUNEMU:
280                         device_info = "BSD tunemu device";
281                         break;
282 #endif
283         }
284
285 #ifdef SIOCGIFADDR
286         if(overwrite_mac)
287                 ioctl(device_fd, SIOCGIFADDR, mymac.x);
288 #endif
289
290         logger(LOG_INFO, "%s is a %s", device, device_info);
291
292         return true;
293 }
294
295 static void close_device(void) {
296         switch(device_type) {
297 #ifdef ENABLE_TUNEMU
298                 case DEVICE_TYPE_TUNEMU:
299                         tunemu_close(device_fd);
300                         break;
301 #endif
302                 default:
303                         close(device_fd);
304         }
305
306         free(device);
307         free(iface);
308 }
309
310 static bool read_packet(vpn_packet_t *packet) {
311         int lenin;
312
313         switch(device_type) {
314                 case DEVICE_TYPE_TUN:
315 #ifdef ENABLE_TUNEMU
316                 case DEVICE_TYPE_TUNEMU:
317                         if(device_type == DEVICE_TYPE_TUNEMU)
318                                 lenin = tunemu_read(device_fd, packet->data + 14, MTU - 14);
319                         else
320 #endif
321                                 lenin = read(device_fd, packet->data + 14, MTU - 14);
322
323                         if(lenin <= 0) {
324                                 logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
325                                            device, strerror(errno));
326                                 return false;
327                         }
328
329                         switch(packet->data[14] >> 4) {
330                                 case 4:
331                                         packet->data[12] = 0x08;
332                                         packet->data[13] = 0x00;
333                                         break;
334                                 case 6:
335                                         packet->data[12] = 0x86;
336                                         packet->data[13] = 0xDD;
337                                         break;
338                                 default:
339                                         ifdebug(TRAFFIC) logger(LOG_ERR,
340                                                            "Unknown IP version %d while reading packet from %s %s",
341                                                            packet->data[14] >> 4, device_info, device);
342                                         return false;
343                         }
344
345                         memset(packet->data, 0, 12);
346                         packet->len = lenin + 14;
347                         break;
348
349                 case DEVICE_TYPE_UTUN:
350                 case DEVICE_TYPE_TUNIFHEAD: {
351                         if((lenin = read(device_fd, packet->data + 10, MTU - 10)) <= 0) {
352                                 logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
353                                            device, strerror(errno));
354                                 return false;
355                         }
356
357                         switch(packet->data[14] >> 4) {
358                                 case 4:
359                                         packet->data[12] = 0x08;
360                                         packet->data[13] = 0x00;
361                                         break;
362                                 case 6:
363                                         packet->data[12] = 0x86;
364                                         packet->data[13] = 0xDD;
365                                         break;
366                                 default:
367                                         ifdebug(TRAFFIC) logger(LOG_ERR,
368                                                            "Unknown IP version %d while reading packet from %s %s",
369                                                            packet->data[14] >> 4, device_info, device);
370                                         return false;
371                         }
372
373                         memset(packet->data, 0, 12);
374                         packet->len = lenin + 10;
375                         break;
376                 }
377
378                 case DEVICE_TYPE_TAP:
379                         if((lenin = read(device_fd, packet->data, MTU)) <= 0) {
380                                 logger(LOG_ERR, "Error while reading from %s %s: %s", device_info,
381                                            device, strerror(errno));
382                                 return false;
383                         }
384
385                         packet->len = lenin;
386                         break;
387
388                 default:
389                         return false;
390         }
391                 
392         device_total_in += packet->len;
393
394         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Read packet of %d bytes from %s",
395                            packet->len, device_info);
396
397         return true;
398 }
399
400 static bool write_packet(vpn_packet_t *packet) {
401         ifdebug(TRAFFIC) logger(LOG_DEBUG, "Writing packet of %d bytes to %s",
402                            packet->len, device_info);
403
404         switch(device_type) {
405                 case DEVICE_TYPE_TUN:
406                         if(write(device_fd, packet->data + 14, packet->len - 14) < 0) {
407                                 logger(LOG_ERR, "Error while writing to %s %s: %s", device_info,
408                                            device, strerror(errno));
409                                 return false;
410                         }
411                         break;
412
413                 case DEVICE_TYPE_UTUN:
414                 case DEVICE_TYPE_TUNIFHEAD: {
415                         int af = (packet->data[12] << 8) + packet->data[13];
416                         uint32_t type;
417
418                         switch (af) {
419                                 case 0x0800:
420                                         type = htonl(AF_INET);
421                                         break;
422                                 case 0x86DD:
423                                         type = htonl(AF_INET6);
424                                         break;
425                                 default:
426                                         ifdebug(TRAFFIC) logger(LOG_ERR,
427                                                            "Unknown address family %x while writing packet to %s %s",
428                                                            af, device_info, device);
429                                         return false;
430                         }
431
432                         memcpy(packet->data + 10, &type, sizeof(type));
433
434                         if(write(device_fd, packet->data + 10, packet->len - 10) < 0) {
435                                 logger(LOG_ERR, "Can't write to %s %s: %s", device_info, device,
436                                            strerror(errno));
437                                 return false;
438                         }
439                         break;
440                 }
441                         
442                 case DEVICE_TYPE_TAP:
443                         if(write(device_fd, packet->data, packet->len) < 0) {
444                                 logger(LOG_ERR, "Error while writing to %s %s: %s", device_info,
445                                            device, strerror(errno));
446                                 return false;
447                         }
448                         break;
449
450 #ifdef ENABLE_TUNEMU
451                 case DEVICE_TYPE_TUNEMU:
452                         if(tunemu_write(device_fd, packet->data + 14, packet->len - 14) < 0) {
453                                 logger(LOG_ERR, "Error while writing to %s %s: %s", device_info,
454                                            device, strerror(errno));
455                                 return false;
456                         }
457                         break;
458 #endif
459
460                 default:
461                         return false;
462         }
463
464         device_total_out += packet->len;
465
466         return true;
467 }
468
469 static void dump_device_stats(void) {
470         logger(LOG_DEBUG, "Statistics for %s %s:", device_info, device);
471         logger(LOG_DEBUG, " total bytes in:  %10"PRIu64, device_total_in);
472         logger(LOG_DEBUG, " total bytes out: %10"PRIu64, device_total_out);
473 }
474
475 const devops_t os_devops = {
476         .setup = setup_device,
477         .close = close_device,
478         .read = read_packet,
479         .write = write_packet,
480         .dump_stats = dump_device_stats,
481 };