Fixed a stx err
[6bed4] / 6bed4peer.c
1 /* 6bed4/peer.c -- Peer-to-Peer IPv6-anywhere with 6bed4 -- peer.c
2  *
3  * This is an implementation of neighbour and router discovery over a
4  * tunnel that packs IPv6 inside UDP/IPv4.  This tunnel mechanism is
5  * so efficient that the server administrators need not mind if it is
6  * distributed widely.
7  *
8  * From: Rick van Rein <rick@openfortress.nl>
9  */
10
11
12 #include <stdlib.h>
13 #include <stdbool.h>
14 #include <stdint.h>
15 #include <stdio.h>
16 #include <errno.h>
17 #include <unistd.h>
18 #include <string.h>
19 #include <getopt.h>
20 #include <fcntl.h>
21 #include <time.h>
22
23 #include <syslog.h>
24 #ifndef LOG_PERROR
25 #define LOG_PERROR LOG_CONS             /* LOG_PERROR is non-POSIX, LOG_CONS is */
26 #endif
27
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <sys/time.h>
31 #include <sys/select.h>
32 #include <sys/ioctl.h>
33
34 #include <net/if.h>
35
36 #include <netinet/in.h>
37 #include <netinet/ip.h>
38 #include <netinet/ip6.h>
39 #include <netinet/udp.h>
40 #include <netinet/icmp6.h>
41 #include <arpa/inet.h>
42
43 #include <asm/types.h>
44 #include <linux/if.h>
45 #include <linux/if_tun.h>
46 #include <linux/if_ether.h>
47 #include <linux/netlink.h>
48 #include <linux/rtnetlink.h>
49
50 /* The following will initially fail, due to an IANA obligation to avoid
51  * default builds with non-standard options.
52  */
53 #include "nonstd.h"
54
55
56 #define MTU 1280
57
58 typedef enum {
59         METRIC_LOW,
60         METRIC_MEDIUM,
61         METRIC_HIGH
62 } metric_t;
63
64 /*
65  * The HAVE_SETUP_TUNNEL variable is used to determine whether absense of
66  * the -t option leads to an error, or to an attempt to setup the tunnel.
67  * The setup_tunnel() function used for that is defined per platform, such
68  * as for LINUX.  Remember to maintain the manpage's optionality for -t.
69  */
70 #undef HAVE_SETUP_TUNNEL
71
72
73 /* Global variables */
74
75 char *program;
76
77 int rtsox = -1;
78 int v4sox = -1;
79 int v6sox = -1;
80 int v4mcast = -1;
81
82 uint8_t v4qos = 0;              /* Current QoS setting on UDP/IPv4 socket */
83 uint32_t v6tc = 0;              /* Current QoS used by the IPv6 socket */
84 uint8_t v4ttl = 64;             /* Default TTL setting on UDP/IPv4 socket */
85 int v4ttl_mcast = -1;           /* Multicast TTL for LAN explorations */
86
87 char *v4server = NULL;
88 char *v6server = NULL;
89 char v6prefix [INET6_ADDRSTRLEN];
90 uint8_t v6lladdr [6];
91
92 const uint8_t v6listen_linklocal [16] = { 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
93 uint8_t v6listen_linklocal_complete [16] = { 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
94
95 struct sockaddr_nl rtname;
96 struct sockaddr_nl rtkernel;
97
98 struct sockaddr_in  v4name;
99 struct sockaddr_in  v4peer;
100 struct sockaddr_in6 v6name;
101
102 struct sockaddr_in v4bind;
103 struct sockaddr_in v4allnodes;
104
105 struct in6_addr v6listen;
106 //TODO:NEEDNOT// struct in6_addr v6listen_complete;
107 struct in_addr  v4listen;
108
109
110 struct {
111         struct ethhdr eth;
112         union {
113                 struct {
114                         struct ip6_hdr v6hdr;
115                         uint8_t data [MTU - sizeof (struct ip6_hdr)];
116                 } idata;
117                 struct {
118                         struct ip6_hdr v6hdr;
119                         struct icmp6_hdr v6icmphdr;
120                 } ndata;
121         } udata;
122 } __attribute__((packed)) v4data6;
123
124 #define v4ether         (v4data6.eth)
125 #define v4data          ((uint8_t *) &v4data6.udata)
126 #define v4hdr6          (&v4data6.udata.idata.v6hdr)
127 #define v4src6          (&v4data6.udata.idata.v6hdr.ip6_src)
128 #define v4dst6          (&v4data6.udata.idata.v6hdr.ip6_dst)
129
130 #define v4v6plen        (v4data6.udata.ndata.v6hdr.ip6_plen)
131 #define v4v6nexthdr     (v4data6.udata.ndata.v6hdr.ip6_nxt)
132 #define v4v6hoplimit    (v4data6.udata.ndata.v6hdr.ip6_hops)
133
134 #define v4icmp6         (&v4data6.udata.ndata.v6icmphdr)
135 #define v4v6icmpdata    (v4data6.udata.ndata.v6icmphdr.icmp6_data8)
136 #define v4v6icmptype    (v4data6.udata.ndata.v6icmphdr.icmp6_type)
137 #define v4v6icmpcode    (v4data6.udata.ndata.v6icmphdr.icmp6_code)
138 #define v4v6icmpcksum   (v4data6.udata.ndata.v6icmphdr.icmp6_cksum)
139 #define v4v6ndtarget    (&v4data6.udata.ndata.v6icmphdr.icmp6_data8 [4])
140
141
142 struct {
143         struct ethhdr eth;
144         union {
145                 uint8_t data [MTU];
146                 struct {
147                         struct ip6_hdr v6hdr;
148                         struct icmp6_hdr v6icmp;
149                 } __attribute__((packed)) ndata;
150         } udata;
151 }  __attribute__((packed)) v6data6;
152
153 #define v6ether         (v6data6.eth)
154 #define v6data          (v6data6.udata.data)
155 #define v6hdr6          (&v6data6.udata.ndata.v6hdr)
156 #define v6hops          (v6data6.udata.ndata.v6hdr.ip6_hops)
157 #define v6type          (v6data6.udata.ndata.v6hdr.ip6_nxt)
158 #define v6plen          (v6data6.udata.ndata.v6hdr.ip6_plen)
159 #define v6src6          (&v6data6.udata.ndata.v6hdr.ip6_src)
160 #define v6dst6          (&v6data6.udata.ndata.v6hdr.ip6_dst)
161 #define v6icmp6type     (v6data6.udata.ndata.v6icmp.icmp6_type)
162 #define v6icmp6code     (v6data6.udata.ndata.v6icmp.icmp6_code)
163 #define v6icmp6data     (v6data6.udata.ndata.v6icmp.icmp6_data8)
164 #define v6icmp6csum     (v6data6.udata.ndata.v6icmp.icmp6_cksum)
165 #define v6ndtarget      (&v6data6.udata.ndata.v6icmp.icmp6_data16[2])
166
167
168 /* Structure for tasks in neighbor discovery queues
169  */
170 struct ndqueue {
171         struct ndqueue *next;
172         struct timeval tv;
173         struct in6_addr source;
174         struct in6_addr target;
175         uint8_t source_lladdr [6];
176         uint8_t todo_lancast, todo_direct;
177 };
178
179 /* Round-robin queue for regular tasks, starting at previous value */
180 struct ndqueue *ndqueue = NULL;
181 struct ndqueue *freequeue = NULL;
182 uint32_t freequeue_items = 100;
183
184 /* The time for the next scheduled maintenance: routersol or keepalive.
185  * The milliseconds are always 0 for maintenance tasks.
186  */
187 time_t maintenance_time_sec;
188 time_t maintenance_time_cycle = 0;
189 time_t maintenance_time_cycle_max = 30;
190 bool got_lladdr = false;
191 time_t keepalive_period = 30;
192 time_t keepalive_ttl = -1;
193
194 /* The network packet structure of a 6bed4 Router Solicitation */
195
196 uint8_t ipv6_router_solicitation [] = {
197         // IPv6 header
198         0x60, 0x00, 0x00, 0x00,
199         16 >> 8, 16 & 0xff, IPPROTO_ICMPV6, 255,
200         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,          // unspecd src
201         0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02, // all-rtr tgt
202         // ICMPv6 header: router solicitation
203         ND_ROUTER_SOLICIT, 0, 0x7a, 0xae,       // Checksum courtesy of WireShark :)
204         // ICMPv6 body: reserved
205         0, 0, 0, 0,
206         // ICMPv6 option: source link layer address 0x0001 (end-aligned)
207         0x01, 0x01, 0, 0, 0, 0, 0x00, 0x01,
208 };
209
210 uint8_t ipv6_defaultrouter_neighbor_advertisement [] = {
211         // IPv6 header
212         0x60, 0x00, 0x00, 0x00,
213         32 >> 8, 32 & 0xff, IPPROTO_ICMPV6, 255,
214         0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   // src is default router
215         0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01,// dst is all-nodes multicast, portable?
216         // ICMPv6 header: neighbor solicitation
217         ND_NEIGHBOR_ADVERT, 0, 0x36, 0xf2,              // Checksum courtesy of WireShark :)
218         // ICMPv6 Neighbor Advertisement: flags
219         0x40, 0, 0, 0,
220         // Target: fe80::
221         0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,   // the targeted neighbor
222         // ICMPv6 option: target link layer address
223         2, 1,
224         UDP_PORT_6BED4 & 0xff, UDP_PORT_6BED4 >> 8,
225         SERVER_6BED4_IPV4_INT0, SERVER_6BED4_IPV4_INT1, SERVER_6BED4_IPV4_INT2, SERVER_6BED4_IPV4_INT3
226 };
227
228 uint8_t router_linklocal_address [] = {
229         0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00,
230 };
231
232 //TODO// Complete with the if-id of the 6bed4 Router:
233 uint8_t router_linklocal_address_complete [] = {
234         0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00,
235 };
236
237 uint8_t democlient_linklocal_address [] = {
238         0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x01,
239 };
240
241 uint8_t allnodes_linklocal_address [] = {
242         0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x01,
243 };
244
245 uint8_t allrouters_linklocal_address [] = {
246         0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x02,
247 };
248
249 uint8_t solicitednodes_linklocal_prefix [13] = {
250         0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01, 0xff
251 };
252
253 bool default_route = false;
254
255 bool foreground = false;
256
257 bool log_to_stderr = false;
258
259 bool multicast = true;
260
261
262 /*
263  *
264  * Driver routines
265  *
266  */
267
268 #ifdef LINUX
269 #define HAVE_SETUP_TUNNEL
270 static struct ifreq ifreq;
271 static bool have_tunnel = false;
272 /* Implement the setup_tunnel() command for Linux.
273  * Return true on success, false on failure.
274  */
275 bool setup_tunnel (void) {
276         if (v6sox == -1) {
277                 v6sox = open ("/dev/net/tun", O_RDWR);
278         }
279         if (v6sox == -1) {
280                 syslog (LOG_ERR, "%s: Failed to access tunnel driver on /dev/net/tun: %s\n", program, strerror (errno));
281                 return 0;
282         }
283         bool ok = true;
284         int flags = fcntl (v6sox, F_GETFL, 0);
285         if (flags == -1) {
286                 syslog (LOG_CRIT, "Failed to retrieve flags for the tunnel file descriptor: %s\n", strerror (errno));
287                 ok = false;
288         }
289         if (!have_tunnel) {
290                 memset (&ifreq, 0, sizeof (ifreq));
291                 strncpy (ifreq.ifr_name, "6bed4", IFNAMSIZ);
292                 ifreq.ifr_flags = IFF_TAP | IFF_NO_PI;
293                 if (ok && (ioctl (v6sox, TUNSETIFF, (void *) &ifreq) == -1)) {
294                         syslog (LOG_CRIT, "Failed to set interface name: %s\n", strerror (errno));
295                         ok = false;
296                 } else {
297                         have_tunnel = ok;
298                 }
299                 ifreq.ifr_name [IFNAMSIZ] = 0;
300                 ifreq.ifr_ifindex = if_nametoindex (ifreq.ifr_name);
301 syslog (LOG_DEBUG, "Found Interface Index %d for name %s\n", ifreq.ifr_ifindex, ifreq.ifr_name);
302                 ok = ok & (ifreq.ifr_ifindex != 0);
303         }
304         char cmd [512+1];
305         snprintf (cmd, 512, "/sbin/sysctl -q -w net.ipv6.conf.%s.forwarding=0", ifreq.ifr_name);
306         if (ok && system (cmd) != 0) {
307                 ok = false;
308         }
309         snprintf (cmd, 512, "/sbin/sysctl -q -w net.ipv6.conf.%s.accept_dad=0", ifreq.ifr_name);
310         if (ok && system (cmd) != 0) {
311                 ok = false;
312         }
313         if (!ok) {
314                 close (v6sox);  /* This removes the tunnel interface */
315                 v6sox = -1;
316         }
317         return ok;
318 }
319 bool setup_tunnel_address (void) {
320         bool ok = have_tunnel;
321         char cmd [512+1];
322
323         snprintf (cmd, 512, "/sbin/sysctl -q -w net.ipv6.conf.%s.autoconf=0", ifreq.ifr_name);
324         if (ok && system (cmd) != 0) {
325                 ok = 0;
326         }
327         snprintf (cmd, 512, "/sbin/ip link set %s address %02x:%02x:%02x:%02x:%02x:%02x", ifreq.ifr_name, v6lladdr [0], v6lladdr [1], v6lladdr [2], v6lladdr [3], v6lladdr [4], v6lladdr [5]);
328         if (ok && system (cmd) != 0) {
329 syslog (LOG_CRIT, "Bad news!\n");
330                 ok = false;
331         }
332         snprintf (cmd, 512, "/sbin/ip link set %s up mtu %d", ifreq.ifr_name, MTU);
333         if (ok && system (cmd) != 0) {
334                 ok = false;
335         }
336         snprintf (cmd, 512, "/sbin/ip -6 addr add %s/64 dev %s", v6prefix, ifreq.ifr_name);
337         if (ok && system (cmd) != 0) {
338                 ok = false;
339         }
340         if (default_route) {
341                 snprintf (cmd, 512, "/sbin/ip -6 route add default via fe80:: dev %s", ifreq.ifr_name);
342                 if (ok && system (cmd) != 0) {
343                         ok = false;
344                 }
345         }
346         return ok;
347 }
348 #endif /* LINUX */
349
350
351 /*
352  *
353  * Utility functions
354  *
355  */
356
357
358 /* Look for an entry in the 50ms-cycled Neighbor Discovery queue.
359  * Match the target address.  Return the entry found, or NULL.
360  */
361 struct ndqueue *findqueue (struct in6_addr *target) {
362         struct ndqueue *ndq = ndqueue;
363         if (ndq) {
364                 do {
365                         if (memcmp (target, &ndq->target, 16) == 0) {
366                                 return ndq;
367                         }
368                         ndq = ndq->next;
369                 } while (ndq != ndqueue);
370         }
371         return NULL;
372 }
373
374 /* Enter an item in the 50ms-cycled Neighbor Discovery queue.
375  * Retrieve its storage space from the free queue.
376  * TODO: Avoid double entries by looking up entries first -> "requeue?"
377  */
378 static int TODO_qlen;
379 void enqueue (struct in6_addr *target, struct in6_addr *v6src, uint8_t *source_lladdr) {
380         //
381         // Refuse to create double entries
382         if (findqueue (target)) {
383                 return;
384         }
385         //
386         // Allocate a free item to enqueue
387         struct ndqueue *new = freequeue;
388         if (!new) {
389                 // Temporarily overflown with ND -> drop the request
390                 return;
391         }
392 char tgt [INET6_ADDRSTRLEN]; inet_ntop (AF_INET6, target, tgt, sizeof (tgt));
393 syslog (LOG_DEBUG, "Queue++ => %d, looking for %s\n", ++TODO_qlen, tgt);
394         freequeue = freequeue->next;
395         //
396         // Setup the new entry with target details
397         memcpy (&new->target, target, sizeof (new->target));
398         memcpy (&new->source, v6src, sizeof (new->source));
399         memcpy (&new->source_lladdr, source_lladdr, sizeof (new->source_lladdr));
400         new->todo_lancast = (v4mcast == -1)? 0: 2;
401         new->todo_direct = 3;
402         //
403         // Time the new item to run instantly
404         new->tv.tv_sec = 0;
405         //
406         // Enqueue the new item in front of the queue
407         if (ndqueue) {
408                 new->next = ndqueue->next;
409                 ndqueue->next = new;
410         } else {
411                 new->next = new;
412                 ndqueue = new;
413         }
414 }
415
416 /* Remove an item from the 50ms-cycled Neighbor Discovery queue.
417  * Enter its storage space in the free queue.
418  */
419 void dequeue (struct ndqueue *togo) {
420         struct ndqueue *prev = ndqueue;
421         do {
422                 if (prev->next == togo) {
423                         if (togo->next != togo) {
424                                 prev->next = togo->next;
425                                 if (ndqueue == togo) {
426                                         ndqueue = togo->next;
427                                 }
428                         } else {
429                                 // Must be the only queued item
430                                 ndqueue = NULL;
431                         }
432                         togo->next = freequeue;
433                         freequeue = togo;
434 syslog (LOG_DEBUG, "Queue-- => %d\n", --TODO_qlen);
435                         return;
436                 }
437                 prev = prev->next;
438         } while (prev != ndqueue);
439 }
440
441
442 /*
443  * Calculate the ICMPv6 checksum field
444  */
445 uint16_t icmp6_checksum (uint8_t *ipv6hdr, size_t payloadlen) {
446         uint16_t plenword = htons (payloadlen);
447         uint16_t nxthword = htons (IPPROTO_ICMPV6);
448         uint16_t *areaptr [] = { (uint16_t *) &ipv6hdr [8], (uint16_t *) &ipv6hdr [24], &plenword, &nxthword, (uint16_t *) &ipv6hdr [40], (uint16_t *) &ipv6hdr [40 + 4] };
449         uint8_t areawords [] = { 8, 8, 1, 1, 1, payloadlen/2 - 2 };
450         uint32_t csum = 0;
451         u_int8_t i, j;
452         for (i=0; i < 6; i++) {
453                 uint16_t *area = areaptr [i];
454                 for (j=0; j<areawords [i]; j++) {
455                         csum += ntohs (area [j]);
456                 }
457         }
458         csum = (csum & 0xffff) + (csum >> 16);
459         csum = (csum & 0xffff) + (csum >> 16);
460         csum = htons (~csum);
461         return csum;
462 }
463
464
465 /*
466  * Send a Redirect reply.  This is in response to a v4v6data message,
467  * and is directed straight at the origin's address but sent with a
468  * lower metric.
469  *
470  * Note: Although the packet arrived in v4data6, the reply is built
471  *       in v6data6 and sent from there as though it had come from
472  *       the IPv6 stack.
473  */
474 void redirect_reply (uint8_t *ngbc_llremote, metric_t ngbc_metric) {
475         void handle_6to4_plain_unicast (const ssize_t pktlen, const uint8_t *lladdr);
476         v6icmp6type = ND_REDIRECT;
477         v6icmp6code = 0;
478         v6icmp6data [0] =
479         v6icmp6data [1] =
480         v6icmp6data [2] =
481         v6icmp6data [3] = 0;            // Reserved
482         memcpy (v6icmp6data + 4, &v6listen, 16);
483                                         // Target IPv6 address
484         switch (ngbc_metric) {
485                                         // Destination Address suggestion
486         case METRIC_LOW:
487                 //
488                 // Redirect to the local-subnet IPv4 address
489                 memcpy (v6icmp6data + 4 + 16, v6listen_linklocal, 8);
490                 v6icmp6data [4 + 16 + 8 ] = v4peer.sin_port & 0x00ff;
491                 v6icmp6data [4 + 16 + 9 ] = v4peer.sin_port >> 8;
492                 memcpy (v6icmp6data + 4 + 16 + 12, &v4peer.sin_addr, 4);
493                 v6icmp6data [4 + 16 + 10] = v4v6icmpdata [4 + 16 + 12];
494                 v6icmp6data [4 + 16 + 11] = 0xff;
495                 v6icmp6data [4 + 16 + 12] = 0xfe;
496                 break;
497         case METRIC_MEDIUM:
498                 memcpy (v6icmp6data + 4 + 16, v6listen_linklocal_complete, 16);
499                 break;
500         case METRIC_HIGH:
501         default:
502                 return;         /* no cause for Redirect, drop */
503         }
504         v6type = IPPROTO_ICMPV6;
505         v6plen = htons (8 + 16 + 16);
506         memcpy (v6src6, &v6listen, 16);
507         memcpy (v6dst6, v4src6, 16);
508         v6icmp6csum = icmp6_checksum ((uint8_t *) v4hdr6, 8 + 16 + 16);
509         handle_6to4_plain_unicast (sizeof (struct ethhdr) + 40 + 8 + 16 + 16, ngbc_llremote);
510
511
512
513 /* Append the current prefix to an ICMPv6 message.  Incoming optidx
514  * and return values signify original and new offset for ICMPv6 options.
515  * The endlife parameter must be set to obtain zero lifetimes, thus
516  * instructing the tunnel client to stop using an invalid prefix.
517  */
518 size_t icmp6_prefix (size_t optidx, uint8_t endlife) {
519         v6icmp6data [optidx++] = 3;     // Type
520         v6icmp6data [optidx++] = 4;     // Length
521         v6icmp6data [optidx++] = 64;    // This is a /64 prefix
522 #ifndef COMPENSATE_FOR_AUTOCONF
523         v6icmp6data [optidx++] = 0xc0;  // L=1, A=1, Reserved1=0
524 #else
525         //TODO// Temporary fix: "ip -6 addr add .../64 dev 6bed4"
526         v6icmp6data [optidx++] = 0x80;  // L=1, A=0, Reserved1=0
527 #endif
528         memset (v6icmp6data + optidx, endlife? 0x00: 0xff, 8);
529         optidx += 8;
530                                         // Valid Lifetime: Zero / Infinite
531                                         // Preferred Lifetime: Zero / Infinite
532         memset (v6icmp6data + optidx, 0, 4);
533         optidx += 4;
534                                         // Reserved2=0
535         memcpy (v6icmp6data + optidx + 0, &v6listen, 8);
536         memset (v6icmp6data + optidx + 8, 0, 8);
537                                         // Set IPv6 prefix
538         optidx += 16;
539         return optidx;
540 }
541
542
543 /*
544  * Construct a Neighbor Advertisement message, providing the
545  * Public 6bed4 Service as the link-local address.
546  *
547  * This is done immediately when the IPv6 stack requests the link-local
548  * address for fe80:: through Router Solicition.  In addition, it is the
549  * fallback response used when attempts to contact the remote peer at its
550  * direct IPv4 address and UDP port (its 6bed4 address) fails repeatedly.
551  *
552  * This routine is called with info==NULL to respond to an fe80::
553  * Neighbor Solicitation, otherwise with an info pointer containing
554  * a target IPv6 address to service.
555  */
556 void advertise_6bed4_public_service (struct ndqueue *info) {
557         if (info) {
558                 memcpy (v6ether.h_dest, info->source_lladdr, 6);
559         } else {
560                 memcpy (v6ether.h_dest, v6ether.h_source, 6);
561         }
562         memcpy (v6ether.h_source, SERVER_6BED4_PORT_IPV4_MACSTR, 6);
563         memcpy (v6data, ipv6_defaultrouter_neighbor_advertisement, 8);
564         if (info) {
565                 memcpy (v6dst6, &info->source, 16);
566         } else {
567                 memcpy (v6dst6, v6src6, 16);
568         }
569         if (info) {
570                 memcpy (v6src6, &info->target, 16);
571         } else {
572                 memcpy (v6src6, router_linklocal_address_complete, 16);
573         }
574         //TODO:OVERWROTE// memcpy (v6data + 8, ipv6_defaultrouter_neighbor_advertisement + 8, 16);
575         memcpy (v6data + 8 + 16 + 16, ipv6_defaultrouter_neighbor_advertisement + 8 + 16 + 16, sizeof (ipv6_defaultrouter_neighbor_advertisement) - 8 - 16 - 16);
576         if (info) {
577                 // Overwrite target only for queued requests
578                 memcpy (&v6icmp6data [4], &info->target, 16);
579         }
580         v6icmp6csum = icmp6_checksum ((uint8_t *) v6hdr6, 32);
581         int sent = write (v6sox, &v6data6, sizeof (struct ethhdr) + sizeof (ipv6_defaultrouter_neighbor_advertisement));
582         if (info) {
583                 syslog (LOG_DEBUG, "TODO: Neighbor Discovery failed to contact directly -- standard response provided\n");
584         } else {
585                 syslog (LOG_DEBUG, "TODO: Neighbor Discovery for Public 6bed4 Service -- standard response provided\n");
586         }
587 }
588
589
590 /*
591  * Test if the provided IPv6 address matches the prefix used for 6bed4.
592  */
593 static inline bool prefix_6bed4 (struct in6_addr *ip6) {
594         return memcmp (&v6listen, ip6->s6_addr, 8) == 0;
595 }
596
597
598 /*
599  * Validate the originator's IPv6 address.  It should match the
600  * UDP/IPv4 coordinates of the receiving 6bed4 socket.  Also,
601  * the /64 prefix must match that of v6listen.
602  */
603 bool validate_originator (struct sockaddr_in *sin, struct in6_addr *ip6) {
604         if ((sin->sin_addr.s_addr == v4peer.sin_addr.s_addr) && (sin->sin_port == v4peer.sin_port)) {
605                 return true;
606         }
607         uint16_t port = ntohs (sin->sin_port);
608         uint32_t addr = ntohl (sin->sin_addr.s_addr);
609 if (memcmp (ip6, v6listen_linklocal, 8) != 0)
610         if (!prefix_6bed4 (ip6)) {
611                 return false;
612         }
613         if ((port & 0xff) != (ip6->s6_addr [8] ^ 0x02)) {
614                 return false;
615         }
616         if ((port >> 8) != ip6->s6_addr [9]) {
617                 return false;
618         }
619         if ((addr >> 24) != ip6->s6_addr [10]) {
620                 return false;
621         }
622         if ((addr & 0x00ffffff) != (htonl (ip6->s6_addr32 [3]) & 0x00ffffff)) {
623                 return false;
624         }
625         return true;
626 }
627
628
629 /*
630  * Translate a Link-Local Address to its metric.  The metrics are
631  * numbered so that a higher number indicates a more costly path
632  * over which to connect.  The values of the metric should not be
633  * published, but be treated as an opaque value with a complete
634  * ordering (that is: <, <=, >=, > relations) defined on it.
635  */
636 metric_t lladdr_metric (uint8_t *lladdr) {
637         uint32_t ipv4 = * (uint32_t *) (lladdr + 2);
638         //
639         // Metric 2: The 6bed4 Router address
640         if (ipv4 == v4peer.sin_addr.s_addr) {
641                 return METRIC_HIGH;
642         }
643         //
644         // Metric 0: Private Addresses, as per RFC 1918
645         if ((ipv4 & 0xff000000) == 0x0a000000) {
646                 return METRIC_LOW;      /* 10.0.0./8 */
647         }
648         if ((ipv4 & 0xffff0000) == 0xc0a80000) {
649                 return METRIC_LOW;      /* 192.168.0.0/16 */
650         }
651         if ((ipv4 & 0xfff00000) == 0xac100000) {
652                 return METRIC_LOW;      /* 172.16.0.0/12 */
653         }
654         //
655         // Metric 1: Direct IPv4 contact is any other address
656         //           Correctness should be checked elsewhere
657         return METRIC_MEDIUM;
658 }
659
660
661 /*
662  * Retrieve the Link-Local Address, if any, for a given 6bed4 Peer.
663  * Return true on success, false on failure to find it.  The lladdr
664  * parameter is only overwritten in case of success.
665  *
666  * Obviously, there is a point where it is more efficient to not
667  * lookup the cache for every request, but to cache it locally
668  * and limit the lookup frequency.  This low-traffic optimal version
669  * is used here for initial simplicity, and because this is a peer
670  * daemon and a reference implementation.  But who knows what people
671  * will submit as patches...
672  *
673  * Note: This code is specific to Linux, but note that BSD also has a
674  *       NetLink concept, so it may port without needing to resort to
675  *       shell commands running slowly in separate processes.
676  * Note: The interface for Linux is under-documented.  Work may be
677  *       needed to handle exception situations, such as going over
678  *       invisible boundaries on the number of neighbours.  Similarly,
679  *       the use of alignment macros is rather unclear.  This is not
680  *       how I prefer to write code, but it's the best I can do now.
681  */
682 bool lookup_neighbor (uint8_t *ipv6, uint8_t *lladdr) {
683         struct mymsg {
684                 struct nlmsghdr hd;
685                 struct ndmsg nd;
686                 uint8_t arg [16384];
687         } msg;
688         memset (&msg, 0, sizeof (struct nlmsghdr) + sizeof (struct ndmsg));
689         msg.hd.nlmsg_len = NLMSG_LENGTH (sizeof (msg.nd));
690         msg.hd.nlmsg_type = RTM_GETNEIGH;
691         msg.hd.nlmsg_flags = NLM_F_REQUEST | NLM_F_ROOT /* | NLM_F_MATCH */;
692         msg.hd.nlmsg_pid = rtname.nl_pid;
693         msg.nd.ndm_family = AF_INET6;
694         msg.nd.ndm_state = NUD_REACHABLE | NUD_DELAY | NUD_PROBE | NUD_PERMANENT | NUD_STALE;   // Ignored by the kernel?
695         msg.nd.ndm_ifindex = ifreq.ifr_ifindex; // Ignored by the kernel?
696         // How to select an IPv6 address?  Ignored by the kernel?
697 #if 0
698         struct rtattr *ra1 = (struct rtattr *) (((char *) &msg) + sizeof (struct nlmsghdr) + sizeof (struct ndmsg));
699         ra1->rta_type = NDA_DST;        // lookup IPv6 address
700         ra1->rta_len = RTA_LENGTH(16);
701         msg.hd.nlmsg_len = NLMSG_ALIGN (msg.hd.nlmsg_len) + RTA_LENGTH (16);
702         memcpy (RTA_DATA (ra1), ipv6, 16);
703 #endif
704         if (send (rtsox, &msg, msg.hd.nlmsg_len, MSG_DONTWAIT) == -1) {
705                 return false;
706         }
707         ssize_t recvlen;
708         uint16_t pos = 0;
709 { char buf [INET6_ADDRSTRLEN]; inet_ntop (AF_INET6, ipv6, buf, sizeof (buf)); syslog (LOG_DEBUG, "Looking up v6addr %s\n", buf); }
710         while (recvlen = recv (rtsox, ((char *) &msg) + pos, sizeof (msg) - pos, MSG_DONTWAIT), recvlen > 0) {
711 syslog (LOG_DEBUG, "Message of %zd bytes from neighbor cache, total is now %zd\n", recvlen, pos + recvlen);
712                 recvlen += pos;
713                 pos = 0;
714                 struct mymsg *resp;
715                 while (resp = (struct mymsg *) (((char *) &msg) + pos),
716                                 (pos + sizeof (struct nlmsghdr) <= recvlen) &&
717                                 (pos + resp->hd.nlmsg_len <= recvlen)) {
718                         bool ok = true, match = false;
719                         uint8_t *result = NULL;
720                         if (resp->hd.nlmsg_type == NLMSG_DONE) {
721                                 return false;
722                         } else if (resp->hd.nlmsg_type != RTM_NEWNEIGH) {
723                                 syslog (LOG_ERR, "Kernel sent an unexpected nlmsg_type 0x%02x, ending neighbor interpretation\n", resp->hd.nlmsg_type);
724                                 ok = false;
725                         } else if (resp->nd.ndm_ifindex != ifreq.ifr_ifindex) {
726                                 ok = false;
727                         } else if (resp->nd.ndm_family != AF_INET6) {
728                                 syslog (LOG_ERR, "Kernel reported unknown neighbor family %d\n", resp->nd.ndm_family);
729                                 ok = false;
730                         } else
731                         if (!(resp->nd.ndm_state & (NUD_REACHABLE | NUD_DELAY | NUD_PROBE | NUD_PERMANENT | NUD_STALE))) {
732                                 ok = false;
733                         }
734                         struct rtattr *ra = (struct rtattr *) ((char *) &resp + pos + sizeof (struct nlmsghdr) + sizeof (struct ndmsg) + 8);
735                         ssize_t rapos = 0;
736                         while (ok && (rapos + ra->rta_len <= resp->hd.nlmsg_len)) {
737                                 switch (ra->rta_type) {
738                                 case NDA_DST:
739 { char buf [INET6_ADDRSTRLEN]; inet_ntop (AF_INET6, RTA_DATA (ra), buf, sizeof (buf)); syslog (LOG_DEBUG, "Comparing against %s\n", buf); }
740                                         if (memcmp (ipv6, RTA_DATA (ra), 16) == 0) {
741                                                 match = true;
742                                         }
743                                         break;
744                                 case NDA_LLADDR:
745                                         result = RTA_DATA (ra);
746                                         break;
747                                 case NDA_PROBES:
748                                 case NDA_CACHEINFO:
749                                 default:
750                                         break;  /* not of interest, skip */
751                                 }
752                                 rapos += ((ra->rta_len - 1) | 0x00000003) + 1;
753                                 ra = (struct rtattr *) (((char *) ra) + (((ra->rta_len - 1) | 0x0000003) + 1));
754                         }
755                         if (ok && match && result) {
756                                 memcpy (lladdr, result, 6);
757                                 return true;    /* Yippy! Erfolg! */
758                         }
759                         pos += resp->hd.nlmsg_len;
760                 }
761                 // Copy remaining partial message to the beginning, continue from there
762                 memcpy (&msg, ((char *) &msg) + pos, recvlen - pos);
763                 pos = recvlen - pos;
764         }
765         return false;
766 }
767
768
769 /*
770  * Major packet processing functions
771  */
772
773
774 /* Handle the IPv4 message pointed at by msg, checking if (TODO:HUH?) the IPv4:port
775  * data matches the lower half of the IPv6 sender address.  Drop silently
776  * if this is not the case.  TODO: or send ICMP?
777  */
778 void handle_4to6_plain (ssize_t v4datalen, struct sockaddr_in *sin) {
779         //
780         // Send the unwrapped IPv6 message out over v6sox
781         v4ether.h_proto = htons (ETH_P_IPV6);
782         memcpy (v4ether.h_dest,   v6lladdr, 6);
783         v4ether.h_source [0] = ntohs (sin->sin_port) & 0xff;
784         v4ether.h_source [1] = ntohs (sin->sin_port) >> 8;
785         memcpy (v4ether.h_source + 2, &sin->sin_addr, 4);
786 syslog (LOG_INFO, "Writing IPv6, result = %zd\n",
787         write (v6sox, &v4data6, sizeof (struct ethhdr) + v4datalen)
788 )
789         ;
790 }
791
792
793 /* Handle the IPv4 message pointed at by msg as a neighbouring command.
794  *
795  * Type Code    ICMPv6 meaning                  Handling
796  * ---- ----    -----------------------------   ----------------------------
797  * 133  0       Router Solicitation             Ignore
798  * 134  0       Router Advertisement            Setup Tunnel with Prefix
799  * 135  0       Neighbour Solicitation          Send Neighbour Advertisement
800  * 136  0       Neighbour Advertisement         Ignore
801  * 137  0       Redirect                        Ignore
802  */
803 void handle_4to6_nd (struct sockaddr_in *sin, ssize_t v4ngbcmdlen) {
804         uint16_t srclinklayer;
805         uint8_t *destprefix = NULL;
806 #ifdef TODO_DEPRECATED
807         uint8_t *destlladdr = NULL;
808 #endif
809         struct ndqueue *ndq;
810         if (v4ngbcmdlen < sizeof (struct ip6_hdr) + sizeof (struct icmp6_hdr)) {
811                 return;
812         }
813         //
814         if (v4v6icmpcode != 0) {
815                 return;
816         }
817         if (icmp6_checksum (v4data, v4ngbcmdlen - sizeof (struct ip6_hdr)) != v4v6icmpcksum) {
818                 return;
819         }
820         //
821         // Approved.  Perform neighbourly courtesy.
822         switch (v4v6icmptype) {
823         case ND_ROUTER_SOLICIT:
824                 return;         /* this is not a router, drop */
825         case ND_ROUTER_ADVERT:
826                 //
827                 // Validate Router Advertisement
828                 if (ntohs (v4v6plen) < sizeof (struct icmp6_hdr) + 16) {
829                         return;   /* strange length, drop */
830                 }
831                 if (v4v6icmpdata [1] & 0x80 != 0x00) {
832                         return;   /* indecent proposal to use DHCPv6, drop */
833                 }
834                 if (memcmp (v4src6, router_linklocal_address, 16) != 0) {
835                         return;   /* not from router, drop */
836                 }
837                 if (memcmp (v4dst6, democlient_linklocal_address, 8) != 0) {
838                         return;   /* no address setup for me, drop */
839                 }
840                 if (v4dst6->s6_addr [8] & 0x01) {
841                         syslog (LOG_WARNING, "TODO: Ignoring (by accepting) an odd public UDP port revealed in a Router Advertisement -- this could cause confusion with multicast traffic\n");
842                 }
843                 size_t rdofs = 12;
844                 //TODO:+4_WRONG?// while (rdofs <= ntohs (v4v6plen) + 4) { ... }
845                 while (rdofs + 4 < ntohs (v4v6plen)) {
846                         if (v4v6icmpdata [rdofs + 1] == 0) {
847                                 return;   /* zero length option */
848                         }
849 #ifdef TODO_DEPRACATED
850                         if ((v4v6icmpdata [rdofs + 0] == ND_OPT_DESTINATION_LINKADDR) && (v4v6icmpdata [rdofs + 1] == 1)) {
851                                 if (v4v6icmpdata [rdofs + 2] & 0x01) {
852                                         syslog (LOG_WARNING, "TODO: Ignoring an odd UDP port offered in a Router Advertisement over 6bed4\n");
853                                 }
854                                 syslog (LOG_INFO, "TODO: Set tunnel link-local address to %02x:%02x:%02x:%02x:%02x:%02x\n", v4v6icmpdata [rdofs + 2], v4v6icmpdata [rdofs + 3], v4v6icmpdata [rdofs + 4], v4v6icmpdata [rdofs + 5], v4v6icmpdata [rdofs + 6], v4v6icmpdata [rdofs + 7]);
855                                 destlladdr = &v4v6icmpdata [rdofs + 2];
856                                 /* continue with next option */
857                         } else
858 #endif
859                         if (v4v6icmpdata [rdofs + 0] != ND_OPT_PREFIX_INFORMATION) {
860                                 /* skip to next option */
861                         } else if (v4v6icmpdata [rdofs + 1] != 4) {
862                                 return;   /* bad length field */
863                         } else if (rdofs + (v4v6icmpdata [rdofs + 1] << 3) > ntohs (v4v6plen) + 4) {
864                                 return;   /* out of packet length */
865                         } else if (v4v6icmpdata [rdofs + 3] & 0xc0 != 0xc0) {
866                                 /* no on-link autoconfig prefix */
867                         } else if (v4v6icmpdata [rdofs + 2] != 64) {
868                                 return;
869                         } else {
870                                 destprefix = &v4v6icmpdata [rdofs + 16];
871                         }
872                         rdofs += (v4v6icmpdata [rdofs + 1] << 3);
873                 }
874                 if (destprefix) {
875                         memcpy (v6listen.s6_addr + 0, destprefix, 8);
876                         memcpy (v6listen.s6_addr + 8, v4dst6->s6_addr + 8, 8);
877                         memcpy (v6listen_linklocal_complete, v4dst6, 16);
878                         v6lladdr [0] = v6listen_linklocal_complete [8] ^ 0x02;
879                         v6lladdr [1] = v6listen_linklocal_complete [9];
880                         v6lladdr [2] = v6listen_linklocal_complete [10];
881                         v6lladdr [3] = v6listen_linklocal_complete [13];
882                         v6lladdr [4] = v6listen_linklocal_complete [14];
883                         v6lladdr [5] = v6listen_linklocal_complete [15];
884                         inet_ntop (AF_INET6,
885                                 &v6listen,
886                                 v6prefix,
887                                 sizeof (v6prefix));
888                         syslog (LOG_INFO, "%s: Assigning address %s to tunnel\n", program, v6prefix);
889                         setup_tunnel_address ();  //TODO// parameters?
890                         got_lladdr = true;
891                         maintenance_time_cycle = maintenance_time_cycle_max;
892                         maintenance_time_sec = time (NULL) + maintenance_time_cycle;
893                 }
894                 return;
895         case ND_NEIGHBOR_SOLICIT:
896                 //
897                 // Validate Neigbour Solicitation (trivial)
898                 //
899                 // Replicate the message over the IPv6 Link (like plain IPv6)
900                 if (v4ngbcmdlen < 24) {
901                         return;         /* too short, drop */
902                 }
903                 syslog (LOG_DEBUG, "%s: Replicating Neighbor Solicatation from 6bed4 to the IPv6 Link\n", program);
904 char buf [INET6_ADDRSTRLEN]; uint8_t ll [6]; if ((memcmp (v4src6, v6listen_linklocal, 8) != 0) && (memcmp (v4src6, &v6listen, 8) != 0)) { inet_ntop (AF_INET6, v4src6, buf, sizeof (buf)); syslog (LOG_DEBUG, "Source IPv6 address %s from wrong origin\n", buf); } else { uint8_t pfaddr [16]; memcpy (pfaddr, v6listen.s6_addr, 8); memcpy (pfaddr + 8, v4src6->s6_addr + 8, 8); inet_ntop (AF_INET6, pfaddr, buf, sizeof (buf)); if (lookup_neighbor (pfaddr, ll)) { syslog (LOG_DEBUG, "Source IPv6 %s has Link-Local Address %02x:%02x:%02x:%02x:%02x:%02x with metric %d\n", buf, ll [0], ll [1], ll [2], ll [3], ll [4], ll [5], lladdr_metric (ll)); } else { syslog (LOG_DEBUG, "Source IPv6 %s is unknown to me\n", buf); } }
905 uint8_t optofs = 4 + 16;
906 #if 0
907 uint8_t *srcll = NULL;  /* TODO -- use 6bed4 Network sender instead! */
908 while ((40 + 4 + optofs + 2 < v4ngbcmdlen) && (40 + 4 + optofs + 8 * v4v6icmpdata [optofs + 1] <= v4ngbcmdlen)) {
909 if (v4v6icmpdata [optofs] == 1) {
910 srcll = v4v6icmpdata + optofs + 2;
911 }
912 optofs += 8 * v4v6icmpdata [optofs + 1];
913 }
914 if (srcll) { syslog (LOG_DEBUG, "ND-contained Source Link-Layer Address %02x:%02x:%02x:%02x:%02x:%02x has metric %d\n", srcll [0], srcll [1], srcll [2], srcll [3], srcll [4], srcll [5], lladdr_metric (srcll)); }
915 #endif
916                 //
917                 // We should attach a Source Link-Layer Address, but
918                 // we cannot automatically trust the one provided remotely.
919                 // Also, we want to detect if routes differ, and handle it.
920                 //
921                 // 0. if no entry in the ngb.cache
922                 //    then use 6bed4 server in ND, initiate ngb.sol to src.ll
923                 //         impl: use 6bed4-server lladdr, set highest metric
924                 // 1. if metric (ngb.cache) < metric (src.ll)
925                 //    then retain ngb.cache, send Redirect to source
926                 // 2. if metric (ngb.cache) > metric (src.ll)
927                 //    then retain ngb.cache, initiate ngb.sol to src.ll
928                 // 3. if metric (ngb.cache) == metric (src.ll)
929                 //    then retain ngb.cache
930                 //
931                 uint8_t src_lladdr [6];
932                 src_lladdr [0] = ntohs (v4name.sin_port) & 0x00ff;
933                 src_lladdr [1] = ntohs (v4name.sin_port) >> 8;
934                 memcpy (src_lladdr + 2, &v4name.sin_addr, 4);
935                 metric_t src_metric = lladdr_metric (src_lladdr);
936                 v4v6icmpdata [4+16+0] = 1;      /* Option: Source LLaddr */
937                 v4v6icmpdata [4+16+1] = 1;      /* Length: 1x 8 bytes */
938                 uint8_t *ngbc_lladdr = v4v6icmpdata + 4+16+2;
939                 uint8_t ngbc_ipv6 [16];
940                 if (memcmp (v4src6, v6listen_linklocal, 8)) {
941                         memcpy (ngbc_ipv6 + 0, &v6listen, 8);
942                         memcpy (ngbc_ipv6 + 8, v4src6 + 8, 8);
943                 } else {
944                         memcpy (ngbc_ipv6, v4src6, 16);
945                 }
946                 bool ngbc_cached = lookup_neighbor (ngbc_ipv6, ngbc_lladdr);
947                 metric_t ngbc_metric;
948                 if (ngbc_cached) {
949                         ngbc_metric = lladdr_metric (ngbc_lladdr);
950                 } else {
951                         ngbc_metric = METRIC_HIGH; /* trigger local ngbsol */
952                         memcpy (ngbc_lladdr, SERVER_6BED4_PORT_IPV4_MACSTR, 6);
953 syslog (LOG_DEBUG, "Failed to find neighbor in cache, initialising it with the high metric\n");
954                 }
955                 syslog (LOG_DEBUG, "Metric analysis: source lladdr %02x:%02x:%02x:%02x:%02x:%02x metric %d, neighbor cache lladdr %02x:%02x:%02x:%02x:%02x:%02x metric %d\n", src_lladdr [0], src_lladdr [1], src_lladdr [2], src_lladdr [3], src_lladdr [4], src_lladdr [5], src_metric, ngbc_lladdr [0], ngbc_lladdr [1], ngbc_lladdr [2], ngbc_lladdr [3], ngbc_lladdr [4], ngbc_lladdr [5], ngbc_metric);
956                 //
957                 // Replicate the ngb.sol with the selected ngbc-lladdr
958                 v4v6icmpcksum = icmp6_checksum ((uint8_t *) v4hdr6, 8 + 16 + 8);
959                 handle_4to6_plain (40 + 24 + 8, &v4name);
960                 //
961                 // If needed, initiate Neigbor Solicitation to the source
962                 // Note: Also when !ngbc_cached as the router is then cached
963                 if (ngbc_metric > src_metric) {
964 syslog (LOG_DEBUG, "Trying to find the more direct route that the remote peer seems to be using\n");
965                         enqueue ((struct in6_addr *) v4src6, &v6listen, v6lladdr);
966                 }
967                 //
968                 // If needed, ask the source to redo Neighbor Solicitation
969                 if (ngbc_metric < src_metric) {
970 syslog (LOG_DEBUG, "Redirecting the remote peer to the more efficient route that I am using\n");
971                         redirect_reply (ngbc_lladdr, ngbc_metric);
972                 }
973                 return;
974         case ND_NEIGHBOR_ADVERT:
975                 //
976                 // Process Neighbor Advertisement coming in over 6bed4
977                 // First, make sure it is against an item in the ndqueue
978                 ndq = findqueue ((struct in6_addr *) v4v6ndtarget);
979                 if (!ndq) {
980                         // Ignore advertisement -- it may be an attack
981                         return;
982                 }
983                 // Remove the matching item from the ndqueue
984                 dequeue (ndq);
985                 // Replicate the Neigbor Advertisement over the IPv6 Link (like plain IPv6)
986                 v4v6icmpdata [0] |= 0xe0;       /* Router, Solicited, Override */
987                 v4v6icmpdata [20] = 2;          /* Target Link-Layer Address */
988                 v4v6icmpdata [21] = 1;          /* Length: 1x 8 bytes */
989                 v4v6icmpdata [22] = ntohs (v4name.sin_port) & 0xff;
990                 v4v6icmpdata [23] = ntohs (v4name.sin_port) >> 8;
991                 memcpy (v4v6icmpdata + 24, &v4name.sin_addr, 4);
992                 v4v6plen = htons (24 + 8);
993                 v4v6icmpcksum = icmp6_checksum ((uint8_t *) v4hdr6, 24 + 8);
994                 handle_4to6_plain (sizeof (struct ip6_hdr) + 24 + 8, &v4name);
995                 return;
996         case ND_REDIRECT:
997                 //
998                 // Redirect indicates that a more efficient bypass exists than
999                 // the currently used route.  The remote peer has established
1000                 // this and wants to share that information to retain a
1001                 // symmetric communication, which is helpful in keeping holes
1002                 // in NAT and firewalls open.
1003                 //
1004                 //TODO// BE EXTREMELY SELECTIVE BEFORE ACCEPTING REDIRECT!!!
1005                 //TODO:NOTYET// enqueue ((struct in6_addr *) v4v6ndtarget, &v6listen, v6lladdr);
1006                 return;
1007         }
1008 }
1009
1010
1011 /* Receive a tunnel package, and route it to either the handler for the
1012  * tunnel protocol, or to the handler that checks and then unpacks the
1013  * contained IPv6.
1014  */
1015 void handle_4to6 (int v4in) {
1016         uint8_t buf [1501];
1017         ssize_t buflen;
1018         socklen_t adrlen = sizeof (v4name);
1019         //
1020         // Receive IPv4 package, which may be tunneled or a tunnel request
1021         buflen = recvfrom (v4in,
1022                         v4data, MTU,
1023                         MSG_DONTWAIT,
1024                         (struct sockaddr *) &v4name, &adrlen
1025                 );
1026         if (buflen == -1) {
1027                 syslog (LOG_INFO, "%s: WARNING: Error receiving IPv4-side package: %s\n",
1028                                 program, strerror (errno));
1029                 return;         /* receiving error, drop */
1030         }
1031         if (buflen <= sizeof (struct ip6_hdr)) {
1032                 return;         /* received too little data, drop */
1033         }
1034         if ((v4data [0] & 0xf0) != 0x60) {
1035                 return;         /* not an IPv6 packet, drop */
1036         }
1037         if (!validate_originator (&v4name, v4src6)) {
1038                 return;         /* source appears fake, drop */
1039         }
1040         /*
1041          * Distinguish types of traffic:
1042          * Non-plain, Plain Unicast, Plain Multicast
1043          */
1044         if ((v4v6nexthdr == IPPROTO_ICMPV6) &&
1045                         (v4v6icmptype >= 133) && (v4v6icmptype <= 137)) {
1046                 //
1047                 // Not Plain: Router Adv/Sol, Neighbor Adv/Sol, Redirect
1048                 if (v4v6hoplimit != 255) {
1049                         return;
1050                 }
1051                 handle_4to6_nd (&v4name, buflen);
1052         } else {
1053                 //
1054                 // Plain Unicast or Plain Multicast (both may enter)
1055                 if (v4v6hoplimit-- <= 1) {
1056                         return;
1057                 }
1058                 handle_4to6_plain (buflen, &v4name);
1059         }
1060 }
1061
1062
1063 /*
1064  * Relay an IPv6 package to 6bed4, using the link-local address as it
1065  * is found in the Ethernet header.  Trust the local IPv6 stack to have
1066  * properly obtained this destination address through Neighbor Discovery
1067  * over 6bed4.
1068  */
1069 void handle_6to4_plain_unicast (const ssize_t pktlen, const uint8_t *lladdr) {
1070         struct sockaddr_in v4dest;
1071         memset (&v4dest, 0, sizeof (v4dest));
1072         v4dest.sin_family = AF_INET;
1073         v4dest.sin_port = htons (lladdr [0] | (lladdr [1] << 8));
1074         memcpy (&v4dest.sin_addr, lladdr + 2, 4);
1075         if (v6tc != (v6hdr6->ip6_vfc & htonl (0x0ff00000))) {
1076                 v6tc = v6hdr6->ip6_vfc & htonl (0x0ff00000);
1077                 v4qos = (ntohl (v6hdr6->ip6_vfc) & 0x0ff00000) >> 24;
1078                 if (setsockopt (v4sox, IPPROTO_IP, IP_TOS, &v4qos, sizeof (v4qos)) == -1) {
1079                         syslog (LOG_ERR, "Failed to switch IPv4 socket to QoS setting 0x%02x\n", v4qos);
1080                 }
1081         }
1082         syslog (LOG_DEBUG, "%s: Sending IPv6-UDP-IPv4 to %d.%d.%d.%d:%d, result = %zd\n", program,
1083         ((uint8_t *) &v4dest.sin_addr.s_addr) [0],
1084         ((uint8_t *) &v4dest.sin_addr.s_addr) [1],
1085         ((uint8_t *) &v4dest.sin_addr.s_addr) [2],
1086         ((uint8_t *) &v4dest.sin_addr.s_addr) [3],
1087         ntohs (v4dest.sin_port),
1088                 sendto (v4sox,
1089                                 v6data,
1090                                 pktlen - sizeof (struct ethhdr),
1091                                 MSG_DONTWAIT,
1092                                 (struct sockaddr *) &v4dest,
1093                                 sizeof (struct sockaddr_in))
1094         )
1095                                 ;
1096 }
1097
1098
1099 /*
1100  * Handle a request for Neighbor Discovery over the 6bed4 Link.
1101  */
1102 void handle_6to4_nd (ssize_t pktlen) {
1103         uint8_t lldest [6];
1104         //
1105         // Validate ICMPv6 message -- trivial, trust local generation
1106         //
1107         // Handle the message dependent on its type
1108         switch (v6icmp6type) {
1109         case ND_ROUTER_SOLICIT:
1110                 v6icmp6type = ND_ROUTER_ADVERT;
1111                 v6icmp6code = 0;
1112                 v6icmp6data [0] = 0;            // Cur Hop Limit: unspec
1113                 v6icmp6data [1] = 0x18;         // M=0, O=0,
1114                                                 // H=0, Prf=11=Low
1115                                                 // Reserved=0
1116                 //TODO: wire says 0x44 for router_adv.flags
1117                 size_t writepos = 2;
1118                 memset (v6icmp6data + writepos,
1119                                 default_route? 0xff: 0x00,
1120                                 2);             // Router Lifetime
1121                 writepos += 2;
1122                 memcpy (v6icmp6data + writepos,
1123                                 "\x00\x00\x80\x00",
1124                                 4);             // Reachable Time: 32s
1125                 writepos += 4;
1126                 memcpy (v6icmp6data + writepos,
1127                                 "\x00\x00\x01\x00",
1128                                 4);             // Retrans Timer: .25s
1129                 writepos += 4;
1130                 writepos = icmp6_prefix (writepos, 0);
1131                 v6plen = htons (4 + writepos);
1132                 memcpy (v6dst6, v6src6, 16);
1133                 memcpy (v6src6, v6listen_linklocal_complete, 16);
1134                 v6icmp6csum = icmp6_checksum ((uint8_t *) v6hdr6, 4 + writepos);
1135                 v6ether.h_proto = htons (ETH_P_IPV6);
1136                 memcpy (v6ether.h_dest, v6ether.h_source, 6);
1137                 memcpy (v6ether.h_source, v6lladdr, 6);
1138                 syslog (LOG_INFO, "Replying Router Advertisement to the IPv6 Link, result = %zd\n",
1139                         write (v6sox, &v6data6, sizeof (struct ethhdr) + sizeof (struct ip6_hdr) + 4 + writepos)
1140                 )
1141                         ;
1142                 break;
1143         case ND_ROUTER_ADVERT:
1144                 return;         /* the IPv6 Link is no router, drop */
1145         case ND_NEIGHBOR_SOLICIT:
1146                 //
1147                 // Neighbor Solicitation is treated depending on its kind:
1148                 //  - the 6bed4 Router address is answered immediately
1149                 //  - discovery for the local IPv6 address is dropped
1150                 //  - discovery for fe80::/64 addresses is answered
1151                 //  - other peers start a process in the ndqueue
1152                 if ((memcmp (v6ndtarget, router_linklocal_address, 16) == 0) ||
1153                     (memcmp (v6ndtarget, router_linklocal_address_complete, 16) == 0)) {
1154                         advertise_6bed4_public_service (NULL);
1155                 } else if (memcmp (v6ndtarget, &v6listen, 16) == 0) {
1156                         return;         /* yes you are unique, drop */
1157                 } else if (memcmp (v6ndtarget, v6listen_linklocal, 8) == 0) {
1158                         //
1159                         // Construct response for fe80::/64
1160                         v6icmp6type = ND_NEIGHBOR_ADVERT;
1161                         v6icmp6data [0] = 0x60; /* Solicited, Override */
1162                         v6icmp6data [20] = 2;   /* Target Link-Layer Address */
1163                         v6icmp6data [21] = 1;   /* Length is 1x 8 bytes */
1164                         v6icmp6data [22] = v6icmp6data [12] ^ 0x02;
1165                         v6icmp6data [23] = v6icmp6data [13];
1166                         v6icmp6data [24] = v6icmp6data [14];
1167                         v6icmp6data [25] = v6icmp6data [17];
1168                         v6icmp6data [26] = v6icmp6data [18];
1169                         v6icmp6data [27] = v6icmp6data [19];
1170                         v6plen = htons (4 + 28);
1171                         memcpy (v6dst6, v6src6, 16);
1172                         memcpy (v6src6, &v6listen, 16);
1173                         memcpy (v6ether.h_dest, v6ether.h_source, 6);
1174                         memcpy (v6ether.h_source, v6lladdr, 6);
1175                         v6icmp6csum = icmp6_checksum ((uint8_t *) v6hdr6, 4 + 28);
1176 syslog (LOG_DEBUG, "Sending trivial reply to fe80::/64 type query\n");
1177                         write (v6sox, &v6data6, sizeof (struct ethhdr) + sizeof (struct ip6_hdr) + 4 + 28);
1178                         return;
1179                 } else {
1180                         enqueue ((struct in6_addr *) v6ndtarget, (struct in6_addr *) v6src6, v6ether.h_source);
1181                 }
1182                 break;
1183         case ND_NEIGHBOR_ADVERT:
1184                 lldest [0] = v6dst6->s6_addr [8] ^ 0x02;
1185                 lldest [1] = v6dst6->s6_addr [9];
1186                 lldest [2] = v6dst6->s6_addr [10];
1187                 lldest [3] = v6dst6->s6_addr [13];
1188                 lldest [4] = v6dst6->s6_addr [14];
1189                 lldest [5] = v6dst6->s6_addr [15];
1190                 handle_6to4_plain_unicast (pktlen, lldest);
1191                 break;
1192         case ND_REDIRECT:
1193                 //TODO:NOT_IMPLEMENTED_YET:ND_REDIRECT_FROM_6BED4//
1194                 //
1195                 // Redirect indicates that a more efficient bypass exists than
1196                 // the currently used route.  The remote peer has established
1197                 // this and wants to share that information to retain a
1198                 // symmetric communication, which is helpful in keeping holes
1199                 // in NAT and firewalls open.
1200                 //
1201                 return;
1202         }
1203 }
1204
1205
1206 /*
1207  * Receive an IPv6 package, check its address and pickup IPv4 address and
1208  * port, then package it as a tunnel message and forward it to IPv4:port.
1209  * Rely on the proper formatting of the incoming IPv6 packet, as it is
1210  * locally generated.
1211  */
1212 void handle_6to4 (void) {
1213         //
1214         // Receive the IPv6 package and ensure a consistent size
1215         size_t rawlen = read (v6sox, &v6data6, sizeof (v6data6));
1216         if (rawlen == -1) {
1217                 return;         /* failure to read, drop */
1218         }
1219         if (rawlen < sizeof (struct ethhdr) + sizeof (struct ip6_hdr) + 1) {
1220                 return;         /* packet too small, drop */
1221         }
1222         if (v6ether.h_proto != htons (ETH_P_IPV6)) {
1223                 return;         /* not IPv6, drop */
1224         }
1225 //TODO// syslog (LOG_DEBUG, "Packet from IPv6 stack, target %02x:%02x:%02x:%02x:%02x:%02x\n", v6ether.h_dest [0], v6ether.h_dest [1], v6ether.h_dest [2], v6ether.h_dest [3], v6ether.h_dest [4], v6ether.h_dest [5]);
1226         //
1227         // Ignore messages from the IPv6 stack to itself
1228         if (memcmp (v6ether.h_dest, v6ether.h_source, 6) == 0) {
1229                 syslog (LOG_DEBUG, "TODO: Self-to-self messaging in IPv6 stack ignored\n");
1230                 return;
1231         }
1232         /*
1233          * Distinguish types of traffic:
1234          * Non-plain, Plain Unicast, Plain Multicast
1235          */
1236         if ((v6type == IPPROTO_ICMPV6) &&
1237                         (v6icmp6type >= 133) && (v6icmp6type <= 137)) {
1238                 //
1239                 // Not Plain: Router Adv/Sol, Neighbor Adv/Sol, Redirect
1240 syslog (LOG_DEBUG, "Forwarding non-plain unicast from IPv6 to 6bed4\n");
1241                 handle_6to4_nd (rawlen);
1242         } else if ((v6dst6->s6_addr [0] != 0xff) && !(v6dst6->s6_addr [8] & 0x01)) {
1243                 //
1244                 // Plain Unicast
1245                 if (v6hops-- <= 1) {
1246                         return;
1247                 }
1248 syslog (LOG_DEBUG, "Forwarding plain unicast from IPv6 to 6bed4\n");
1249                 handle_6to4_plain_unicast (rawlen, v6ether.h_dest);
1250         } else {
1251                 //
1252                 // Plain Multicast
1253                 //TODO:IGNORE_MULTICAST//
1254                 //TODO// syslog (LOG_DEBUG, "%s: Plain multicast from 6bed4 Link to 6bed4 Network is not supported\n", program);
1255         }
1256 }
1257
1258
1259 /*
1260  * Send a single Neighbor Solicitation message over 6bed4.  This will
1261  * be sent to the given 6bed4 address, and is usually part of a series
1262  * of attempts to find a short-cut route to the 6bed4 peer.
1263  */
1264 void solicit_6bed4_neighbor (const struct ndqueue *info, const uint8_t *addr6bed4) {
1265         memcpy (v6src6, &info->source, 16);
1266         memcpy (v6dst6, &info->target, 16);
1267         v6type = IPPROTO_ICMPV6;
1268         v6hops = 255;
1269         v6icmp6type = ND_NEIGHBOR_SOLICIT;
1270         v6icmp6code = 0;
1271         v6icmp6data [0] =
1272         v6icmp6data [1] =
1273         v6icmp6data [2] =
1274         v6icmp6data [3] = 0x00;
1275         memcpy (v6icmp6data + 4, &info->target, 16);
1276         v6icmp6data [20] = 1;   // option type is Source Link-Layer Address
1277         v6icmp6data [21] = 1;   // option length is 1x 8 bytes
1278         memcpy (v6icmp6data + 22, v6lladdr, 6);
1279         uint16_t pktlen = sizeof (struct ip6_hdr) + 4 + 28;
1280         //OLD// v6icmp6csum = icmp6_checksum ((uint8_t *) v6hdr6, 28 + 8);
1281         v6plen = htons (4 + 28);
1282         v6icmp6csum = icmp6_checksum ((uint8_t *) v6hdr6, 4 + 28);
1283         handle_6to4_plain_unicast (sizeof (struct ip6_hdr) + 8 + 28 + 10, addr6bed4);
1284         //TODO// Why these +8 and +10 are needed, I don't know yet!
1285 }
1286
1287
1288 /*
1289  * Find a neighbor's 6bed4 address.  This is coordinated by the ndqueue,
1290  * which schedules such tasks and makes them repeat.  Furthermore, a few
1291  * attempts may be scheduled on the local network before attempts
1292  * shift to the direct target IPv4/UDP addresses.  Of course the local
1293  * network will only be scheduled if the public IPv4 address matches
1294  * the one for the local node.
1295  *
1296  * This process is dequeued by reverse Neighbor Advertisements.  If none
1297  * comes back in spite of the various Neighbor Solicitations sent, then
1298  * the final action is to send a Neighbor Advertisement to the host with
1299  * the Public 6bed4 Service as its target of last resort.  In case of
1300  * this last resort, the process is not continued any further; the
1301  * return value indicates whether the queue entry should be kept for
1302  * another round.
1303  */
1304 bool chase_neighbor_6bed4_address (struct ndqueue *info) {
1305         uint8_t addr6bed4 [6];
1306         static const uint8_t addr6bed4_lancast [8] = {
1307                 UDP_PORT_6BED4 & 0xff, UDP_PORT_6BED4 >> 8,
1308                 224, 0, 0, 1
1309         };
1310         if (info->todo_lancast > 0) {
1311                 // Attempt 1. Send to LAN multicast address (same public IP)
1312                 info->todo_lancast--;
1313                 solicit_6bed4_neighbor (info, addr6bed4_lancast);
1314                 return true;
1315         } else if (info->todo_direct > 0) {
1316                 // Attempt 2. Send to target's direct IP address / UDP port
1317                 info->todo_direct--;
1318                 addr6bed4 [0] = info->target.s6_addr [8] ^ 0x02;
1319                 addr6bed4 [1] = info->target.s6_addr [9];
1320                 addr6bed4 [2] = info->target.s6_addr [10];
1321                 addr6bed4 [3] = info->target.s6_addr [13];
1322                 addr6bed4 [4] = info->target.s6_addr [14];
1323                 addr6bed4 [5] = info->target.s6_addr [15];
1324                 solicit_6bed4_neighbor (info, addr6bed4);
1325                 return true;
1326         } else {
1327                 // Attempt 3. Respond with Public 6bed4 Service
1328                 syslog (LOG_INFO, "%s: Failed to find a bypass, passing back the 6bed4 Router\n", program);
1329                 advertise_6bed4_public_service (info);
1330                 return false;
1331         }
1332 }
1333
1334
1335 /*
1336  * Perform Router Solicitation.  This is the usual mechanism that is used
1337  * on ethernet links as well, except that the 6bed4 permits fixed interface
1338  * identifiers; for this client, the interface identifier will be 0x0001.
1339  * The router always has interface identifier 0x0000 but it will now be
1340  * addressed at the all-routers IPv6 address 0xff02::2 with the general
1341  * source IPv6 address ::
1342  */
1343 void solicit_router (void) {
1344         v4name.sin_family = AF_INET;
1345         memcpy (&v4name.sin_addr.s_addr, &v4listen, 4);
1346         v4name.sin_port = htons (UDP_PORT_6BED4);
1347         int done = 0;
1348         int secs = 1;
1349 // syslog (LOG_DEBUG, "%s: Sending RouterSolicitation-IPv6-UDP-IPv4 to %d.%d.%d.%d:%d, result = %d\n", program,
1350 // ((uint8_t *) &v4name.sin_addr.s_addr) [0],
1351 // ((uint8_t *) &v4name.sin_addr.s_addr) [1],
1352 // ((uint8_t *) &v4name.sin_addr.s_addr) [2],
1353 // ((uint8_t *) &v4name.sin_addr.s_addr) [3],
1354 // ntohs (v4name.sin_port),
1355 (
1356         sendto (v4sox,
1357                         ipv6_router_solicitation,
1358                         sizeof (ipv6_router_solicitation),
1359                         MSG_DONTWAIT,
1360                         (struct sockaddr *) &v4name, sizeof (v4name)));
1361 }
1362
1363
1364 /*
1365  * Send a KeepAlive message.  This is an UDP/IPv4 message with no contents.
1366  * The router will not respond, but that is okay; outgoing traffic is the
1367  * way to keep holes in NAT and firewalls open.
1368  */
1369 void keepalive (void) {
1370         v4name.sin_family = AF_INET;
1371         memcpy (&v4name.sin_addr.s_addr, &v4listen, 4);
1372         v4name.sin_port = htons (UDP_PORT_6BED4);
1373         int done = 0;
1374         int secs = 1;
1375         setsockopt (v4sox, IPPROTO_IP, IP_TTL, &keepalive_ttl, sizeof (keepalive_ttl));
1376         sendto (v4sox,
1377                         "",
1378                         0,
1379                         MSG_DONTWAIT,
1380                         (struct sockaddr *) &v4name, sizeof (v4name));
1381         setsockopt (v4sox, IPPROTO_IP, IP_TTL, &v4ttl, sizeof (v4ttl));
1382 }
1383
1384
1385 /* Regular maintenance is a routine that runs regularly to do one of two
1386  * generic tasks: either it sends Router Solicitation messages to the
1387  * Public 6bed4 Service, or it sends an empty UDP message somewhat in its
1388  * direction to keep NAT/firewall holes open.
1389  */
1390 void regular_maintenance (void) {
1391         if (!got_lladdr) {
1392                 solicit_router ();
1393                 maintenance_time_cycle <<= 1;
1394                 maintenance_time_cycle += 1;
1395                 if (maintenance_time_cycle > maintenance_time_cycle_max) {
1396                         maintenance_time_cycle = maintenance_time_cycle_max;
1397                 }
1398                 syslog (LOG_INFO, "Sent Router Advertisement to Public 6bed4 Service, next attempt in %ld seconds\n", maintenance_time_cycle);
1399         } else {
1400                 syslog (LOG_INFO, "Sending a KeepAlive message (empty UDP) to the 6bed4 Router\n");
1401                 keepalive ();
1402                 maintenance_time_cycle = maintenance_time_cycle_max;
1403         }
1404         maintenance_time_sec = time (NULL) + maintenance_time_cycle;
1405 }
1406
1407
1408 /* Run the daemon core code, passing information between IPv4 and IPv6 and
1409  * responding to tunnel requests if so requested.
1410  */
1411 void run_daemon (void) {
1412         fd_set io;
1413         bool keep;
1414         maintenance_time_sec = 0;       // trigger Router Solicitation
1415         FD_ZERO (&io);
1416         FD_SET (v4sox, &io);
1417         FD_SET (v6sox, &io);
1418         int nfds = (v4sox < v6sox)? (v6sox + 1): (v4sox + 1);
1419         if (v4mcast != -1) {
1420                 FD_SET (v4mcast, &io);
1421                 if (v4mcast >= nfds) {
1422                         nfds = v4mcast + 1;
1423                 }
1424         }
1425         while (1) {
1426                 struct timeval tout;
1427                 struct timeval now;
1428                 gettimeofday (&now, NULL);
1429                 if (maintenance_time_sec <= now.tv_sec) {
1430                         regular_maintenance ();
1431                 }
1432                 tout.tv_sec = maintenance_time_sec - now.tv_sec;
1433                 tout.tv_usec = 0;
1434                 while (ndqueue && (
1435                                 ((ndqueue->next->tv.tv_sec == now.tv_sec)
1436                                   && (ndqueue->next->tv.tv_usec <= now.tv_usec))
1437                                 || (ndqueue->next->tv.tv_sec < now.tv_sec))) {
1438                         //
1439                         // Run the entry's handler code
1440                         syslog (LOG_DEBUG, "Queue at %ld.%03ld: Timed for %ld.%03ld", now.tv_sec, now.tv_usec / 1000, ndqueue->next->tv.tv_sec, ndqueue->next->tv.tv_usec / 1000);
1441                         keep = chase_neighbor_6bed4_address (ndqueue->next);
1442                         if (!keep) {
1443                                 dequeue (ndqueue->next);
1444                                 continue;
1445                         }
1446                         //
1447                         // Make ndqueue point to the entry to run
1448                         ndqueue = ndqueue->next;
1449                         //
1450                         // Add 50ms to the running time
1451                         if (now.tv_usec < 950000) {
1452                                 ndqueue->tv.tv_usec = now.tv_usec +   50000;
1453                                 ndqueue->tv.tv_sec  = now.tv_sec  + 0;
1454                         } else {
1455                                 ndqueue->tv.tv_usec = now.tv_usec -  950000;
1456                                 ndqueue->tv.tv_sec  = now.tv_sec  + 1;
1457                         }
1458                 }
1459                 if (ndqueue && ((ndqueue->next->tv.tv_sec - now.tv_sec) < tout.tv_sec)) {
1460                         tout.tv_sec  = ndqueue->next->tv.tv_sec  - now.tv_sec ;
1461                         tout.tv_usec = ndqueue->next->tv.tv_usec - now.tv_usec;
1462                         if (tout.tv_usec < 0) {
1463                                 tout.tv_usec += 1000000;
1464                                 tout.tv_sec  -= 1;
1465                         }
1466                 }
1467                 if (select (nfds, &io, NULL, NULL, &tout) == -1) {
1468                         syslog (LOG_ERR, "Select failed: %s\n", strerror (errno));
1469                 }
1470                 if (FD_ISSET (v4sox, &io)) {
1471 syslog (LOG_DEBUG, "Got unicast input\n");
1472                         handle_4to6 (v4sox);
1473                 } else {
1474                         FD_SET (v4sox, &io);
1475                 }
1476                 if (FD_ISSET (v6sox, &io)) {
1477                         handle_6to4 ();
1478                 } else {
1479                         FD_SET (v6sox, &io);
1480                 }
1481                 if (v4mcast != -1) {
1482                         if (FD_ISSET (v4mcast, &io)) {
1483 syslog (LOG_DEBUG, "WOW: Got multicast input\n");
1484                                 handle_4to6 (v4mcast);
1485                         } else {
1486                                 FD_SET (v4mcast, &io);
1487                         }
1488                 }
1489 //fflush (stdout);
1490         }
1491 }
1492
1493
1494 /* Option descriptive data structures */
1495
1496 char *short_opt = "s:t:dl:p:r:k:feh";
1497
1498 struct option long_opt [] = {
1499         { "v4server", 1, NULL, 's' },
1500         { "tundev", 1, NULL, 't' },
1501         { "default-route", 0, NULL, 'd' },
1502         { "listen", 1, NULL, 'l' },
1503         { "port", 1, NULL, 'p' },
1504         { "radius-multicast", 1, NULL, 'r' },
1505         { "foreground", 0, NULL, 'f' },
1506         { "fork-not", 0, NULL, 'f' },
1507         { "keepalive", 1, NULL, 'k' },
1508         { "keepalive-period-ttl", 1, NULL, 'k' },
1509         { "error-console", 0, NULL, 'e' },
1510         { "help", 0, NULL, 'h' },
1511         { NULL, 0, NULL, 0 }    /* Array termination */
1512 };
1513
1514
1515 /* Parse commandline arguments (and start to process them).
1516  * Return 1 on success, 0 on failure.
1517  */
1518 int process_args (int argc, char *argv []) {
1519         int ok = 1;
1520         int help = 0;
1521         int done = 0;
1522         unsigned long tmpport;
1523         char *endarg;
1524         default_route = false;
1525         while (!done) {
1526                 switch (getopt_long (argc, argv, short_opt, long_opt, NULL)) {
1527                 case -1:
1528                         done = 1;
1529                         if (optind != argc) {
1530                                 fprintf (stderr, "%s: Extra arguments not permitted: %s...\n", program, argv [optind]);
1531                                 ok = 0;
1532                         }
1533                         break;
1534                 case 's':
1535                         if (v4sox != -1) {
1536                                 ok = 0;
1537                                 fprintf (stderr, "%s: You can only specify a single server address\n", program);
1538                                 continue;
1539                         }
1540                         v4server = optarg;
1541                         if (inet_pton (AF_INET, optarg, &v4peer.sin_addr) <= 0) {
1542                                 ok = 0;
1543                                 fprintf (stderr, "%s: Failed to parse IPv4 address %s\n", program, optarg);
1544                                 break;
1545                         }
1546                         memcpy (&v4listen, &v4peer.sin_addr, 4);
1547                         v4sox = socket (AF_INET, SOCK_DGRAM, 0);
1548                         if (v4sox == -1) {
1549                                 ok = 0;
1550                                 fprintf (stderr, "%s: Failed to allocate UDPv4 socket: %s\n", program, strerror (errno));
1551                                 break;
1552                         }
1553                         break;
1554                 case 't':
1555                         if (v6sox != -1) {
1556                                 ok = 0;
1557                                 fprintf (stderr, "%s: Multiple -t arguments are not permitted\n", program);
1558                                 break;
1559                         }
1560                         v6sox = open (optarg, O_RDWR);
1561                         if (v6sox == -1) {
1562                                 ok = 0;
1563                                 fprintf (stderr, "%s: Failed to open tunnel device %s: %s\n", program, optarg, strerror (errno));
1564                                 break;
1565                         }
1566                         break;
1567                 case 'd':
1568                         if (default_route) {
1569                                 fprintf (stderr, "%s: You can only request default route setup once\n", program);
1570                                 exit (1);
1571                         }
1572                         default_route = true;
1573                         break;
1574                 case 'l':
1575                         if (inet_pton (AF_INET, optarg, &v4bind.sin_addr.s_addr) != 1) {
1576                                 fprintf (stderr, "%s: IPv4 address %s is not valid\n", program, optarg);
1577                                 exit (1);
1578                         }
1579                         break;
1580                 case 'p':
1581                         tmpport = strtoul (optarg, &endarg, 10);
1582                         if ((*endarg) || (tmpport > 65535)) {
1583                                 fprintf (stderr, "%s: UDP port number %s is not valid\n", program, optarg);
1584                                 exit (1);
1585                         }
1586                         if (tmpport & 0x0001) {
1587                                 fprintf (stderr, "%s: UDP port number %ld is odd, which is not permitted\n", program, tmpport);
1588                                 exit (1);
1589                         }
1590                         v4bind.sin_port = htons (tmpport);
1591                         break;
1592                 case 'f':
1593                         if (foreground) {
1594                                 fprintf (stderr, "%s: You can only request foreground operation once\n", program);
1595                                 exit (1);
1596                         }
1597                         foreground = true;
1598                         break;
1599                 case 'e':
1600                         if (log_to_stderr) {
1601                                 fprintf (stderr, "%s: You can only specify logging to stderr once\n", program);
1602                                 exit (1);
1603                         }
1604                         log_to_stderr = true;
1605                         break;
1606                 case 'r':
1607                         if (v4ttl_mcast != -1) {
1608                                 fprintf (stderr, "%s: You can set the radius for multicast once\n", program);
1609                                 exit (1);
1610                         }
1611                         char *zero;
1612                         long setting = strtol(optarg, &zero, 10);
1613                         if (*zero || (setting < 0) || (setting > 255)) {
1614                                 fprintf (stderr, "%s: Multicast radius must be a number in the range 0 to 255, inclusive, not %s\n", program, optarg);
1615                                 exit (1);
1616                         }
1617                         v4ttl_mcast = setting;
1618                         break;
1619                 case 'k':
1620                         if (keepalive_ttl != -1) {
1621                                 fprintf (stderr, "%s: You can only set the keepalive period and TTL once\n", program);
1622                                 exit (1);
1623                         }
1624                         char *rest;
1625                         keepalive_period = strtol (optarg, &rest, 10);
1626                         if (*rest == ',') {
1627                                 rest++;
1628                                 keepalive_ttl = strtol (rest, &rest, 10);
1629                                 if ((keepalive_ttl < 0) || (keepalive_ttl > 255)) {
1630                                         fprintf (stderr, "%s: The keepalive TTL must be in the range 0 to 255, inclusive\n", program);
1631                                         exit (1);
1632                                 }
1633                         } else {
1634                                 keepalive_ttl = 3;
1635                         }
1636                         if (*rest) {
1637                                 fprintf (stderr, "%s: The format for keepalive configuration is 'period,ttl' or just 'period', but not %s\n", program, optarg);
1638                                 exit (1);
1639                         }
1640                         break;
1641                 default:
1642                         ok = 0;
1643                         help = 1;
1644                         /* continue into 'h' to produce usage information */
1645                 case 'h':
1646                         help = 1;
1647                         break;
1648                 }
1649                 if (help || !ok) {
1650                         done = 1;
1651                 }
1652         }
1653         if (help) {
1654 #ifdef HAVE_SETUP_TUNNEL
1655                 fprintf (stderr, "Usage: %s [-d] [-t /dev/tunX]\n       %s -h\n", program, program);
1656 #else
1657                 fprintf (stderr, "Usage: %s [-d] -t /dev/tunX\n       %s -h\n", program, program);
1658 #endif
1659                 return 0;
1660         }
1661         if (!ok) {
1662                 return 0;
1663         }
1664         if (keepalive_ttl != -1) {
1665                 maintenance_time_cycle_max = keepalive_period;
1666         } else {
1667                 keepalive_ttl = 3;
1668         }
1669 #ifdef HAVE_SETUP_TUNNEL
1670         if (v6sox == -1) {
1671                 if (geteuid () != 0) {
1672                         fprintf (stderr, "%s: You should be root, or use -t to specify an accessible tunnel device\n", program);
1673                         return false;
1674                 } else {
1675                         return setup_tunnel ();
1676                 }
1677         }
1678 #else /* ! HAVE_SETUP_TUNNEL */
1679         if (v6sox == -1) {
1680                 fprintf (stderr, "%s: You must specify a tunnel device with -t that is accessible to you\n", program);
1681                 return 0;
1682         }
1683 #endif /* HAVE_SETUP_TUNNEL */
1684         return ok;
1685 }
1686
1687
1688 /* The main program parses commandline arguments and forks off the daemon
1689  */
1690 int main (int argc, char *argv []) {
1691         //
1692         // Initialise
1693         program = strrchr (argv [0], '/');
1694         if (program) {
1695                 program++;
1696         } else {
1697                 program = argv [0];
1698         }
1699         memset (&v4name, 0, sizeof (v4name));
1700         memset (&v4peer, 0, sizeof (v4peer));
1701         memset (&v6name, 0, sizeof (v6name));
1702         v4name.sin_family  = AF_INET ;
1703         v4peer.sin_family  = AF_INET ;
1704         v6name.sin6_family = AF_INET6;
1705         // Fixed public server data, IPv4 and UDP:
1706         v4server = SERVER_6BED4_IPV4_TXT;
1707         v4peer.sin_addr.s_addr = htonl (SERVER_6BED4_IPV4_INT32);
1708         v4name.sin_port = htons (UDP_PORT_6BED4);
1709         v4peer.sin_port = htons (UDP_PORT_6BED4);
1710         memcpy (&v4listen, &v4peer.sin_addr, 4);
1711         memset (&v4bind, 0, sizeof (v4bind));
1712         v4bind.sin_family = AF_INET;
1713         //
1714         // Parse commandline arguments
1715         if (!process_args (argc, argv)) {
1716                 exit (1);
1717         }
1718         //
1719         // Construct the 6bed4 Router's complete link-layer address
1720         router_linklocal_address_complete [8] = (ntohs (v4peer.sin_port) & 0xff) ^ 0x02;
1721         router_linklocal_address_complete [9] = ntohs (v4peer.sin_port) >> 8;
1722         router_linklocal_address_complete [10] = ntohl (v4peer.sin_addr.s_addr) >> 24;
1723         router_linklocal_address_complete [11] = 0xff;
1724         router_linklocal_address_complete [12] = 0xfe;
1725         memcpy (router_linklocal_address_complete + 13, &((uint8_t *) &v4peer.sin_addr) [1], 3);
1726         //
1727         // Open the syslog channel
1728         openlog (program, LOG_NDELAY | LOG_PID | ( log_to_stderr? LOG_PERROR: 0), LOG_DAEMON);
1729         //
1730         // Create memory for the freequeue buffer
1731         freequeue = calloc (freequeue_items, sizeof (struct ndqueue));
1732         if (!freequeue) {
1733                 syslog (LOG_CRIT, "%s: Failed to allocate %d queue items\n", program, freequeue_items);
1734                 exit (1);
1735         }
1736         int i;
1737         for (i = 1; i < freequeue_items; i++) {
1738                 freequeue [i].next = &freequeue [i-1];
1739         }
1740         freequeue = &freequeue [freequeue_items - 1];
1741         //
1742         // Create socket for normal outgoing (and return) 6bed4 traffic
1743         if (v4sox == -1) {
1744                 v4sox = socket (AF_INET, SOCK_DGRAM, 0);
1745                 if (v4sox == -1) {
1746                         syslog (LOG_CRIT, "%s: Failed to open a local IPv4 socket -- does your system still support IPv4?\n", program);
1747                         exit (1);
1748                 }
1749         }
1750         struct sockaddr_in tmpaddr;
1751         memset (&tmpaddr, 0, sizeof (tmpaddr));
1752         tmpaddr.sin_family = AF_INET;
1753         srand (getpid ());
1754         uint16_t portn = rand () & 0x3ffe;
1755         uint16_t port0 = portn + 16384;
1756         //TODO// Move port iteration + allocation to separate function
1757         while (portn < port0) {
1758                 tmpaddr.sin_port = htons ((portn & 0x3ffe) + 49152);
1759                 if (bind (v4sox, (struct sockaddr *) &tmpaddr, sizeof (tmpaddr)) == 0) {
1760                         break;
1761                 }
1762                 portn += 2;
1763         }
1764         if (portn < port0) {
1765                 syslog (LOG_DEBUG, "Bound to UDP port %d\n", ntohs (tmpaddr.sin_port));
1766         } else {
1767                 fprintf (stderr, "%s: All even dynamic ports rejected binding: %s\n", program, strerror (errno));
1768                 exit (1);
1769         }
1770         //
1771         // Setup fragmentation, QoS and TTL options
1772         u_int yes = 1;
1773         u_int no = 0;
1774 #ifdef IP_DONTFRAG
1775         if (setsockopt (v4sox, IPPROTO_IP, IP_DONTFRAG, no, sizeof (no)) == -1) {
1776                 syslog (LOG_ERR, "Failed to permit fragmentation -- not all peers may be accessible with MTU 1280");
1777         }
1778 #else
1779 #warning "Target system lacks support for controlling packet fragmentation"
1780 #endif
1781         socklen_t soxlen = sizeof (v4qos);
1782         if (getsockopt (v4sox, IPPROTO_IP, IP_TOS, &v4qos, &soxlen) == -1) {
1783                 syslog (LOG_ERR, "Quality of Service is not supported by the IPv4-side socket");
1784                 v4qos = 0;
1785         }
1786         v6tc = htonl (v4qos << 20);
1787         soxlen = sizeof (v4ttl);
1788         if (getsockopt (v4sox, IPPROTO_IP, IP_TTL, &v4ttl, &soxlen) == -1) {
1789                 syslog (LOG_ERR, "Time To Live cannot be varied on the IPv4 socket");
1790                 v4ttl = 64;
1791         }
1792         //
1793         // Bind to the IPv4 all-nodes local multicast address
1794         memset (&v4allnodes, 0, sizeof (v4allnodes));
1795         v4allnodes.sin_family = AF_INET;
1796         v4allnodes.sin_port = htons (UDP_PORT_6BED4);
1797         v4allnodes.sin_addr.s_addr = htonl ( INADDR_ANY );
1798         if (multicast) {
1799                 v4mcast = socket (AF_INET, SOCK_DGRAM, 0);
1800                 if (v4mcast != -1) {
1801                         struct ip_mreq mreq;
1802                         mreq.imr_multiaddr.s_addr = htonl ( (224L << 24) | 1L);
1803                         mreq.imr_multiaddr.s_addr = htonl ( INADDR_ANY );
1804                         if (bind (v4mcast, (struct sockaddr *) &v4allnodes, sizeof (v4allnodes)) != 0) {
1805                                 close (v4mcast);
1806                                 v4mcast = -1;
1807                                 syslog (LOG_ERR, "No LAN bypass: Failed to bind to IPv4 all-nodes: %s\n", strerror (errno));
1808                         } else if (setsockopt (v4mcast, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof (yes)) == -1) {
1809                                 close (v4mcast);
1810                                 v4mcast = -1;
1811                                 syslog (LOG_ERR, "No LAN bypass: Failed to share multicast port: %s\n", strerror (errno));
1812                         } else if (setsockopt (v4mcast, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof (mreq)) == -1) {
1813                                 close (v4mcast);
1814                                 v4mcast = -1;
1815                                 syslog (LOG_ERR, "No LAN bypass: Failed to setup multicast: %s\n", strerror (errno));
1816                         } else if ((v4ttl_mcast != -1) && (setsockopt (v4mcast, IPPROTO_IP, IP_MULTICAST_TTL, &v4ttl_mcast, sizeof (v4ttl_mcast)) == -1)) {
1817                                 close (v4mcast);
1818                                 v4mcast = -1;
1819                                 syslog (LOG_ERR, "No LAN bypass: Failed to configure the multicast radius: %s\n", strerror (errno));
1820                         }
1821 #if 0
1822                         if (bind (v4mcast, (struct sockaddr *) &v4allnodes, sizeof (v4allnodes)) != 0) {
1823                                 close (v4mcast);
1824                                 v4mcast = -1;
1825                                 syslog (LOG_ERR, "%s: No LAN bypass: Failed to bind to IPv4 all-nodes\n", program);
1826                         } else if (listen (v4mcast, 10) != 0) {
1827                                 close (v4mcast);
1828                                 v4mcast = -1;
1829                                 syslog (LOG_ERR, "%s: No LAN bypass: Failed to listen to IPv4 all-nodes\n", program);
1830                         }
1831 #endif
1832                 }
1833         } else {
1834                 syslog (LOG_INFO, "%s: No LAN bypass: Not desired\n", program);
1835         }
1836         //
1837         // Construct an rtnetlink socket for neighbor cache interaction
1838         rtsox = socket (PF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
1839         if (rtsox == -1) {
1840                 syslog (LOG_CRIT, "Failed to gain access to the neighbor cache: %s\n", strerror (errno));
1841                 exit (1);
1842         }
1843         memset (&rtname,   0, sizeof (rtname  ));
1844         memset (&rtkernel, 0, sizeof (rtkernel));
1845         rtname.nl_family = rtkernel.nl_family = AF_NETLINK;
1846         rtname.nl_pid = getpid ();
1847         if (bind (rtsox, (struct sockaddr *) &rtname, sizeof (rtname)) == -1) {
1848                 syslog (LOG_CRIT, "Failed to bind to the neighbor cache socket: %s\n", strerror (errno));
1849                 exit (1);
1850         }
1851         if (connect (rtsox, (struct sockaddr *) &rtkernel, sizeof (rtkernel)) == -1) {
1852                 syslog (LOG_CRIT, "Failed to connect to the neighbor cachr in the kernel; %s\n", strerror (errno));
1853                 exit (1);
1854         }
1855 { uint8_t testll [6];
1856 uint8_t test_address [] = { 0xfe, 0x80, 0,0,0,0,0,0, 0xc2, 0x25, 0x06, 0xff, 0xfe, 0xb0, 0x7e, 0xa6 };
1857 if (lookup_neighbor (test_address, testll)) {
1858 syslog (LOG_INFO, "Successfully retrieved LL: %02x:%02x:%02x:%02x:%02x:%02x\n", testll [0], testll [1], testll [2], testll [3], testll [4], testll [5]);
1859 } else { syslog (LOG_INFO, "Failed to find LL\n"); } }
1860         //
1861         // If port and/or listen arguments were provided, bind to them
1862         if ((v4bind.sin_addr.s_addr != INADDR_ANY) || (v4bind.sin_port != 0)) {
1863                 if (bind (v4sox, (struct sockaddr *) &v4bind, sizeof (v4bind)) != 0) {
1864                         syslog (LOG_CRIT, "%s: Failed to bind to local socket -- did you specify both address and port?\n", program);
1865                         exit (1);
1866                 }
1867         }
1868         //
1869         // Run the daemon
1870         if (foreground) {
1871                 run_daemon ();
1872         } else {
1873                 if (setsid () != -1) {
1874                         syslog (LOG_CRIT, "%s: Failure to detach from parent session: %s\n", program, strerror (errno));
1875                         exit (1);
1876                 }
1877                 switch (fork ()) {
1878                 case -1:
1879                         syslog (LOG_CRIT, "%s: Failure to fork daemon process: %s\n", program, strerror (errno));
1880                         exit (1);
1881                 case 0:
1882                         close (0);
1883                         if (! log_to_stderr) {
1884                                 close (1);
1885                                 close (2);
1886                         }
1887                         run_daemon ();
1888                         break;
1889                 default:
1890                         break;
1891                 }
1892         }
1893         //
1894         // Report successful creation of the daemon
1895         closelog ();
1896         exit (0);
1897 }
1898