Fix format strings for Windows.
[tinc] / src / route.c
1 /*
2     route.c -- routing
3     Copyright (C) 2000-2005 Ivo Timmermans,
4                   2000-2010 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 "splay_tree.h"
24 #include "connection.h"
25 #include "control_common.h"
26 #include "ethernet.h"
27 #include "ipv4.h"
28 #include "ipv6.h"
29 #include "logger.h"
30 #include "meta.h"
31 #include "net.h"
32 #include "protocol.h"
33 #include "route.h"
34 #include "subnet.h"
35 #include "utils.h"
36
37 rmode_t routing_mode = RMODE_ROUTER;
38 fmode_t forwarding_mode = FMODE_INTERNAL;
39 bool directonly = false;
40 bool priorityinheritance = false;
41 int macexpire = 600;
42 bool overwrite_mac = false;
43 mac_t mymac = {{0xFE, 0xFD, 0, 0, 0, 0}};
44 bool pcap = false;
45
46 /* Sizes of various headers */
47
48 static const size_t ether_size = sizeof(struct ether_header);
49 static const size_t arp_size = sizeof(struct ether_arp);
50 static const size_t ip_size = sizeof(struct ip);
51 static const size_t icmp_size = sizeof(struct icmp) - sizeof(struct ip);
52 static const size_t ip6_size = sizeof(struct ip6_hdr);
53 static const size_t icmp6_size = sizeof(struct icmp6_hdr);
54 static const size_t ns_size = sizeof(struct nd_neighbor_solicit);
55 static const size_t opt_size = sizeof(struct nd_opt_hdr);
56
57 #ifndef MAX
58 #define MAX(a, b) ((a) > (b) ? (a) : (b))
59 #endif
60
61 static struct event age_subnets_event;
62
63 /* RFC 1071 */
64
65 static uint16_t inet_checksum(void *data, int len, uint16_t prevsum) {
66         uint16_t *p = data;
67         uint32_t checksum = prevsum ^ 0xFFFF;
68
69         while(len >= 2) {
70                 checksum += *p++;
71                 len -= 2;
72         }
73         
74         if(len)
75                 checksum += *(uint8_t *)p;
76
77         while(checksum >> 16)
78                 checksum = (checksum & 0xFFFF) + (checksum >> 16);
79
80         return ~checksum;
81 }
82
83 static bool ratelimit(int frequency) {
84         static time_t lasttime = 0;
85         static int count = 0;
86         time_t now = time(NULL);
87         
88         if(lasttime == now) {
89                 if(++count > frequency)
90                         return true;
91         } else {
92                 lasttime = now;
93                 count = 0;
94         }
95
96         return false;
97 }
98
99 static bool checklength(node_t *source, vpn_packet_t *packet, length_t length) {
100         if(packet->len < length) {
101                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Got too short packet from %s (%s)", source->name, source->hostname);
102                 return false;
103         } else
104                 return true;
105 }
106
107 static void clamp_mss(const node_t *source, const node_t *via, vpn_packet_t *packet) {
108         if(!source || !via || !(via->options & OPTION_CLAMP_MSS))
109                 return;
110
111         uint16_t mtu = source->mtu;
112         if(via != myself && via->mtu < mtu)
113                 mtu = via->mtu;
114
115         /* Find TCP header */
116         int start = 0;
117         uint16_t type = packet->data[12] << 8 | packet->data[13];
118
119         if(type == ETH_P_IP && packet->data[23] == 6)
120                 start = 14 + (packet->data[14] & 0xf) * 4;
121         else if(type == ETH_P_IPV6 && packet->data[20] == 6)
122                 start = 14 + 40;
123
124         if(!start || packet->len <= start + 20)
125                 return;
126
127         /* Use data offset field to calculate length of options field */
128         int len = ((packet->data[start + 12] >> 4) - 5) * 4;
129
130         if(packet->len < start + 20 + len)
131                 return;
132
133         /* Search for MSS option header */
134         for(int i = 0; i < len;) {
135                 if(packet->data[start + 20 + i] == 0)
136                         break;
137
138                 if(packet->data[start + 20 + i] == 1) {
139                         i++;
140                         continue;
141                 }
142
143                 if(i > len - 2 || i > len - packet->data[start + 21 + i])
144                         break;
145
146                 if(packet->data[start + 20 + i] != 2) {
147                         if(packet->data[start + 21 + i] < 2)
148                                 break;
149                         i += packet->data[start + 21 + i];
150                         continue;
151                 }
152
153                 if(packet->data[start + 21] != 4)
154                         break;
155
156                 /* Found it */
157                 uint16_t oldmss = packet->data[start + 22 + i] << 8 | packet->data[start + 23 + i];
158                 uint16_t newmss = mtu - start - 20;
159                 uint16_t csum = packet->data[start + 16] << 8 | packet->data[start + 17];
160
161                 if(oldmss <= newmss)
162                         break;
163                 
164                 ifdebug(TRAFFIC) logger(LOG_INFO, "Clamping MSS of packet from %s to %s to %d", source->name, via->name, newmss);
165
166                 /* Update the MSS value and the checksum */
167                 packet->data[start + 22 + i] = newmss >> 8;
168                 packet->data[start + 23 + i] = newmss & 0xff;
169                 csum ^= 0xffff;
170                 csum -= oldmss;
171                 csum += newmss;
172                 csum ^= 0xffff;
173                 packet->data[start + 16] = csum >> 8;
174                 packet->data[start + 17] = csum & 0xff;
175                 break;
176         }
177 }
178
179 static void swap_mac_addresses(vpn_packet_t *packet) {
180         mac_t tmp;
181         memcpy(&tmp, &packet->data[0], sizeof tmp);
182         memcpy(&packet->data[0], &packet->data[6], sizeof tmp);
183         memcpy(&packet->data[6], &tmp, sizeof tmp);
184 }
185         
186 static void age_subnets(int fd, short events, void *data) {
187         subnet_t *s;
188         connection_t *c;
189         splay_node_t *node, *next, *node2;
190         bool left = false;
191         time_t now = time(NULL);
192
193         for(node = myself->subnet_tree->head; node; node = next) {
194                 next = node->next;
195                 s = node->data;
196                 if(s->expires && s->expires < now) {
197                         ifdebug(TRAFFIC) {
198                                 char netstr[MAXNETSTR];
199                                 if(net2str(netstr, sizeof netstr, s))
200                                         logger(LOG_INFO, "Subnet %s expired", netstr);
201                         }
202
203                         for(node2 = connection_tree->head; node2; node2 = node2->next) {
204                                 c = node2->data;
205                                 if(c->status.active)
206                                         send_del_subnet(c, s);
207                         }
208
209                         subnet_del(myself, s);
210                 } else {
211                         if(s->expires)
212                                 left = true;
213                 }
214         }
215
216         if(left)
217                 event_add(&age_subnets_event, &(struct timeval){10, 0});
218 }
219
220 static void learn_mac(mac_t *address) {
221         subnet_t *subnet;
222         splay_node_t *node;
223         connection_t *c;
224
225         subnet = lookup_subnet_mac(myself, address);
226
227         /* If we don't know this MAC address yet, store it */
228
229         if(!subnet) {
230                 ifdebug(TRAFFIC) logger(LOG_INFO, "Learned new MAC address %hx:%hx:%hx:%hx:%hx:%hx",
231                                    address->x[0], address->x[1], address->x[2], address->x[3],
232                                    address->x[4], address->x[5]);
233
234                 subnet = new_subnet();
235                 subnet->type = SUBNET_MAC;
236                 subnet->expires = time(NULL) + macexpire;
237                 subnet->net.mac.address = *address;
238                 subnet->weight = 10;
239                 subnet_add(myself, subnet);
240                 subnet_update(myself, subnet, true);
241
242                 /* And tell all other tinc daemons it's our MAC */
243
244                 for(node = connection_tree->head; node; node = node->next) {
245                         c = node->data;
246                         if(c->status.active)
247                                 send_add_subnet(c, subnet);
248                 }
249
250                 if(!timeout_initialized(&age_subnets_event))
251                         timeout_set(&age_subnets_event, age_subnets, NULL);
252                 event_add(&age_subnets_event, &(struct timeval){10, 0});
253         } else {
254                 if(subnet->expires)
255                         subnet->expires = time(NULL) + macexpire;
256         }
257 }
258
259 /* RFC 792 */
260
261 static void route_ipv4_unreachable(node_t *source, vpn_packet_t *packet, uint8_t type, uint8_t code) {
262         struct ip ip = {0};
263         struct icmp icmp = {0};
264         
265         struct in_addr ip_src;
266         struct in_addr ip_dst;
267         uint32_t oldlen;
268
269         if(ratelimit(3))
270                 return;
271         
272         /* Swap Ethernet source and destination addresses */
273
274         swap_mac_addresses(packet);
275
276         /* Copy headers from packet into properly aligned structs on the stack */
277
278         memcpy(&ip, packet->data + ether_size, ip_size);
279
280         /* Remember original source and destination */
281         
282         ip_src = ip.ip_src;
283         ip_dst = ip.ip_dst;
284
285         oldlen = packet->len - ether_size;
286
287         if(type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
288                 icmp.icmp_nextmtu = htons(packet->len - ether_size);
289
290         if(oldlen >= IP_MSS - ip_size - icmp_size)
291                 oldlen = IP_MSS - ip_size - icmp_size;
292         
293         /* Copy first part of original contents to ICMP message */
294         
295         memmove(packet->data + ether_size + ip_size + icmp_size, packet->data + ether_size, oldlen);
296
297         /* Fill in IPv4 header */
298         
299         ip.ip_v = 4;
300         ip.ip_hl = ip_size / 4;
301         ip.ip_tos = 0;
302         ip.ip_len = htons(ip_size + icmp_size + oldlen);
303         ip.ip_id = 0;
304         ip.ip_off = 0;
305         ip.ip_ttl = 255;
306         ip.ip_p = IPPROTO_ICMP;
307         ip.ip_sum = 0;
308         ip.ip_src = ip_dst;
309         ip.ip_dst = ip_src;
310
311         ip.ip_sum = inet_checksum(&ip, ip_size, ~0);
312         
313         /* Fill in ICMP header */
314         
315         icmp.icmp_type = type;
316         icmp.icmp_code = code;
317         icmp.icmp_cksum = 0;
318         
319         icmp.icmp_cksum = inet_checksum(&icmp, icmp_size, ~0);
320         icmp.icmp_cksum = inet_checksum(packet->data + ether_size + ip_size + icmp_size, oldlen, icmp.icmp_cksum);
321
322         /* Copy structs on stack back to packet */
323
324         memcpy(packet->data + ether_size, &ip, ip_size);
325         memcpy(packet->data + ether_size + ip_size, &icmp, icmp_size);
326         
327         packet->len = ether_size + ip_size + icmp_size + oldlen;
328
329         send_packet(source, packet);
330 }
331
332 /* RFC 791 */
333
334 static void fragment_ipv4_packet(node_t *dest, vpn_packet_t *packet) {
335         struct ip ip;
336         vpn_packet_t fragment;
337         int len, maxlen, todo;
338         uint8_t *offset;
339         uint16_t ip_off, origf;
340         
341         memcpy(&ip, packet->data + ether_size, ip_size);
342         fragment.priority = packet->priority;
343
344         if(ip.ip_hl != ip_size / 4)
345                 return;
346         
347         todo = ntohs(ip.ip_len) - ip_size;
348
349         if(ether_size + ip_size + todo != packet->len) {
350                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Length of packet (%d) doesn't match length in IPv4 header (%d)", packet->len, (int)(ether_size + ip_size + todo));
351                 return;
352         }
353
354         ifdebug(TRAFFIC) logger(LOG_INFO, "Fragmenting packet of %d bytes to %s (%s)", packet->len, dest->name, dest->hostname);
355
356         offset = packet->data + ether_size + ip_size;
357         maxlen = (dest->mtu - ether_size - ip_size) & ~0x7;
358         ip_off = ntohs(ip.ip_off);
359         origf = ip_off & ~IP_OFFMASK;
360         ip_off &= IP_OFFMASK;
361         
362         while(todo) {
363                 len = todo > maxlen ? maxlen : todo;
364                 memcpy(fragment.data + ether_size + ip_size, offset, len);
365                 todo -= len;
366                 offset += len;
367
368                 ip.ip_len = htons(ip_size + len);
369                 ip.ip_off = htons(ip_off | origf | (todo ? IP_MF : 0));
370                 ip.ip_sum = 0;
371                 ip.ip_sum = inet_checksum(&ip, ip_size, ~0);
372                 memcpy(fragment.data, packet->data, ether_size);
373                 memcpy(fragment.data + ether_size, &ip, ip_size);
374                 fragment.len = ether_size + ip_size + len;
375
376                 send_packet(dest, &fragment);
377
378                 ip_off += len / 8;
379         }       
380 }
381
382 static void route_ipv4_unicast(node_t *source, vpn_packet_t *packet) {
383         subnet_t *subnet;
384         node_t *via;
385         ipv4_t dest;
386
387         memcpy(&dest, &packet->data[30], sizeof dest);
388         subnet = lookup_subnet_ipv4(&dest);
389
390         if(!subnet) {
391                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet from %s (%s): unknown IPv4 destination address %d.%d.%d.%d",
392                                 source->name, source->hostname,
393                                 dest.x[0],
394                                 dest.x[1],
395                                 dest.x[2],
396                                 dest.x[3]);
397
398                 route_ipv4_unreachable(source, packet, ICMP_DEST_UNREACH, ICMP_NET_UNKNOWN);
399                 return;
400         }
401         
402         if(subnet->owner == source) {
403                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Packet looping back to %s (%s)!", source->name, source->hostname);
404                 return;
405         }
406
407         if(!subnet->owner->status.reachable)
408                 return route_ipv4_unreachable(source, packet, ICMP_DEST_UNREACH, ICMP_NET_UNREACH);
409
410         if(forwarding_mode == FMODE_OFF && source != myself && subnet->owner != myself)
411                 return route_ipv4_unreachable(source, packet, ICMP_DEST_UNREACH, ICMP_NET_ANO);
412
413         if(priorityinheritance)
414                 packet->priority = packet->data[15];
415
416         via = (subnet->owner->via == myself) ? subnet->owner->nexthop : subnet->owner->via;
417         
418         if(directonly && subnet->owner != via)
419                 return route_ipv4_unreachable(source, packet, ICMP_DEST_UNREACH, ICMP_NET_ANO);
420
421         if(via && packet->len > MAX(via->mtu, 590) && via != myself) {
422                 ifdebug(TRAFFIC) logger(LOG_INFO, "Packet for %s (%s) length %d larger than MTU %d", subnet->owner->name, subnet->owner->hostname, packet->len, via->mtu);
423                 if(packet->data[20] & 0x40) {
424                         packet->len = MAX(via->mtu, 590);
425                         route_ipv4_unreachable(source, packet, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED);
426                 } else {
427                         fragment_ipv4_packet(via, packet);
428                 }
429
430                 return;
431         }
432
433         clamp_mss(source, via, packet);
434  
435         send_packet(subnet->owner, packet);
436 }
437
438 static void route_ipv4(node_t *source, vpn_packet_t *packet) {
439         if(!checklength(source, packet, ether_size + ip_size))
440                 return;
441
442         if(((packet->data[30] & 0xf0) == 0xe0) || (
443                         packet->data[30] == 255 &&
444                         packet->data[31] == 255 &&
445                         packet->data[32] == 255 &&
446                         packet->data[33] == 255))
447                 broadcast_packet(source, packet);
448         else
449                 route_ipv4_unicast(source, packet);
450 }
451
452 /* RFC 2463 */
453
454 static void route_ipv6_unreachable(node_t *source, vpn_packet_t *packet, uint8_t type, uint8_t code) {
455         struct ip6_hdr ip6;
456         struct icmp6_hdr icmp6 = {0};
457         uint16_t checksum;      
458
459         struct {
460                 struct in6_addr ip6_src;        /* source address */
461                 struct in6_addr ip6_dst;        /* destination address */
462                 uint32_t length;
463                 uint32_t next;
464         } pseudo;
465
466         if(ratelimit(3))
467                 return;
468         
469         /* Swap Ethernet source and destination addresses */
470
471         swap_mac_addresses(packet);
472
473         /* Copy headers from packet to structs on the stack */
474
475         memcpy(&ip6, packet->data + ether_size, ip6_size);
476
477         /* Remember original source and destination */
478         
479         pseudo.ip6_src = ip6.ip6_dst;
480         pseudo.ip6_dst = ip6.ip6_src;
481
482         pseudo.length = packet->len - ether_size;
483
484         if(type == ICMP6_PACKET_TOO_BIG)
485                 icmp6.icmp6_mtu = htonl(pseudo.length);
486         
487         if(pseudo.length >= IP_MSS - ip6_size - icmp6_size)
488                 pseudo.length = IP_MSS - ip6_size - icmp6_size;
489         
490         /* Copy first part of original contents to ICMP message */
491         
492         memmove(packet->data + ether_size + ip6_size + icmp6_size, packet->data + ether_size, pseudo.length);
493
494         /* Fill in IPv6 header */
495         
496         ip6.ip6_flow = htonl(0x60000000UL);
497         ip6.ip6_plen = htons(icmp6_size + pseudo.length);
498         ip6.ip6_nxt = IPPROTO_ICMPV6;
499         ip6.ip6_hlim = 255;
500         ip6.ip6_src = pseudo.ip6_src;
501         ip6.ip6_dst = pseudo.ip6_dst;
502
503         /* Fill in ICMP header */
504         
505         icmp6.icmp6_type = type;
506         icmp6.icmp6_code = code;
507         icmp6.icmp6_cksum = 0;
508
509         /* Create pseudo header */
510                 
511         pseudo.length = htonl(icmp6_size + pseudo.length);
512         pseudo.next = htonl(IPPROTO_ICMPV6);
513
514         /* Generate checksum */
515         
516         checksum = inet_checksum(&pseudo, sizeof pseudo, ~0);
517         checksum = inet_checksum(&icmp6, icmp6_size, checksum);
518         checksum = inet_checksum(packet->data + ether_size + ip6_size + icmp6_size, ntohl(pseudo.length) - icmp6_size, checksum);
519
520         icmp6.icmp6_cksum = checksum;
521
522         /* Copy structs on stack back to packet */
523
524         memcpy(packet->data + ether_size, &ip6, ip6_size);
525         memcpy(packet->data + ether_size + ip6_size, &icmp6, icmp6_size);
526         
527         packet->len = ether_size + ip6_size + ntohl(pseudo.length);
528         
529         send_packet(source, packet);
530 }
531
532 static void route_ipv6_unicast(node_t *source, vpn_packet_t *packet) {
533         subnet_t *subnet;
534         node_t *via;
535         ipv6_t dest;
536
537         memcpy(&dest, &packet->data[38], sizeof dest);
538         subnet = lookup_subnet_ipv6(&dest);
539
540         if(!subnet) {
541                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet from %s (%s): unknown IPv6 destination address %hx:%hx:%hx:%hx:%hx:%hx:%hx:%hx",
542                                 source->name, source->hostname,
543                                 ntohs(dest.x[0]),
544                                 ntohs(dest.x[1]),
545                                 ntohs(dest.x[2]),
546                                 ntohs(dest.x[3]),
547                                 ntohs(dest.x[4]),
548                                 ntohs(dest.x[5]),
549                                 ntohs(dest.x[6]),
550                                 ntohs(dest.x[7]));
551
552                 route_ipv6_unreachable(source, packet, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR);
553                 return;
554         }
555
556         if(subnet->owner == source) {
557                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Packet looping back to %s (%s)!", source->name, source->hostname);
558                 return;
559         }
560
561         if(!subnet->owner->status.reachable)
562                 return route_ipv6_unreachable(source, packet, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOROUTE);
563
564         if(forwarding_mode == FMODE_OFF && source != myself && subnet->owner != myself)
565                 return route_ipv6_unreachable(source, packet, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN);
566
567         via = (subnet->owner->via == myself) ? subnet->owner->nexthop : subnet->owner->via;
568         
569         if(directonly && subnet->owner != via)
570                 return route_ipv6_unreachable(source, packet, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN);
571
572         if(via && packet->len > MAX(via->mtu, 1294) && via != myself) {
573                 ifdebug(TRAFFIC) logger(LOG_INFO, "Packet for %s (%s) length %d larger than MTU %d", subnet->owner->name, subnet->owner->hostname, packet->len, via->mtu);
574                 packet->len = MAX(via->mtu, 1294);
575                 route_ipv6_unreachable(source, packet, ICMP6_PACKET_TOO_BIG, 0);
576                 return;
577         }
578
579         clamp_mss(source, via, packet);
580  
581         send_packet(subnet->owner, packet);
582 }
583
584 /* RFC 2461 */
585
586 static void route_neighborsol(node_t *source, vpn_packet_t *packet) {
587         struct ip6_hdr ip6;
588         struct nd_neighbor_solicit ns;
589         struct nd_opt_hdr opt;
590         subnet_t *subnet;
591         uint16_t checksum;
592         bool has_opt;
593
594         struct {
595                 struct in6_addr ip6_src;        /* source address */
596                 struct in6_addr ip6_dst;        /* destination address */
597                 uint32_t length;
598                 uint32_t next;
599         } pseudo;
600
601         if(!checklength(source, packet, ether_size + ip6_size + ns_size))
602                 return;
603         
604         has_opt = packet->len >= ether_size + ip6_size + ns_size + opt_size + ETH_ALEN;
605         
606         if(source != myself) {
607                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Got neighbor solicitation request from %s (%s) while in router mode!", source->name, source->hostname);
608                 return;
609         }
610
611         /* Copy headers from packet to structs on the stack */
612
613         memcpy(&ip6, packet->data + ether_size, ip6_size);
614         memcpy(&ns, packet->data + ether_size + ip6_size, ns_size);
615         if(has_opt)
616                 memcpy(&opt, packet->data + ether_size + ip6_size + ns_size, opt_size);
617
618         /* First, snatch the source address from the neighbor solicitation packet */
619
620         if(overwrite_mac)
621                 memcpy(mymac.x, packet->data + ETH_ALEN, ETH_ALEN);
622
623         /* Check if this is a valid neighbor solicitation request */
624
625         if(ns.nd_ns_hdr.icmp6_type != ND_NEIGHBOR_SOLICIT ||
626            (has_opt && opt.nd_opt_type != ND_OPT_SOURCE_LINKADDR)) {
627                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet: received unknown type neighbor solicitation request");
628                 return;
629         }
630
631         /* Create pseudo header */
632
633         pseudo.ip6_src = ip6.ip6_src;
634         pseudo.ip6_dst = ip6.ip6_dst;
635         if(has_opt)
636                 pseudo.length = htonl(ns_size + opt_size + ETH_ALEN);
637         else
638                 pseudo.length = htonl(ns_size);
639         pseudo.next = htonl(IPPROTO_ICMPV6);
640
641         /* Generate checksum */
642
643         checksum = inet_checksum(&pseudo, sizeof pseudo, ~0);
644         checksum = inet_checksum(&ns, ns_size, checksum);
645         if(has_opt) {
646                 checksum = inet_checksum(&opt, opt_size, checksum);
647                 checksum = inet_checksum(packet->data + ether_size + ip6_size + ns_size + opt_size, ETH_ALEN, checksum);
648         }
649
650         if(checksum) {
651                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet: checksum error for neighbor solicitation request");
652                 return;
653         }
654
655         /* Check if the IPv6 address exists on the VPN */
656
657         subnet = lookup_subnet_ipv6((ipv6_t *) &ns.nd_ns_target);
658
659         if(!subnet) {
660                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet: neighbor solicitation request for unknown address %hx:%hx:%hx:%hx:%hx:%hx:%hx:%hx",
661                                    ntohs(((uint16_t *) &ns.nd_ns_target)[0]),
662                                    ntohs(((uint16_t *) &ns.nd_ns_target)[1]),
663                                    ntohs(((uint16_t *) &ns.nd_ns_target)[2]),
664                                    ntohs(((uint16_t *) &ns.nd_ns_target)[3]),
665                                    ntohs(((uint16_t *) &ns.nd_ns_target)[4]),
666                                    ntohs(((uint16_t *) &ns.nd_ns_target)[5]),
667                                    ntohs(((uint16_t *) &ns.nd_ns_target)[6]),
668                                    ntohs(((uint16_t *) &ns.nd_ns_target)[7]));
669
670                 return;
671         }
672
673         /* Check if it is for our own subnet */
674
675         if(subnet->owner == myself)
676                 return;                                 /* silently ignore */
677
678         /* Create neighbor advertation reply */
679
680         memcpy(packet->data, packet->data + ETH_ALEN, ETH_ALEN);        /* copy destination address */
681         packet->data[ETH_ALEN * 2 - 1] ^= 0xFF; /* mangle source address so it looks like it's not from us */
682
683         ip6.ip6_dst = ip6.ip6_src;                      /* swap destination and source protocoll address */
684         ip6.ip6_src = ns.nd_ns_target;
685
686         if(has_opt)
687                 memcpy(packet->data + ether_size + ip6_size + ns_size + opt_size, packet->data + ETH_ALEN, ETH_ALEN);   /* add fake source hard addr */
688
689         ns.nd_ns_cksum = 0;
690         ns.nd_ns_type = ND_NEIGHBOR_ADVERT;
691         ns.nd_ns_reserved = htonl(0x40000000UL);        /* Set solicited flag */
692         opt.nd_opt_type = ND_OPT_TARGET_LINKADDR;
693
694         /* Create pseudo header */
695
696         pseudo.ip6_src = ip6.ip6_src;
697         pseudo.ip6_dst = ip6.ip6_dst;
698         if(has_opt)
699                 pseudo.length = htonl(ns_size + opt_size + ETH_ALEN);
700         else
701                 pseudo.length = htonl(ns_size);
702         pseudo.next = htonl(IPPROTO_ICMPV6);
703
704         /* Generate checksum */
705
706         checksum = inet_checksum(&pseudo, sizeof pseudo, ~0);
707         checksum = inet_checksum(&ns, ns_size, checksum);
708         if(has_opt) {
709                 checksum = inet_checksum(&opt, opt_size, checksum);
710                 checksum = inet_checksum(packet->data + ether_size + ip6_size + ns_size + opt_size, ETH_ALEN, checksum);
711         }
712
713         ns.nd_ns_hdr.icmp6_cksum = checksum;
714
715         /* Copy structs on stack back to packet */
716
717         memcpy(packet->data + ether_size, &ip6, ip6_size);
718         memcpy(packet->data + ether_size + ip6_size, &ns, ns_size);
719         if(has_opt)
720                 memcpy(packet->data + ether_size + ip6_size + ns_size, &opt, opt_size);
721
722         send_packet(source, packet);
723 }
724
725 static void route_ipv6(node_t *source, vpn_packet_t *packet) {
726         if(!checklength(source, packet, ether_size + ip6_size))
727                 return;
728
729         if(packet->data[20] == IPPROTO_ICMPV6 && checklength(source, packet, ether_size + ip6_size + icmp6_size) && packet->data[54] == ND_NEIGHBOR_SOLICIT) {
730                 route_neighborsol(source, packet);
731                 return;
732         }
733
734         if(packet->data[38] == 255)
735                 broadcast_packet(source, packet);
736         else
737                 route_ipv6_unicast(source, packet);
738 }
739
740 /* RFC 826 */
741
742 static void route_arp(node_t *source, vpn_packet_t *packet) {
743         struct ether_arp arp;
744         subnet_t *subnet;
745         struct in_addr addr;
746
747         if(!checklength(source, packet, ether_size + arp_size))
748                 return;
749
750         if(source != myself) {
751                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Got ARP request from %s (%s) while in router mode!", source->name, source->hostname);
752                 return;
753         }
754
755         /* First, snatch the source address from the ARP packet */
756
757         if(overwrite_mac)
758                 memcpy(mymac.x, packet->data + ETH_ALEN, ETH_ALEN);
759
760         /* Copy headers from packet to structs on the stack */
761
762         memcpy(&arp, packet->data + ether_size, arp_size);
763
764         /* Check if this is a valid ARP request */
765
766         if(ntohs(arp.arp_hrd) != ARPHRD_ETHER || ntohs(arp.arp_pro) != ETH_P_IP ||
767            arp.arp_hln != ETH_ALEN || arp.arp_pln != sizeof addr || ntohs(arp.arp_op) != ARPOP_REQUEST) {
768                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet: received unknown type ARP request");
769                 return;
770         }
771
772         /* Check if the IPv4 address exists on the VPN */
773
774         subnet = lookup_subnet_ipv4((ipv4_t *) &arp.arp_tpa);
775
776         if(!subnet) {
777                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet: ARP request for unknown address %d.%d.%d.%d",
778                                    arp.arp_tpa[0], arp.arp_tpa[1], arp.arp_tpa[2],
779                                    arp.arp_tpa[3]);
780                 return;
781         }
782
783         /* Check if it is for our own subnet */
784
785         if(subnet->owner == myself)
786                 return;                                 /* silently ignore */
787
788         memcpy(packet->data, packet->data + ETH_ALEN, ETH_ALEN);        /* copy destination address */
789         packet->data[ETH_ALEN * 2 - 1] ^= 0xFF; /* mangle source address so it looks like it's not from us */
790
791         memcpy(&addr, arp.arp_tpa, sizeof addr);        /* save protocol addr */
792         memcpy(arp.arp_tpa, arp.arp_spa, sizeof addr);  /* swap destination and source protocol address */
793         memcpy(arp.arp_spa, &addr, sizeof addr);        /* ... */
794
795         memcpy(arp.arp_tha, arp.arp_sha, ETH_ALEN);     /* set target hard/proto addr */
796         memcpy(arp.arp_sha, packet->data + ETH_ALEN, ETH_ALEN); /* add fake source hard addr */
797         arp.arp_op = htons(ARPOP_REPLY);
798
799         /* Copy structs on stack back to packet */
800
801         memcpy(packet->data + ether_size, &arp, arp_size);
802
803         send_packet(source, packet);
804 }
805
806 static void route_mac(node_t *source, vpn_packet_t *packet) {
807         subnet_t *subnet;
808         mac_t dest;
809
810         /* Learn source address */
811
812         if(source == myself) {
813                 mac_t src;
814                 memcpy(&src, &packet->data[6], sizeof src);
815                 learn_mac(&src);
816         }
817
818         /* Lookup destination address */
819
820         memcpy(&dest, &packet->data[0], sizeof dest);
821         subnet = lookup_subnet_mac(NULL, &dest);
822
823         if(!subnet) {
824                 broadcast_packet(source, packet);
825                 return;
826         }
827
828         if(subnet->owner == source) {
829                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Packet looping back to %s (%s)!", source->name, source->hostname);
830                 return;
831         }
832
833         if(forwarding_mode == FMODE_OFF && source != myself && subnet->owner != myself)
834                 return;
835
836         // Handle packets larger than PMTU
837
838         node_t *via = (subnet->owner->via == myself) ? subnet->owner->nexthop : subnet->owner->via;
839
840         if(directonly && subnet->owner != via)
841                 return;
842         
843         if(via && packet->len > via->mtu && via != myself) {
844                 ifdebug(TRAFFIC) logger(LOG_INFO, "Packet for %s (%s) length %d larger than MTU %d", subnet->owner->name, subnet->owner->hostname, packet->len, via->mtu);
845                 uint16_t type = packet->data[12] << 8 | packet->data[13];
846                 if(type == ETH_P_IP && packet->len > 590) {
847                         if(packet->data[20] & 0x40) {
848                                 packet->len = via->mtu;
849                                 route_ipv4_unreachable(source, packet, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED);
850                         } else {
851                                 fragment_ipv4_packet(via, packet);
852                         }
853                         return;
854                 } else if(type == ETH_P_IPV6 && packet->len > 1294) {
855                         packet->len = via->mtu;
856                         route_ipv6_unreachable(source, packet, ICMP6_PACKET_TOO_BIG, 0);
857                         return;
858                 }
859         }
860
861         clamp_mss(source, via, packet);
862  
863         send_packet(subnet->owner, packet);
864 }
865
866 static void send_pcap(vpn_packet_t *packet) {
867         pcap = false;
868         for(splay_node_t *node = connection_tree->head; node; node = node->next) {
869                 connection_t *c = node->data;
870                 if(!c->status.pcap)
871                         continue;
872                 else
873                         pcap = true;
874                 if(send_request(c, "%d %d %d", CONTROL, REQ_PCAP, packet->len))
875                         send_meta(c, (char *)packet->data, packet->len);
876         }
877 }
878
879 void route(node_t *source, vpn_packet_t *packet) {
880         if(pcap)
881                 send_pcap(packet);
882
883         if(forwarding_mode == FMODE_KERNEL && source != myself) {
884                 send_packet(myself, packet);
885                 return;
886         }
887
888         if(!checklength(source, packet, ether_size))
889                 return;
890
891         switch (routing_mode) {
892                 case RMODE_ROUTER:
893                         {
894                                 uint16_t type = packet->data[12] << 8 | packet->data[13];
895
896                                 switch (type) {
897                                         case ETH_P_ARP:
898                                                 route_arp(source, packet);
899                                                 break;
900
901                                         case ETH_P_IP:
902                                                 route_ipv4(source, packet);
903                                                 break;
904
905                                         case ETH_P_IPV6:
906                                                 route_ipv6(source, packet);
907                                                 break;
908
909                                         default:
910                                                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet from %s (%s): unknown type %hx", source->name, source->hostname, type);
911                                                 break;
912                                 }
913                         }
914                         break;
915
916                 case RMODE_SWITCH:
917                         route_mac(source, packet);
918                         break;
919
920                 case RMODE_HUB:
921                         broadcast_packet(source, packet);
922                         break;
923         }
924 }