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