Work around a GCC bug that causes inet_checksum() to give wrong results.
[tinc] / src / route.c
1 /*
2     route.c -- routing
3     Copyright (C) 2000-2005 Ivo Timmermans,
4                   2000-2013 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include "connection.h"
24 #include "control_common.h"
25 #include "ethernet.h"
26 #include "ipv4.h"
27 #include "ipv6.h"
28 #include "logger.h"
29 #include "meta.h"
30 #include "net.h"
31 #include "protocol.h"
32 #include "route.h"
33 #include "subnet.h"
34 #include "utils.h"
35
36 rmode_t routing_mode = RMODE_ROUTER;
37 fmode_t forwarding_mode = FMODE_INTERNAL;
38 bmode_t broadcast_mode = BMODE_MST;
39 bool decrement_ttl = false;
40 bool directonly = false;
41 bool priorityinheritance = false;
42 int macexpire = 600;
43 bool overwrite_mac = false;
44 mac_t mymac = {{0xFE, 0xFD, 0, 0, 0, 0}};
45 bool pcap = false;
46
47 /* Sizes of various headers */
48
49 static const size_t ether_size = sizeof(struct ether_header);
50 static const size_t arp_size = sizeof(struct ether_arp);
51 static const size_t ip_size = sizeof(struct ip);
52 static const size_t icmp_size = sizeof(struct icmp) - sizeof(struct ip);
53 static const size_t ip6_size = sizeof(struct ip6_hdr);
54 static const size_t icmp6_size = sizeof(struct icmp6_hdr);
55 static const size_t ns_size = sizeof(struct nd_neighbor_solicit);
56 static const size_t opt_size = sizeof(struct nd_opt_hdr);
57
58 #ifndef MAX
59 #define MAX(a, b) ((a) > (b) ? (a) : (b))
60 #endif
61
62 volatile int dummy;
63 static timeout_t age_subnets_timeout;
64
65 /* RFC 1071 */
66
67 static uint16_t inet_checksum(void *data, int len, uint16_t prevsum) {
68         uint16_t *p = data;
69         uint32_t checksum = prevsum ^ 0xFFFF;
70
71         while(len >= 2) {
72                 checksum += *p++;
73                 len -= 2;
74         }
75
76         if(len) {
77                 checksum += *(uint8_t *)p;
78         }
79
80         while(checksum >> 16) {
81                 checksum = (checksum & 0xFFFF) + (checksum >> 16);
82         }
83
84         // Work around a compiler optimization bug.
85         if(checksum) {
86                 dummy = 1;
87         }
88
89         return ~checksum;
90 }
91
92 static bool ratelimit(int frequency) {
93         static time_t lasttime = 0;
94         static int count = 0;
95
96         if(lasttime == now.tv_sec) {
97                 if(count >= frequency) {
98                         return true;
99                 }
100         } else {
101                 lasttime = now.tv_sec;
102                 count = 0;
103         }
104
105         count++;
106         return false;
107 }
108
109 static bool checklength(node_t *source, vpn_packet_t *packet, length_t length) {
110         if(packet->len < length) {
111                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Got too short packet from %s (%s)", source->name, source->hostname);
112                 return false;
113         } else {
114                 return true;
115         }
116 }
117
118 static void swap_mac_addresses(vpn_packet_t *packet) {
119         mac_t tmp;
120         memcpy(&tmp, &DATA(packet)[0], sizeof(tmp));
121         memcpy(&DATA(packet)[0], &DATA(packet)[6], sizeof(tmp));
122         memcpy(&DATA(packet)[6], &tmp, sizeof(tmp));
123 }
124
125 /* RFC 792 */
126
127 static void route_ipv4_unreachable(node_t *source, vpn_packet_t *packet, length_t ether_size, uint8_t type, uint8_t code) {
128         struct ip ip = {0};
129         struct icmp icmp = {0};
130
131         struct in_addr ip_src;
132         struct in_addr ip_dst;
133         uint32_t oldlen;
134
135         if(ratelimit(3)) {
136                 return;
137         }
138
139         /* Swap Ethernet source and destination addresses */
140
141         swap_mac_addresses(packet);
142
143         /* Copy headers from packet into properly aligned structs on the stack */
144
145         memcpy(&ip, DATA(packet) + ether_size, ip_size);
146
147         /* Remember original source and destination */
148
149         ip_src = ip.ip_src;
150         ip_dst = ip.ip_dst;
151
152         /* Try to reply with an IP address assigned to the local machine */
153
154         if(type == ICMP_TIME_EXCEEDED && code == ICMP_EXC_TTL) {
155                 int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
156
157                 if(sockfd != -1) {
158                         struct sockaddr_in addr;
159                         memset(&addr, 0, sizeof(addr));
160                         addr.sin_family = AF_INET;
161                         addr.sin_addr = ip.ip_src;
162
163                         if(!connect(sockfd, (const struct sockaddr *) &addr, sizeof(addr))) {
164                                 memset(&addr, 0, sizeof(addr));
165                                 addr.sin_family = AF_INET;
166                                 socklen_t addrlen = sizeof(addr);
167
168                                 if(!getsockname(sockfd, (struct sockaddr *) &addr, &addrlen) && addrlen <= sizeof(addr)) {
169                                         ip_dst = addr.sin_addr;
170                                 }
171                         }
172
173                         close(sockfd);
174                 }
175         }
176
177         oldlen = packet->len - ether_size;
178
179         if(type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED) {
180                 icmp.icmp_nextmtu = htons(packet->len - ether_size);
181         }
182
183         if(oldlen >= IP_MSS - ip_size - icmp_size) {
184                 oldlen = IP_MSS - ip_size - icmp_size;
185         }
186
187         /* Copy first part of original contents to ICMP message */
188
189         memmove(DATA(packet) + ether_size + ip_size + icmp_size, DATA(packet) + ether_size, oldlen);
190
191         /* Fill in IPv4 header */
192
193         ip.ip_v = 4;
194         ip.ip_hl = ip_size / 4;
195         ip.ip_tos = 0;
196         ip.ip_len = htons(ip_size + icmp_size + oldlen);
197         ip.ip_id = 0;
198         ip.ip_off = 0;
199         ip.ip_ttl = 255;
200         ip.ip_p = IPPROTO_ICMP;
201         ip.ip_sum = 0;
202         ip.ip_src = ip_dst;
203         ip.ip_dst = ip_src;
204
205         ip.ip_sum = inet_checksum(&ip, ip_size, ~0);
206
207         /* Fill in ICMP header */
208
209         icmp.icmp_type = type;
210         icmp.icmp_code = code;
211         icmp.icmp_cksum = 0;
212
213         icmp.icmp_cksum = inet_checksum(&icmp, icmp_size, ~0);
214         icmp.icmp_cksum = inet_checksum(DATA(packet) + ether_size + ip_size + icmp_size, oldlen, icmp.icmp_cksum);
215
216         /* Copy structs on stack back to packet */
217
218         memcpy(DATA(packet) + ether_size, &ip, ip_size);
219         memcpy(DATA(packet) + ether_size + ip_size, &icmp, icmp_size);
220
221         packet->len = ether_size + ip_size + icmp_size + oldlen;
222
223         send_packet(source, packet);
224 }
225
226 /* RFC 2463 */
227
228 static void route_ipv6_unreachable(node_t *source, vpn_packet_t *packet, length_t ether_size, uint8_t type, uint8_t code) {
229         struct ip6_hdr ip6;
230         struct icmp6_hdr icmp6 = {0};
231         uint16_t checksum;
232
233         struct {
234                 struct in6_addr ip6_src;        /* source address */
235                 struct in6_addr ip6_dst;        /* destination address */
236                 uint32_t length;
237                 uint32_t next;
238         } pseudo;
239
240         if(ratelimit(3)) {
241                 return;
242         }
243
244         /* Swap Ethernet source and destination addresses */
245
246         swap_mac_addresses(packet);
247
248         /* Copy headers from packet to structs on the stack */
249
250         memcpy(&ip6, DATA(packet) + ether_size, ip6_size);
251
252         /* Remember original source and destination */
253
254         pseudo.ip6_src = ip6.ip6_dst;
255         pseudo.ip6_dst = ip6.ip6_src;
256
257         /* Try to reply with an IP address assigned to the local machine */
258
259         if(type == ICMP6_TIME_EXCEEDED && code == ICMP6_TIME_EXCEED_TRANSIT) {
260                 int sockfd = socket(AF_INET6, SOCK_DGRAM, 0);
261
262                 if(sockfd != -1) {
263                         struct sockaddr_in6 addr;
264                         memset(&addr, 0, sizeof(addr));
265                         addr.sin6_family = AF_INET6;
266                         addr.sin6_addr = ip6.ip6_src;
267
268                         if(!connect(sockfd, (const struct sockaddr *) &addr, sizeof(addr))) {
269                                 memset(&addr, 0, sizeof(addr));
270                                 addr.sin6_family = AF_INET6;
271                                 socklen_t addrlen = sizeof(addr);
272
273                                 if(!getsockname(sockfd, (struct sockaddr *) &addr, &addrlen) && addrlen <= sizeof(addr)) {
274                                         pseudo.ip6_src = addr.sin6_addr;
275                                 }
276                         }
277
278                         close(sockfd);
279                 }
280         }
281
282         pseudo.length = packet->len - ether_size;
283
284         if(type == ICMP6_PACKET_TOO_BIG) {
285                 icmp6.icmp6_mtu = htonl(pseudo.length);
286         }
287
288         if(pseudo.length >= IP_MSS - ip6_size - icmp6_size) {
289                 pseudo.length = IP_MSS - ip6_size - icmp6_size;
290         }
291
292         /* Copy first part of original contents to ICMP message */
293
294         memmove(DATA(packet) + ether_size + ip6_size + icmp6_size, DATA(packet) + ether_size, pseudo.length);
295
296         /* Fill in IPv6 header */
297
298         ip6.ip6_flow = htonl(0x60000000UL);
299         ip6.ip6_plen = htons(icmp6_size + pseudo.length);
300         ip6.ip6_nxt = IPPROTO_ICMPV6;
301         ip6.ip6_hlim = 255;
302         ip6.ip6_src = pseudo.ip6_src;
303         ip6.ip6_dst = pseudo.ip6_dst;
304
305         /* Fill in ICMP header */
306
307         icmp6.icmp6_type = type;
308         icmp6.icmp6_code = code;
309         icmp6.icmp6_cksum = 0;
310
311         /* Create pseudo header */
312
313         pseudo.length = htonl(icmp6_size + pseudo.length);
314         pseudo.next = htonl(IPPROTO_ICMPV6);
315
316         /* Generate checksum */
317
318         checksum = inet_checksum(&pseudo, sizeof(pseudo), ~0);
319         checksum = inet_checksum(&icmp6, icmp6_size, checksum);
320         checksum = inet_checksum(DATA(packet) + ether_size + ip6_size + icmp6_size, ntohl(pseudo.length) - icmp6_size, checksum);
321
322         icmp6.icmp6_cksum = checksum;
323
324         /* Copy structs on stack back to packet */
325
326         memcpy(DATA(packet) + ether_size, &ip6, ip6_size);
327         memcpy(DATA(packet) + ether_size + ip6_size, &icmp6, icmp6_size);
328
329         packet->len = ether_size + ip6_size + ntohl(pseudo.length);
330
331         send_packet(source, packet);
332 }
333
334 static bool do_decrement_ttl(node_t *source, vpn_packet_t *packet) {
335         uint16_t type = DATA(packet)[12] << 8 | DATA(packet)[13];
336         length_t ethlen = ether_size;
337
338         if(type == ETH_P_8021Q) {
339                 type = DATA(packet)[16] << 8 | DATA(packet)[17];
340                 ethlen += 4;
341         }
342
343         switch(type) {
344         case ETH_P_IP:
345                 if(!checklength(source, packet, ethlen + ip_size)) {
346                         return false;
347                 }
348
349                 if(DATA(packet)[ethlen + 8] <= 1) {
350                         if(DATA(packet)[ethlen + 11] != IPPROTO_ICMP || DATA(packet)[ethlen + 32] != ICMP_TIME_EXCEEDED) {
351                                 route_ipv4_unreachable(source, packet, ethlen, ICMP_TIME_EXCEEDED, ICMP_EXC_TTL);
352                         }
353
354                         return false;
355                 }
356
357                 uint16_t old = DATA(packet)[ethlen + 8] << 8 | DATA(packet)[ethlen + 9];
358                 DATA(packet)[ethlen + 8]--;
359                 uint16_t new = DATA(packet)[ethlen + 8] << 8 | DATA(packet)[ethlen + 9];
360
361                 uint32_t checksum = DATA(packet)[ethlen + 10] << 8 | DATA(packet)[ethlen + 11];
362                 checksum += old + (~new & 0xFFFF);
363
364                 while(checksum >> 16) {
365                         checksum = (checksum & 0xFFFF) + (checksum >> 16);
366                 }
367
368                 DATA(packet)[ethlen + 10] = checksum >> 8;
369                 DATA(packet)[ethlen + 11] = checksum & 0xff;
370
371                 return true;
372
373         case ETH_P_IPV6:
374                 if(!checklength(source, packet, ethlen + ip6_size)) {
375                         return false;
376                 }
377
378                 if(DATA(packet)[ethlen + 7] <= 1) {
379                         if(DATA(packet)[ethlen + 6] != IPPROTO_ICMPV6 || DATA(packet)[ethlen + 40] != ICMP6_TIME_EXCEEDED) {
380                                 route_ipv6_unreachable(source, packet, ethlen, ICMP6_TIME_EXCEEDED, ICMP6_TIME_EXCEED_TRANSIT);
381                         }
382
383                         return false;
384                 }
385
386                 DATA(packet)[ethlen + 7]--;
387
388                 return true;
389
390         default:
391                 return true;
392         }
393 }
394
395 static void clamp_mss(const node_t *source, const node_t *via, vpn_packet_t *packet) {
396         if(!source || !via || !(via->options & OPTION_CLAMP_MSS)) {
397                 return;
398         }
399
400         uint16_t mtu = source->mtu;
401
402         if(via != myself && via->mtu < mtu) {
403                 mtu = via->mtu;
404         }
405
406         /* Find TCP header */
407         int start = ether_size;
408         uint16_t type = DATA(packet)[12] << 8 | DATA(packet)[13];
409
410         if(type == ETH_P_8021Q) {
411                 start += 4;
412                 type = DATA(packet)[16] << 8 | DATA(packet)[17];
413         }
414
415         /* IP in IP (RFC 2003) packet */
416         if(type == ETH_P_IP && DATA(packet)[start + 9] == 4) {
417                 start += 20;
418         }
419
420         if(packet->len <= start + 20) {
421                 return;
422         }
423
424         if(type == ETH_P_IP && DATA(packet)[start + 9] == 6) {
425                 start += (DATA(packet)[start] & 0xf) * 4;
426         } else if(type == ETH_P_IPV6 && DATA(packet)[start + 6] == 6) {
427                 start += 40;
428         } else {
429                 return;
430         }
431
432         if(packet->len <= start + 20) {
433                 return;
434         }
435
436         /* Use data offset field to calculate length of options field */
437         int len = ((DATA(packet)[start + 12] >> 4) - 5) * 4;
438
439         if(packet->len < start + 20 + len) {
440                 return;
441         }
442
443         /* Search for MSS option header */
444         for(int i = 0; i < len;) {
445                 if(DATA(packet)[start + 20 + i] == 0) {
446                         break;
447                 }
448
449                 if(DATA(packet)[start + 20 + i] == 1) {
450                         i++;
451                         continue;
452                 }
453
454                 if(i > len - 2 || i > len - DATA(packet)[start + 21 + i]) {
455                         break;
456                 }
457
458                 if(DATA(packet)[start + 20 + i] != 2) {
459                         if(DATA(packet)[start + 21 + i] < 2) {
460                                 break;
461                         }
462
463                         i += DATA(packet)[start + 21 + i];
464                         continue;
465                 }
466
467                 if(DATA(packet)[start + 21] != 4) {
468                         break;
469                 }
470
471                 /* Found it */
472                 uint16_t oldmss = DATA(packet)[start + 22 + i] << 8 | DATA(packet)[start + 23 + i];
473                 uint16_t newmss = mtu - start - 20;
474                 uint32_t csum = DATA(packet)[start + 16] << 8 | DATA(packet)[start + 17];
475
476                 if(oldmss <= newmss) {
477                         break;
478                 }
479
480                 logger(DEBUG_TRAFFIC, LOG_INFO, "Clamping MSS of packet from %s to %s to %d", source->name, via->name, newmss);
481
482                 /* Update the MSS value and the checksum */
483                 DATA(packet)[start + 22 + i] = newmss >> 8;
484                 DATA(packet)[start + 23 + i] = newmss & 0xff;
485                 csum ^= 0xffff;
486                 csum += oldmss ^ 0xffff;
487                 csum += newmss;
488                 csum = (csum & 0xffff) + (csum >> 16);
489                 csum += csum >> 16;
490                 csum ^= 0xffff;
491                 DATA(packet)[start + 16] = csum >> 8;
492                 DATA(packet)[start + 17] = csum;
493                 break;
494         }
495 }
496
497 static void age_subnets(void *data) {
498         bool left = false;
499
500         for splay_each(subnet_t, s, myself->subnet_tree) {
501                 if(s->expires && s->expires < now.tv_sec) {
502                         if(debug_level >= DEBUG_TRAFFIC) {
503                                 char netstr[MAXNETSTR];
504
505                                 if(net2str(netstr, sizeof(netstr), s)) {
506                                         logger(DEBUG_TRAFFIC, LOG_INFO, "Subnet %s expired", netstr);
507                                 }
508                         }
509
510                         for list_each(connection_t, c, connection_list)
511                                 if(c->edge) {
512                                         send_del_subnet(c, s);
513                                 }
514
515                         subnet_del(myself, s);
516                 } else {
517                         if(s->expires) {
518                                 left = true;
519                         }
520                 }
521         }
522
523         if(left)
524                 timeout_set(&age_subnets_timeout, &(struct timeval) {
525                 10, rand() % 100000
526         });
527 }
528
529 static void learn_mac(mac_t *address) {
530         subnet_t *subnet = lookup_subnet_mac(myself, address);
531
532         /* If we don't know this MAC address yet, store it */
533
534         if(!subnet) {
535                 logger(DEBUG_TRAFFIC, LOG_INFO, "Learned new MAC address %x:%x:%x:%x:%x:%x",
536                        address->x[0], address->x[1], address->x[2], address->x[3],
537                        address->x[4], address->x[5]);
538
539                 subnet = new_subnet();
540                 subnet->type = SUBNET_MAC;
541                 subnet->expires = now.tv_sec + macexpire;
542                 subnet->net.mac.address = *address;
543                 subnet->weight = 10;
544                 subnet_add(myself, subnet);
545                 subnet_update(myself, subnet, true);
546
547                 /* And tell all other tinc daemons it's our MAC */
548
549                 for list_each(connection_t, c, connection_list)
550                         if(c->edge) {
551                                 send_add_subnet(c, subnet);
552                         }
553
554                 timeout_add(&age_subnets_timeout, age_subnets, NULL, &(struct timeval) {
555                         10, rand() % 100000
556                 });
557         } else {
558                 if(subnet->expires) {
559                         subnet->expires = now.tv_sec + macexpire;
560                 }
561         }
562 }
563
564 static void route_broadcast(node_t *source, vpn_packet_t *packet) {
565         if(decrement_ttl && source != myself)
566                 if(!do_decrement_ttl(source, packet)) {
567                         return;
568                 }
569
570         broadcast_packet(source, packet);
571 }
572
573 /* RFC 791 */
574
575 static void fragment_ipv4_packet(node_t *dest, vpn_packet_t *packet, length_t ether_size) {
576         struct ip ip;
577         vpn_packet_t fragment;
578         int maxlen, todo;
579         uint8_t *offset;
580         uint16_t ip_off, origf;
581
582         memcpy(&ip, DATA(packet) + ether_size, ip_size);
583         fragment.priority = packet->priority;
584         fragment.offset = DEFAULT_PACKET_OFFSET;
585
586         if(ip.ip_hl != ip_size / 4) {
587                 return;
588         }
589
590         todo = ntohs(ip.ip_len) - ip_size;
591
592         if(ether_size + ip_size + todo != packet->len) {
593                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Length of packet (%d) doesn't match length in IPv4 header (%d)", packet->len, (int)(ether_size + ip_size + todo));
594                 return;
595         }
596
597         logger(DEBUG_TRAFFIC, LOG_INFO, "Fragmenting packet of %d bytes to %s (%s)", packet->len, dest->name, dest->hostname);
598
599         offset = DATA(packet) + ether_size + ip_size;
600         maxlen = (dest->mtu - ether_size - ip_size) & ~0x7;
601         ip_off = ntohs(ip.ip_off);
602         origf = ip_off & ~IP_OFFMASK;
603         ip_off &= IP_OFFMASK;
604
605         while(todo) {
606                 int len = todo > maxlen ? maxlen : todo;
607                 memcpy(DATA(&fragment) + ether_size + ip_size, offset, len);
608                 todo -= len;
609                 offset += len;
610
611                 ip.ip_len = htons(ip_size + len);
612                 ip.ip_off = htons(ip_off | origf | (todo ? IP_MF : 0));
613                 ip.ip_sum = 0;
614                 ip.ip_sum = inet_checksum(&ip, ip_size, ~0);
615                 memcpy(DATA(&fragment), DATA(packet), ether_size);
616                 memcpy(DATA(&fragment) + ether_size, &ip, ip_size);
617                 fragment.len = ether_size + ip_size + len;
618
619                 send_packet(dest, &fragment);
620
621                 ip_off += len / 8;
622         }
623 }
624
625 static void route_ipv4(node_t *source, vpn_packet_t *packet) {
626         if(!checklength(source, packet, ether_size + ip_size)) {
627                 return;
628         }
629
630         subnet_t *subnet;
631         node_t *via;
632         ipv4_t dest;
633
634         memcpy(&dest, &DATA(packet)[30], sizeof(dest));
635         subnet = lookup_subnet_ipv4(&dest);
636
637         if(!subnet) {
638                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet from %s (%s): unknown IPv4 destination address %d.%d.%d.%d",
639                        source->name, source->hostname,
640                        dest.x[0],
641                        dest.x[1],
642                        dest.x[2],
643                        dest.x[3]);
644
645                 route_ipv4_unreachable(source, packet, ether_size, ICMP_DEST_UNREACH, ICMP_NET_UNKNOWN);
646                 return;
647         }
648
649         if(!subnet->owner) {
650                 route_broadcast(source, packet);
651                 return;
652         }
653
654         if(subnet->owner == source) {
655                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Packet looping back to %s (%s)!", source->name, source->hostname);
656                 return;
657         }
658
659         if(!subnet->owner->status.reachable) {
660                 route_ipv4_unreachable(source, packet, ether_size, ICMP_DEST_UNREACH, ICMP_NET_UNREACH);
661                 return;
662         }
663
664         if(forwarding_mode == FMODE_OFF && source != myself && subnet->owner != myself) {
665                 route_ipv4_unreachable(source, packet, ether_size, ICMP_DEST_UNREACH, ICMP_NET_ANO);
666                 return;
667         }
668
669         if(decrement_ttl && source != myself && subnet->owner != myself)
670                 if(!do_decrement_ttl(source, packet)) {
671                         return;
672                 }
673
674         if(priorityinheritance) {
675                 packet->priority = DATA(packet)[15];
676         }
677
678         via = (subnet->owner->via == myself) ? subnet->owner->nexthop : subnet->owner->via;
679
680         if(via == source) {
681                 logger(DEBUG_TRAFFIC, LOG_ERR, "Routing loop for packet from %s (%s)!", source->name, source->hostname);
682                 return;
683         }
684
685         if(directonly && subnet->owner != via) {
686                 route_ipv4_unreachable(source, packet, ether_size, ICMP_DEST_UNREACH, ICMP_NET_ANO);
687                 return;
688         }
689
690         if(via && packet->len > MAX(via->mtu, 590) && via != myself) {
691                 logger(DEBUG_TRAFFIC, LOG_INFO, "Packet for %s (%s) length %d larger than MTU %d", subnet->owner->name, subnet->owner->hostname, packet->len, via->mtu);
692
693                 if(DATA(packet)[20] & 0x40) {
694                         packet->len = MAX(via->mtu, 590);
695                         route_ipv4_unreachable(source, packet, ether_size, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED);
696                 } else {
697                         fragment_ipv4_packet(via, packet, ether_size);
698                 }
699
700                 return;
701         }
702
703         clamp_mss(source, via, packet);
704
705         send_packet(subnet->owner, packet);
706 }
707
708 static void route_neighborsol(node_t *source, vpn_packet_t *packet);
709
710 static void route_ipv6(node_t *source, vpn_packet_t *packet) {
711         if(!checklength(source, packet, ether_size + ip6_size)) {
712                 return;
713         }
714
715         if(DATA(packet)[20] == IPPROTO_ICMPV6 && checklength(source, packet, ether_size + ip6_size + icmp6_size) && DATA(packet)[54] == ND_NEIGHBOR_SOLICIT) {
716                 route_neighborsol(source, packet);
717                 return;
718         }
719
720         subnet_t *subnet;
721         node_t *via;
722         ipv6_t dest;
723
724         memcpy(&dest, &DATA(packet)[38], sizeof(dest));
725         subnet = lookup_subnet_ipv6(&dest);
726
727         if(!subnet) {
728                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet from %s (%s): unknown IPv6 destination address %hx:%hx:%hx:%hx:%hx:%hx:%hx:%hx",
729                        source->name, source->hostname,
730                        ntohs(dest.x[0]),
731                        ntohs(dest.x[1]),
732                        ntohs(dest.x[2]),
733                        ntohs(dest.x[3]),
734                        ntohs(dest.x[4]),
735                        ntohs(dest.x[5]),
736                        ntohs(dest.x[6]),
737                        ntohs(dest.x[7]));
738
739                 route_ipv6_unreachable(source, packet, ether_size, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR);
740                 return;
741         }
742
743         if(!subnet->owner) {
744                 route_broadcast(source, packet);
745                 return;
746         }
747
748         if(subnet->owner == source) {
749                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Packet looping back to %s (%s)!", source->name, source->hostname);
750                 return;
751         }
752
753         if(!subnet->owner->status.reachable) {
754                 route_ipv6_unreachable(source, packet, ether_size, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOROUTE);
755                 return;
756         }
757
758         if(forwarding_mode == FMODE_OFF && source != myself && subnet->owner != myself) {
759                 route_ipv6_unreachable(source, packet, ether_size, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN);
760                 return;
761         }
762
763         if(decrement_ttl && source != myself && subnet->owner != myself)
764                 if(!do_decrement_ttl(source, packet)) {
765                         return;
766                 }
767
768         if(priorityinheritance) {
769                 packet->priority = ((DATA(packet)[14] & 0x0f) << 4) | (DATA(packet)[15] >> 4);
770         }
771
772         via = (subnet->owner->via == myself) ? subnet->owner->nexthop : subnet->owner->via;
773
774         if(via == source) {
775                 logger(DEBUG_TRAFFIC, LOG_ERR, "Routing loop for packet from %s (%s)!", source->name, source->hostname);
776                 return;
777         }
778
779         if(directonly && subnet->owner != via) {
780                 route_ipv6_unreachable(source, packet, ether_size, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN);
781                 return;
782         }
783
784         if(via && packet->len > MAX(via->mtu, 1294) && via != myself) {
785                 logger(DEBUG_TRAFFIC, LOG_INFO, "Packet for %s (%s) length %d larger than MTU %d", subnet->owner->name, subnet->owner->hostname, packet->len, via->mtu);
786                 packet->len = MAX(via->mtu, 1294);
787                 route_ipv6_unreachable(source, packet, ether_size, ICMP6_PACKET_TOO_BIG, 0);
788                 return;
789         }
790
791         clamp_mss(source, via, packet);
792
793         send_packet(subnet->owner, packet);
794 }
795
796 /* RFC 2461 */
797
798 static void route_neighborsol(node_t *source, vpn_packet_t *packet) {
799         struct ip6_hdr ip6;
800         struct nd_neighbor_solicit ns;
801         struct nd_opt_hdr opt;
802         subnet_t *subnet;
803         uint16_t checksum;
804         bool has_opt;
805
806         struct {
807                 struct in6_addr ip6_src;
808                 struct in6_addr ip6_dst;
809                 uint32_t length;
810                 uint32_t next;
811         } pseudo;
812
813         if(!checklength(source, packet, ether_size + ip6_size + ns_size)) {
814                 return;
815         }
816
817         has_opt = packet->len >= ether_size + ip6_size + ns_size + opt_size + ETH_ALEN;
818
819         if(source != myself) {
820                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Got neighbor solicitation request from %s (%s) while in router mode!", source->name, source->hostname);
821                 return;
822         }
823
824         /* Copy headers from packet to structs on the stack */
825
826         memcpy(&ip6, DATA(packet) + ether_size, ip6_size);
827         memcpy(&ns, DATA(packet) + ether_size + ip6_size, ns_size);
828
829         if(has_opt) {
830                 memcpy(&opt, DATA(packet) + ether_size + ip6_size + ns_size, opt_size);
831         }
832
833         /* First, snatch the source address from the neighbor solicitation packet */
834
835         if(overwrite_mac) {
836                 memcpy(mymac.x, DATA(packet) + ETH_ALEN, ETH_ALEN);
837         }
838
839         /* Check if this is a valid neighbor solicitation request */
840
841         if(ns.nd_ns_hdr.icmp6_type != ND_NEIGHBOR_SOLICIT ||
842                         (has_opt && opt.nd_opt_type != ND_OPT_SOURCE_LINKADDR)) {
843                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet: received unknown type neighbor solicitation request");
844                 return;
845         }
846
847         /* Create pseudo header */
848
849         pseudo.ip6_src = ip6.ip6_src;
850         pseudo.ip6_dst = ip6.ip6_dst;
851
852         if(has_opt) {
853                 pseudo.length = htonl(ns_size + opt_size + ETH_ALEN);
854         } else {
855                 pseudo.length = htonl(ns_size);
856         }
857
858         pseudo.next = htonl(IPPROTO_ICMPV6);
859
860         /* Generate checksum */
861
862         checksum = inet_checksum(&pseudo, sizeof(pseudo), ~0);
863         checksum = inet_checksum(&ns, ns_size, checksum);
864
865         if(has_opt) {
866                 checksum = inet_checksum(&opt, opt_size, checksum);
867                 checksum = inet_checksum(DATA(packet) + ether_size + ip6_size + ns_size + opt_size, ETH_ALEN, checksum);
868         }
869
870         if(checksum) {
871                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet: checksum error for neighbor solicitation request");
872                 return;
873         }
874
875         /* Check if the IPv6 address exists on the VPN */
876
877         subnet = lookup_subnet_ipv6((ipv6_t *) &ns.nd_ns_target);
878
879         if(!subnet) {
880                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet: neighbor solicitation request for unknown address %hx:%hx:%hx:%hx:%hx:%hx:%hx:%hx",
881                        ntohs(((uint16_t *) &ns.nd_ns_target)[0]),
882                        ntohs(((uint16_t *) &ns.nd_ns_target)[1]),
883                        ntohs(((uint16_t *) &ns.nd_ns_target)[2]),
884                        ntohs(((uint16_t *) &ns.nd_ns_target)[3]),
885                        ntohs(((uint16_t *) &ns.nd_ns_target)[4]),
886                        ntohs(((uint16_t *) &ns.nd_ns_target)[5]),
887                        ntohs(((uint16_t *) &ns.nd_ns_target)[6]),
888                        ntohs(((uint16_t *) &ns.nd_ns_target)[7]));
889
890                 return;
891         }
892
893         /* Check if it is for our own subnet */
894
895         if(subnet->owner == myself) {
896                 return;        /* silently ignore */
897         }
898
899         if(decrement_ttl)
900                 if(!do_decrement_ttl(source, packet)) {
901                         return;
902                 }
903
904         /* Create neighbor advertation reply */
905
906         memcpy(DATA(packet), DATA(packet) + ETH_ALEN, ETH_ALEN); /* copy destination address */
907         DATA(packet)[ETH_ALEN * 2 - 1] ^= 0xFF;                  /* mangle source address so it looks like it's not from us */
908
909         ip6.ip6_dst = ip6.ip6_src;                               /* swap destination and source protocoll address */
910         ip6.ip6_src = ns.nd_ns_target;
911
912         if(has_opt) {
913                 memcpy(DATA(packet) + ether_size + ip6_size + ns_size + opt_size, DATA(packet) + ETH_ALEN, ETH_ALEN);        /* add fake source hard addr */
914         }
915
916         ns.nd_ns_cksum = 0;
917         ns.nd_ns_type = ND_NEIGHBOR_ADVERT;
918         ns.nd_ns_reserved = htonl(0x40000000UL);                 /* Set solicited flag */
919         opt.nd_opt_type = ND_OPT_TARGET_LINKADDR;
920
921         /* Create pseudo header */
922
923         pseudo.ip6_src = ip6.ip6_src;
924         pseudo.ip6_dst = ip6.ip6_dst;
925
926         if(has_opt) {
927                 pseudo.length = htonl(ns_size + opt_size + ETH_ALEN);
928         } else {
929                 pseudo.length = htonl(ns_size);
930         }
931
932         pseudo.next = htonl(IPPROTO_ICMPV6);
933
934         /* Generate checksum */
935
936         checksum = inet_checksum(&pseudo, sizeof(pseudo), ~0);
937         checksum = inet_checksum(&ns, ns_size, checksum);
938
939         if(has_opt) {
940                 checksum = inet_checksum(&opt, opt_size, checksum);
941                 checksum = inet_checksum(DATA(packet) + ether_size + ip6_size + ns_size + opt_size, ETH_ALEN, checksum);
942         }
943
944         ns.nd_ns_hdr.icmp6_cksum = checksum;
945
946         /* Copy structs on stack back to packet */
947
948         memcpy(DATA(packet) + ether_size, &ip6, ip6_size);
949         memcpy(DATA(packet) + ether_size + ip6_size, &ns, ns_size);
950
951         if(has_opt) {
952                 memcpy(DATA(packet) + ether_size + ip6_size + ns_size, &opt, opt_size);
953         }
954
955         send_packet(source, packet);
956 }
957
958 /* RFC 826 */
959
960 static void route_arp(node_t *source, vpn_packet_t *packet) {
961         struct ether_arp arp;
962         subnet_t *subnet;
963         struct in_addr addr;
964
965         if(!checklength(source, packet, ether_size + arp_size)) {
966                 return;
967         }
968
969         if(source != myself) {
970                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Got ARP request from %s (%s) while in router mode!", source->name, source->hostname);
971                 return;
972         }
973
974         /* First, snatch the source address from the ARP packet */
975
976         if(overwrite_mac) {
977                 memcpy(mymac.x, DATA(packet) + ETH_ALEN, ETH_ALEN);
978         }
979
980         /* Copy headers from packet to structs on the stack */
981
982         memcpy(&arp, DATA(packet) + ether_size, arp_size);
983
984         /* Check if this is a valid ARP request */
985
986         if(ntohs(arp.arp_hrd) != ARPHRD_ETHER || ntohs(arp.arp_pro) != ETH_P_IP ||
987                         arp.arp_hln != ETH_ALEN || arp.arp_pln != sizeof(addr) || ntohs(arp.arp_op) != ARPOP_REQUEST) {
988                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet: received unknown type ARP request");
989                 return;
990         }
991
992         /* Check if the IPv4 address exists on the VPN */
993
994         subnet = lookup_subnet_ipv4((ipv4_t *) &arp.arp_tpa);
995
996         if(!subnet) {
997                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet: ARP request for unknown address %d.%d.%d.%d",
998                        arp.arp_tpa[0], arp.arp_tpa[1], arp.arp_tpa[2],
999                        arp.arp_tpa[3]);
1000                 return;
1001         }
1002
1003         /* Check if it is for our own subnet */
1004
1005         if(subnet->owner == myself) {
1006                 return;        /* silently ignore */
1007         }
1008
1009         if(decrement_ttl)
1010                 if(!do_decrement_ttl(source, packet)) {
1011                         return;
1012                 }
1013
1014         memcpy(&addr, arp.arp_tpa, sizeof(addr));                 /* save protocol addr */
1015         memcpy(arp.arp_tpa, arp.arp_spa, sizeof(addr));           /* swap destination and source protocol address */
1016         memcpy(arp.arp_spa, &addr, sizeof(addr));                 /* ... */
1017
1018         memcpy(arp.arp_tha, arp.arp_sha, ETH_ALEN);              /* set target hard/proto addr */
1019         memcpy(arp.arp_sha, DATA(packet) + ETH_ALEN, ETH_ALEN);  /* set source hard/proto addr */
1020         arp.arp_sha[ETH_ALEN - 1] ^= 0xFF;                       /* for consistency with route_packet() */
1021         arp.arp_op = htons(ARPOP_REPLY);
1022
1023         /* Copy structs on stack back to packet */
1024
1025         memcpy(DATA(packet) + ether_size, &arp, arp_size);
1026
1027         send_packet(source, packet);
1028 }
1029
1030 static void route_mac(node_t *source, vpn_packet_t *packet) {
1031         subnet_t *subnet;
1032         mac_t dest;
1033
1034         /* Learn source address */
1035
1036         if(source == myself) {
1037                 mac_t src;
1038                 memcpy(&src, &DATA(packet)[6], sizeof(src));
1039                 learn_mac(&src);
1040         }
1041
1042         /* Lookup destination address */
1043
1044         memcpy(&dest, &DATA(packet)[0], sizeof(dest));
1045         subnet = lookup_subnet_mac(NULL, &dest);
1046
1047         if(!subnet || !subnet->owner) {
1048                 route_broadcast(source, packet);
1049                 return;
1050         }
1051
1052         if(subnet->owner == source) {
1053                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Packet looping back to %s (%s)!", source->name, source->hostname);
1054                 return;
1055         }
1056
1057         if(forwarding_mode == FMODE_OFF && source != myself && subnet->owner != myself) {
1058                 return;
1059         }
1060
1061         if(decrement_ttl && source != myself && subnet->owner != myself)
1062                 if(!do_decrement_ttl(source, packet)) {
1063                         return;
1064                 }
1065
1066         uint16_t type = DATA(packet)[12] << 8 | DATA(packet)[13];
1067
1068         if(priorityinheritance) {
1069                 if(type == ETH_P_IP && packet->len >= ether_size + ip_size) {
1070                         packet->priority = DATA(packet)[15];
1071                 } else if(type == ETH_P_IPV6 && packet->len >= ether_size + ip6_size) {
1072                         packet->priority = ((DATA(packet)[14] & 0x0f) << 4) | (DATA(packet)[15] >> 4);
1073                 }
1074         }
1075
1076         // Handle packets larger than PMTU
1077
1078         node_t *via = (subnet->owner->via == myself) ? subnet->owner->nexthop : subnet->owner->via;
1079
1080         if(directonly && subnet->owner != via) {
1081                 return;
1082         }
1083
1084         if(via && packet->len > via->mtu && via != myself) {
1085                 logger(DEBUG_TRAFFIC, LOG_INFO, "Packet for %s (%s) length %d larger than MTU %d", subnet->owner->name, subnet->owner->hostname, packet->len, via->mtu);
1086                 length_t ethlen = 14;
1087
1088                 if(type == ETH_P_8021Q) {
1089                         type = DATA(packet)[16] << 8 | DATA(packet)[17];
1090                         ethlen += 4;
1091                 }
1092
1093                 if(type == ETH_P_IP && packet->len > 576 + ethlen) {
1094                         if(DATA(packet)[6 + ethlen] & 0x40) {
1095                                 packet->len = via->mtu;
1096                                 route_ipv4_unreachable(source, packet, ethlen, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED);
1097                         } else {
1098                                 fragment_ipv4_packet(via, packet, ethlen);
1099                         }
1100
1101                         return;
1102                 } else if(type == ETH_P_IPV6 && packet->len > 1280 + ethlen) {
1103                         packet->len = via->mtu;
1104                         route_ipv6_unreachable(source, packet, ethlen, ICMP6_PACKET_TOO_BIG, 0);
1105                         return;
1106                 }
1107         }
1108
1109         clamp_mss(source, via, packet);
1110
1111         send_packet(subnet->owner, packet);
1112 }
1113
1114 static void send_pcap(vpn_packet_t *packet) {
1115         pcap = false;
1116
1117         for list_each(connection_t, c, connection_list) {
1118                 if(!c->status.pcap) {
1119                         continue;
1120                 }
1121
1122                 pcap = true;
1123                 int len = packet->len;
1124
1125                 if(c->outmaclength && c->outmaclength < len) {
1126                         len = c->outmaclength;
1127                 }
1128
1129                 if(send_request(c, "%d %d %d", CONTROL, REQ_PCAP, len)) {
1130                         send_meta(c, (char *)DATA(packet), len);
1131                 }
1132         }
1133 }
1134
1135 void route(node_t *source, vpn_packet_t *packet) {
1136         if(pcap) {
1137                 send_pcap(packet);
1138         }
1139
1140         if(forwarding_mode == FMODE_KERNEL && source != myself) {
1141                 send_packet(myself, packet);
1142                 return;
1143         }
1144
1145         if(!checklength(source, packet, ether_size)) {
1146                 return;
1147         }
1148
1149         uint16_t type = DATA(packet)[12] << 8 | DATA(packet)[13];
1150
1151         switch(routing_mode) {
1152         case RMODE_ROUTER:
1153                 switch(type) {
1154                 case ETH_P_ARP:
1155                         route_arp(source, packet);
1156                         break;
1157
1158                 case ETH_P_IP:
1159                         route_ipv4(source, packet);
1160                         break;
1161
1162                 case ETH_P_IPV6:
1163                         route_ipv6(source, packet);
1164                         break;
1165
1166                 default:
1167                         logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet from %s (%s): unknown type %hx", source->name, source->hostname, type);
1168                         break;
1169                 }
1170
1171                 break;
1172
1173         case RMODE_SWITCH:
1174                 route_mac(source, packet);
1175                 break;
1176
1177         case RMODE_HUB:
1178                 route_broadcast(source, packet);
1179                 break;
1180         }
1181 }