Reformat all code using astyle.
[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         if(type == ETH_P_IP && DATA(packet)[start + 9] == 6) {
410                 start += (DATA(packet)[start] & 0xf) * 4;
411         } else if(type == ETH_P_IPV6 && DATA(packet)[start + 6] == 6) {
412                 start += 40;
413         } else {
414                 return;
415         }
416
417         if(packet->len <= start + 20) {
418                 return;
419         }
420
421         /* Use data offset field to calculate length of options field */
422         int len = ((DATA(packet)[start + 12] >> 4) - 5) * 4;
423
424         if(packet->len < start + 20 + len) {
425                 return;
426         }
427
428         /* Search for MSS option header */
429         for(int i = 0; i < len;) {
430                 if(DATA(packet)[start + 20 + i] == 0) {
431                         break;
432                 }
433
434                 if(DATA(packet)[start + 20 + i] == 1) {
435                         i++;
436                         continue;
437                 }
438
439                 if(i > len - 2 || i > len - DATA(packet)[start + 21 + i]) {
440                         break;
441                 }
442
443                 if(DATA(packet)[start + 20 + i] != 2) {
444                         if(DATA(packet)[start + 21 + i] < 2) {
445                                 break;
446                         }
447
448                         i += DATA(packet)[start + 21 + i];
449                         continue;
450                 }
451
452                 if(DATA(packet)[start + 21] != 4) {
453                         break;
454                 }
455
456                 /* Found it */
457                 uint16_t oldmss = DATA(packet)[start + 22 + i] << 8 | DATA(packet)[start + 23 + i];
458                 uint16_t newmss = mtu - start - 20;
459                 uint32_t csum = DATA(packet)[start + 16] << 8 | DATA(packet)[start + 17];
460
461                 if(oldmss <= newmss) {
462                         break;
463                 }
464
465                 logger(DEBUG_TRAFFIC, LOG_INFO, "Clamping MSS of packet from %s to %s to %d", source->name, via->name, newmss);
466
467                 /* Update the MSS value and the checksum */
468                 DATA(packet)[start + 22 + i] = newmss >> 8;
469                 DATA(packet)[start + 23 + i] = newmss & 0xff;
470                 csum ^= 0xffff;
471                 csum += oldmss ^ 0xffff;
472                 csum += newmss;
473                 csum = (csum & 0xffff) + (csum >> 16);
474                 csum += csum >> 16;
475                 csum ^= 0xffff;
476                 DATA(packet)[start + 16] = csum >> 8;
477                 DATA(packet)[start + 17] = csum;
478                 break;
479         }
480 }
481
482 static void age_subnets(void *data) {
483         bool left = false;
484
485         for splay_each(subnet_t, s, myself->subnet_tree) {
486                 if(s->expires && s->expires < now.tv_sec) {
487                         if(debug_level >= DEBUG_TRAFFIC) {
488                                 char netstr[MAXNETSTR];
489
490                                 if(net2str(netstr, sizeof(netstr), s)) {
491                                         logger(DEBUG_TRAFFIC, LOG_INFO, "Subnet %s expired", netstr);
492                                 }
493                         }
494
495                         for list_each(connection_t, c, connection_list)
496                                 if(c->edge) {
497                                         send_del_subnet(c, s);
498                                 }
499
500                         subnet_del(myself, s);
501                 } else {
502                         if(s->expires) {
503                                 left = true;
504                         }
505                 }
506         }
507
508         if(left)
509                 timeout_set(&age_subnets_timeout, &(struct timeval) {
510                 10, rand() % 100000
511         });
512 }
513
514 static void learn_mac(mac_t *address) {
515         subnet_t *subnet = lookup_subnet_mac(myself, address);
516
517         /* If we don't know this MAC address yet, store it */
518
519         if(!subnet) {
520                 logger(DEBUG_TRAFFIC, LOG_INFO, "Learned new MAC address %x:%x:%x:%x:%x:%x",
521                        address->x[0], address->x[1], address->x[2], address->x[3],
522                        address->x[4], address->x[5]);
523
524                 subnet = new_subnet();
525                 subnet->type = SUBNET_MAC;
526                 subnet->expires = now.tv_sec + macexpire;
527                 subnet->net.mac.address = *address;
528                 subnet->weight = 10;
529                 subnet_add(myself, subnet);
530                 subnet_update(myself, subnet, true);
531
532                 /* And tell all other tinc daemons it's our MAC */
533
534                 for list_each(connection_t, c, connection_list)
535                         if(c->edge) {
536                                 send_add_subnet(c, subnet);
537                         }
538
539                 timeout_add(&age_subnets_timeout, age_subnets, NULL, &(struct timeval) {
540                         10, rand() % 100000
541                 });
542         } else {
543                 if(subnet->expires) {
544                         subnet->expires = now.tv_sec + macexpire;
545                 }
546         }
547 }
548
549 static void route_broadcast(node_t *source, vpn_packet_t *packet) {
550         if(decrement_ttl && source != myself)
551                 if(!do_decrement_ttl(source, packet)) {
552                         return;
553                 }
554
555         broadcast_packet(source, packet);
556 }
557
558 /* RFC 791 */
559
560 static void fragment_ipv4_packet(node_t *dest, vpn_packet_t *packet, length_t ether_size) {
561         struct ip ip;
562         vpn_packet_t fragment;
563         int maxlen, todo;
564         uint8_t *offset;
565         uint16_t ip_off, origf;
566
567         memcpy(&ip, DATA(packet) + ether_size, ip_size);
568         fragment.priority = packet->priority;
569         fragment.offset = DEFAULT_PACKET_OFFSET;
570
571         if(ip.ip_hl != ip_size / 4) {
572                 return;
573         }
574
575         todo = ntohs(ip.ip_len) - ip_size;
576
577         if(ether_size + ip_size + todo != packet->len) {
578                 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));
579                 return;
580         }
581
582         logger(DEBUG_TRAFFIC, LOG_INFO, "Fragmenting packet of %d bytes to %s (%s)", packet->len, dest->name, dest->hostname);
583
584         offset = DATA(packet) + ether_size + ip_size;
585         maxlen = (dest->mtu - ether_size - ip_size) & ~0x7;
586         ip_off = ntohs(ip.ip_off);
587         origf = ip_off & ~IP_OFFMASK;
588         ip_off &= IP_OFFMASK;
589
590         while(todo) {
591                 int len = todo > maxlen ? maxlen : todo;
592                 memcpy(DATA(&fragment) + ether_size + ip_size, offset, len);
593                 todo -= len;
594                 offset += len;
595
596                 ip.ip_len = htons(ip_size + len);
597                 ip.ip_off = htons(ip_off | origf | (todo ? IP_MF : 0));
598                 ip.ip_sum = 0;
599                 ip.ip_sum = inet_checksum(&ip, ip_size, ~0);
600                 memcpy(DATA(&fragment), DATA(packet), ether_size);
601                 memcpy(DATA(&fragment) + ether_size, &ip, ip_size);
602                 fragment.len = ether_size + ip_size + len;
603
604                 send_packet(dest, &fragment);
605
606                 ip_off += len / 8;
607         }
608 }
609
610 static void route_ipv4(node_t *source, vpn_packet_t *packet) {
611         if(!checklength(source, packet, ether_size + ip_size)) {
612                 return;
613         }
614
615         subnet_t *subnet;
616         node_t *via;
617         ipv4_t dest;
618
619         memcpy(&dest, &DATA(packet)[30], sizeof(dest));
620         subnet = lookup_subnet_ipv4(&dest);
621
622         if(!subnet) {
623                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet from %s (%s): unknown IPv4 destination address %d.%d.%d.%d",
624                        source->name, source->hostname,
625                        dest.x[0],
626                        dest.x[1],
627                        dest.x[2],
628                        dest.x[3]);
629
630                 route_ipv4_unreachable(source, packet, ether_size, ICMP_DEST_UNREACH, ICMP_NET_UNKNOWN);
631                 return;
632         }
633
634         if(!subnet->owner) {
635                 route_broadcast(source, packet);
636                 return;
637         }
638
639         if(subnet->owner == source) {
640                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Packet looping back to %s (%s)!", source->name, source->hostname);
641                 return;
642         }
643
644         if(!subnet->owner->status.reachable) {
645                 return route_ipv4_unreachable(source, packet, ether_size, ICMP_DEST_UNREACH, ICMP_NET_UNREACH);
646         }
647
648         if(forwarding_mode == FMODE_OFF && source != myself && subnet->owner != myself) {
649                 return route_ipv4_unreachable(source, packet, ether_size, ICMP_DEST_UNREACH, ICMP_NET_ANO);
650         }
651
652         if(decrement_ttl && source != myself && subnet->owner != myself)
653                 if(!do_decrement_ttl(source, packet)) {
654                         return;
655                 }
656
657         if(priorityinheritance) {
658                 packet->priority = DATA(packet)[15];
659         }
660
661         via = (subnet->owner->via == myself) ? subnet->owner->nexthop : subnet->owner->via;
662
663         if(via == source) {
664                 logger(DEBUG_TRAFFIC, LOG_ERR, "Routing loop for packet from %s (%s)!", source->name, source->hostname);
665                 return;
666         }
667
668         if(directonly && subnet->owner != via) {
669                 return route_ipv4_unreachable(source, packet, ether_size, ICMP_DEST_UNREACH, ICMP_NET_ANO);
670         }
671
672         if(via && packet->len > MAX(via->mtu, 590) && via != myself) {
673                 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);
674
675                 if(DATA(packet)[20] & 0x40) {
676                         packet->len = MAX(via->mtu, 590);
677                         route_ipv4_unreachable(source, packet, ether_size, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED);
678                 } else {
679                         fragment_ipv4_packet(via, packet, ether_size);
680                 }
681
682                 return;
683         }
684
685         clamp_mss(source, via, packet);
686
687         send_packet(subnet->owner, packet);
688 }
689
690 static void route_neighborsol(node_t *source, vpn_packet_t *packet);
691
692 static void route_ipv6(node_t *source, vpn_packet_t *packet) {
693         if(!checklength(source, packet, ether_size + ip6_size)) {
694                 return;
695         }
696
697         if(DATA(packet)[20] == IPPROTO_ICMPV6 && checklength(source, packet, ether_size + ip6_size + icmp6_size) && DATA(packet)[54] == ND_NEIGHBOR_SOLICIT) {
698                 route_neighborsol(source, packet);
699                 return;
700         }
701
702         subnet_t *subnet;
703         node_t *via;
704         ipv6_t dest;
705
706         memcpy(&dest, &DATA(packet)[38], sizeof(dest));
707         subnet = lookup_subnet_ipv6(&dest);
708
709         if(!subnet) {
710                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet from %s (%s): unknown IPv6 destination address %hx:%hx:%hx:%hx:%hx:%hx:%hx:%hx",
711                        source->name, source->hostname,
712                        ntohs(dest.x[0]),
713                        ntohs(dest.x[1]),
714                        ntohs(dest.x[2]),
715                        ntohs(dest.x[3]),
716                        ntohs(dest.x[4]),
717                        ntohs(dest.x[5]),
718                        ntohs(dest.x[6]),
719                        ntohs(dest.x[7]));
720
721                 route_ipv6_unreachable(source, packet, ether_size, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR);
722                 return;
723         }
724
725         if(!subnet->owner) {
726                 route_broadcast(source, packet);
727                 return;
728         }
729
730         if(subnet->owner == source) {
731                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Packet looping back to %s (%s)!", source->name, source->hostname);
732                 return;
733         }
734
735         if(!subnet->owner->status.reachable) {
736                 return route_ipv6_unreachable(source, packet, ether_size, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOROUTE);
737         }
738
739         if(forwarding_mode == FMODE_OFF && source != myself && subnet->owner != myself) {
740                 return route_ipv6_unreachable(source, packet, ether_size, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN);
741         }
742
743         if(decrement_ttl && source != myself && subnet->owner != myself)
744                 if(!do_decrement_ttl(source, packet)) {
745                         return;
746                 }
747
748         if(priorityinheritance) {
749                 packet->priority = ((DATA(packet)[14] & 0x0f) << 4) | (DATA(packet)[15] >> 4);
750         }
751
752         via = (subnet->owner->via == myself) ? subnet->owner->nexthop : subnet->owner->via;
753
754         if(via == source) {
755                 logger(DEBUG_TRAFFIC, LOG_ERR, "Routing loop for packet from %s (%s)!", source->name, source->hostname);
756                 return;
757         }
758
759         if(directonly && subnet->owner != via) {
760                 return route_ipv6_unreachable(source, packet, ether_size, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN);
761         }
762
763         if(via && packet->len > MAX(via->mtu, 1294) && via != myself) {
764                 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);
765                 packet->len = MAX(via->mtu, 1294);
766                 route_ipv6_unreachable(source, packet, ether_size, ICMP6_PACKET_TOO_BIG, 0);
767                 return;
768         }
769
770         clamp_mss(source, via, packet);
771
772         send_packet(subnet->owner, packet);
773 }
774
775 /* RFC 2461 */
776
777 static void route_neighborsol(node_t *source, vpn_packet_t *packet) {
778         struct ip6_hdr ip6;
779         struct nd_neighbor_solicit ns;
780         struct nd_opt_hdr opt;
781         subnet_t *subnet;
782         uint16_t checksum;
783         bool has_opt;
784
785         struct {
786                 struct in6_addr ip6_src;
787                 struct in6_addr ip6_dst;
788                 uint32_t length;
789                 uint32_t next;
790         } pseudo;
791
792         if(!checklength(source, packet, ether_size + ip6_size + ns_size)) {
793                 return;
794         }
795
796         has_opt = packet->len >= ether_size + ip6_size + ns_size + opt_size + ETH_ALEN;
797
798         if(source != myself) {
799                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Got neighbor solicitation request from %s (%s) while in router mode!", source->name, source->hostname);
800                 return;
801         }
802
803         /* Copy headers from packet to structs on the stack */
804
805         memcpy(&ip6, DATA(packet) + ether_size, ip6_size);
806         memcpy(&ns, DATA(packet) + ether_size + ip6_size, ns_size);
807
808         if(has_opt) {
809                 memcpy(&opt, DATA(packet) + ether_size + ip6_size + ns_size, opt_size);
810         }
811
812         /* First, snatch the source address from the neighbor solicitation packet */
813
814         if(overwrite_mac) {
815                 memcpy(mymac.x, DATA(packet) + ETH_ALEN, ETH_ALEN);
816         }
817
818         /* Check if this is a valid neighbor solicitation request */
819
820         if(ns.nd_ns_hdr.icmp6_type != ND_NEIGHBOR_SOLICIT ||
821                         (has_opt && opt.nd_opt_type != ND_OPT_SOURCE_LINKADDR)) {
822                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet: received unknown type neighbor solicitation request");
823                 return;
824         }
825
826         /* Create pseudo header */
827
828         pseudo.ip6_src = ip6.ip6_src;
829         pseudo.ip6_dst = ip6.ip6_dst;
830
831         if(has_opt) {
832                 pseudo.length = htonl(ns_size + opt_size + ETH_ALEN);
833         } else {
834                 pseudo.length = htonl(ns_size);
835         }
836
837         pseudo.next = htonl(IPPROTO_ICMPV6);
838
839         /* Generate checksum */
840
841         checksum = inet_checksum(&pseudo, sizeof(pseudo), ~0);
842         checksum = inet_checksum(&ns, ns_size, checksum);
843
844         if(has_opt) {
845                 checksum = inet_checksum(&opt, opt_size, checksum);
846                 checksum = inet_checksum(DATA(packet) + ether_size + ip6_size + ns_size + opt_size, ETH_ALEN, checksum);
847         }
848
849         if(checksum) {
850                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet: checksum error for neighbor solicitation request");
851                 return;
852         }
853
854         /* Check if the IPv6 address exists on the VPN */
855
856         subnet = lookup_subnet_ipv6((ipv6_t *) &ns.nd_ns_target);
857
858         if(!subnet) {
859                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet: neighbor solicitation request for unknown address %hx:%hx:%hx:%hx:%hx:%hx:%hx:%hx",
860                        ntohs(((uint16_t *) &ns.nd_ns_target)[0]),
861                        ntohs(((uint16_t *) &ns.nd_ns_target)[1]),
862                        ntohs(((uint16_t *) &ns.nd_ns_target)[2]),
863                        ntohs(((uint16_t *) &ns.nd_ns_target)[3]),
864                        ntohs(((uint16_t *) &ns.nd_ns_target)[4]),
865                        ntohs(((uint16_t *) &ns.nd_ns_target)[5]),
866                        ntohs(((uint16_t *) &ns.nd_ns_target)[6]),
867                        ntohs(((uint16_t *) &ns.nd_ns_target)[7]));
868
869                 return;
870         }
871
872         /* Check if it is for our own subnet */
873
874         if(subnet->owner == myself) {
875                 return;        /* silently ignore */
876         }
877
878         if(decrement_ttl)
879                 if(!do_decrement_ttl(source, packet)) {
880                         return;
881                 }
882
883         /* Create neighbor advertation reply */
884
885         memcpy(DATA(packet), DATA(packet) + ETH_ALEN, ETH_ALEN); /* copy destination address */
886         DATA(packet)[ETH_ALEN * 2 - 1] ^= 0xFF;                  /* mangle source address so it looks like it's not from us */
887
888         ip6.ip6_dst = ip6.ip6_src;                               /* swap destination and source protocoll address */
889         ip6.ip6_src = ns.nd_ns_target;
890
891         if(has_opt) {
892                 memcpy(DATA(packet) + ether_size + ip6_size + ns_size + opt_size, DATA(packet) + ETH_ALEN, ETH_ALEN);        /* add fake source hard addr */
893         }
894
895         ns.nd_ns_cksum = 0;
896         ns.nd_ns_type = ND_NEIGHBOR_ADVERT;
897         ns.nd_ns_reserved = htonl(0x40000000UL);                 /* Set solicited flag */
898         opt.nd_opt_type = ND_OPT_TARGET_LINKADDR;
899
900         /* Create pseudo header */
901
902         pseudo.ip6_src = ip6.ip6_src;
903         pseudo.ip6_dst = ip6.ip6_dst;
904
905         if(has_opt) {
906                 pseudo.length = htonl(ns_size + opt_size + ETH_ALEN);
907         } else {
908                 pseudo.length = htonl(ns_size);
909         }
910
911         pseudo.next = htonl(IPPROTO_ICMPV6);
912
913         /* Generate checksum */
914
915         checksum = inet_checksum(&pseudo, sizeof(pseudo), ~0);
916         checksum = inet_checksum(&ns, ns_size, checksum);
917
918         if(has_opt) {
919                 checksum = inet_checksum(&opt, opt_size, checksum);
920                 checksum = inet_checksum(DATA(packet) + ether_size + ip6_size + ns_size + opt_size, ETH_ALEN, checksum);
921         }
922
923         ns.nd_ns_hdr.icmp6_cksum = checksum;
924
925         /* Copy structs on stack back to packet */
926
927         memcpy(DATA(packet) + ether_size, &ip6, ip6_size);
928         memcpy(DATA(packet) + ether_size + ip6_size, &ns, ns_size);
929
930         if(has_opt) {
931                 memcpy(DATA(packet) + ether_size + ip6_size + ns_size, &opt, opt_size);
932         }
933
934         send_packet(source, packet);
935 }
936
937 /* RFC 826 */
938
939 static void route_arp(node_t *source, vpn_packet_t *packet) {
940         struct ether_arp arp;
941         subnet_t *subnet;
942         struct in_addr addr;
943
944         if(!checklength(source, packet, ether_size + arp_size)) {
945                 return;
946         }
947
948         if(source != myself) {
949                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Got ARP request from %s (%s) while in router mode!", source->name, source->hostname);
950                 return;
951         }
952
953         /* First, snatch the source address from the ARP packet */
954
955         if(overwrite_mac) {
956                 memcpy(mymac.x, DATA(packet) + ETH_ALEN, ETH_ALEN);
957         }
958
959         /* Copy headers from packet to structs on the stack */
960
961         memcpy(&arp, DATA(packet) + ether_size, arp_size);
962
963         /* Check if this is a valid ARP request */
964
965         if(ntohs(arp.arp_hrd) != ARPHRD_ETHER || ntohs(arp.arp_pro) != ETH_P_IP ||
966                         arp.arp_hln != ETH_ALEN || arp.arp_pln != sizeof(addr) || ntohs(arp.arp_op) != ARPOP_REQUEST) {
967                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet: received unknown type ARP request");
968                 return;
969         }
970
971         /* Check if the IPv4 address exists on the VPN */
972
973         subnet = lookup_subnet_ipv4((ipv4_t *) &arp.arp_tpa);
974
975         if(!subnet) {
976                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet: ARP request for unknown address %d.%d.%d.%d",
977                        arp.arp_tpa[0], arp.arp_tpa[1], arp.arp_tpa[2],
978                        arp.arp_tpa[3]);
979                 return;
980         }
981
982         /* Check if it is for our own subnet */
983
984         if(subnet->owner == myself) {
985                 return;        /* silently ignore */
986         }
987
988         if(decrement_ttl)
989                 if(!do_decrement_ttl(source, packet)) {
990                         return;
991                 }
992
993         memcpy(&addr, arp.arp_tpa, sizeof(addr));                 /* save protocol addr */
994         memcpy(arp.arp_tpa, arp.arp_spa, sizeof(addr));           /* swap destination and source protocol address */
995         memcpy(arp.arp_spa, &addr, sizeof(addr));                 /* ... */
996
997         memcpy(arp.arp_tha, arp.arp_sha, ETH_ALEN);              /* set target hard/proto addr */
998         memcpy(arp.arp_sha, DATA(packet) + ETH_ALEN, ETH_ALEN);  /* set source hard/proto addr */
999         arp.arp_sha[ETH_ALEN - 1] ^= 0xFF;                       /* for consistency with route_packet() */
1000         arp.arp_op = htons(ARPOP_REPLY);
1001
1002         /* Copy structs on stack back to packet */
1003
1004         memcpy(DATA(packet) + ether_size, &arp, arp_size);
1005
1006         send_packet(source, packet);
1007 }
1008
1009 static void route_mac(node_t *source, vpn_packet_t *packet) {
1010         subnet_t *subnet;
1011         mac_t dest;
1012
1013         /* Learn source address */
1014
1015         if(source == myself) {
1016                 mac_t src;
1017                 memcpy(&src, &DATA(packet)[6], sizeof(src));
1018                 learn_mac(&src);
1019         }
1020
1021         /* Lookup destination address */
1022
1023         memcpy(&dest, &DATA(packet)[0], sizeof(dest));
1024         subnet = lookup_subnet_mac(NULL, &dest);
1025
1026         if(!subnet || !subnet->owner) {
1027                 route_broadcast(source, packet);
1028                 return;
1029         }
1030
1031         if(subnet->owner == source) {
1032                 logger(DEBUG_TRAFFIC, LOG_WARNING, "Packet looping back to %s (%s)!", source->name, source->hostname);
1033                 return;
1034         }
1035
1036         if(forwarding_mode == FMODE_OFF && source != myself && subnet->owner != myself) {
1037                 return;
1038         }
1039
1040         if(decrement_ttl && source != myself && subnet->owner != myself)
1041                 if(!do_decrement_ttl(source, packet)) {
1042                         return;
1043                 }
1044
1045         uint16_t type = DATA(packet)[12] << 8 | DATA(packet)[13];
1046
1047         if(priorityinheritance) {
1048                 if(type == ETH_P_IP && packet->len >= ether_size + ip_size) {
1049                         packet->priority = DATA(packet)[15];
1050                 } else if(type == ETH_P_IPV6 && packet->len >= ether_size + ip6_size) {
1051                         packet->priority = ((DATA(packet)[14] & 0x0f) << 4) | (DATA(packet)[15] >> 4);
1052                 }
1053         }
1054
1055         // Handle packets larger than PMTU
1056
1057         node_t *via = (subnet->owner->via == myself) ? subnet->owner->nexthop : subnet->owner->via;
1058
1059         if(directonly && subnet->owner != via) {
1060                 return;
1061         }
1062
1063         if(via && packet->len > via->mtu && via != myself) {
1064                 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);
1065                 length_t ethlen = 14;
1066
1067                 if(type == ETH_P_8021Q) {
1068                         type = DATA(packet)[16] << 8 | DATA(packet)[17];
1069                         ethlen += 4;
1070                 }
1071
1072                 if(type == ETH_P_IP && packet->len > 576 + ethlen) {
1073                         if(DATA(packet)[6 + ethlen] & 0x40) {
1074                                 packet->len = via->mtu;
1075                                 route_ipv4_unreachable(source, packet, ethlen, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED);
1076                         } else {
1077                                 fragment_ipv4_packet(via, packet, ethlen);
1078                         }
1079
1080                         return;
1081                 } else if(type == ETH_P_IPV6 && packet->len > 1280 + ethlen) {
1082                         packet->len = via->mtu;
1083                         route_ipv6_unreachable(source, packet, ethlen, ICMP6_PACKET_TOO_BIG, 0);
1084                         return;
1085                 }
1086         }
1087
1088         clamp_mss(source, via, packet);
1089
1090         send_packet(subnet->owner, packet);
1091 }
1092
1093 static void send_pcap(vpn_packet_t *packet) {
1094         pcap = false;
1095
1096         for list_each(connection_t, c, connection_list) {
1097                 if(!c->status.pcap) {
1098                         continue;
1099                 }
1100
1101                 pcap = true;
1102                 int len = packet->len;
1103
1104                 if(c->outmaclength && c->outmaclength < len) {
1105                         len = c->outmaclength;
1106                 }
1107
1108                 if(send_request(c, "%d %d %d", CONTROL, REQ_PCAP, len)) {
1109                         send_meta(c, (char *)DATA(packet), len);
1110                 }
1111         }
1112 }
1113
1114 void route(node_t *source, vpn_packet_t *packet) {
1115         if(pcap) {
1116                 send_pcap(packet);
1117         }
1118
1119         if(forwarding_mode == FMODE_KERNEL && source != myself) {
1120                 send_packet(myself, packet);
1121                 return;
1122         }
1123
1124         if(!checklength(source, packet, ether_size)) {
1125                 return;
1126         }
1127
1128         uint16_t type = DATA(packet)[12] << 8 | DATA(packet)[13];
1129
1130         switch(routing_mode) {
1131         case RMODE_ROUTER:
1132                 switch(type) {
1133                 case ETH_P_ARP:
1134                         route_arp(source, packet);
1135                         break;
1136
1137                 case ETH_P_IP:
1138                         route_ipv4(source, packet);
1139                         break;
1140
1141                 case ETH_P_IPV6:
1142                         route_ipv6(source, packet);
1143                         break;
1144
1145                 default:
1146                         logger(DEBUG_TRAFFIC, LOG_WARNING, "Cannot route packet from %s (%s): unknown type %hx", source->name, source->hostname, type);
1147                         break;
1148                 }
1149
1150                 break;
1151
1152         case RMODE_SWITCH:
1153                 route_mac(source, packet);
1154                 break;
1155
1156         case RMODE_HUB:
1157                 route_broadcast(source, packet);
1158                 break;
1159         }
1160 }