updated relay_6bed4_plain_unicast
[6bed4] / router.c
1 /* 6bed4/router.c -- traffic forwarding daemon for public TSP service
2  *
3  * This is an implementation of the profile that makes TSP service publicly
4  * usable, that is without authentication.  However to avoid abuse of such
5  * a service, it is not anonymous -- IPv6 addresses contain the IPv4 address
6  * and port.
7  *
8  * This is an implementation of neighbour and router discovery over a
9  * tunnel that packs IPv6 inside UDP/IPv4.  This tunnel mechanism is
10  * targeted specifically at embedded devices that are to function on
11  * any network, including IPv4-only, while being designed as IPv6-only
12  * devices with a fallback to this tunnel.
13  *
14  * Interestingly, as a side-effect of this design the router daemon can be
15  * stateless.  Any further requirements that are stateful are most likely
16  * filtering, and that can be solved in stateful firewall configuration.
17  *
18  * The intention of TSP is to enable IPv4-only hosts to connecto to
19  * IPv6 services; the public TSP profile adds to that the ability to
20  * do it in a temporary manner.
21  *
22  * TODO: Should we translate ICMPv4 --> ICMPv6?
23  *
24  * From: Rick van Rein <rick@openfortress.nl>
25  */
26
27
28 #include <stdlib.h>
29 #include <stdint.h>
30 #include <stdio.h>
31 #include <stdbool.h>
32
33 #include <errno.h>
34 #include <unistd.h>
35 #include <string.h>
36 #include <getopt.h>
37 #include <fcntl.h>
38
39 #include <sys/types.h>
40 #include <sys/socket.h>
41 #include <sys/time.h>
42 #include <sys/select.h>
43 #include <sys/ioctl.h>
44
45 #include <netinet/in.h>
46 #include <netinet/ip.h>
47 #include <netinet/ip6.h>
48 #include <netinet/udp.h>
49 #include <netinet/icmp6.h>
50 #include <arpa/inet.h>
51
52 #include <linux/if.h>
53 #include <linux/if_tun.h>
54 #include <linux/if_ether.h>
55
56
57 /* The following will initially fail, due to an IANA obligation to avoid
58  * default builds with non-standard options.
59  */
60 #include "nonstd.h"
61
62
63 #define MTU 1280
64
65 /*
66  * The HAVE_SETUP_TUNNEL variable is used to determine whether absense of
67  * the -t option leads to an error, or to an attempt to setup the tunnel.
68  * The setup_tunnel() function used for that is defined per platform, such
69  * as for LINUX.  Remember to maintain the manpage's optionality for -t.
70  */
71 #undef HAVE_SETUP_TUNNEL
72
73
74 /* Global variables */
75
76 char *program;
77
78 int v4sox = -1;
79 int v6sox = -1;
80
81 char *v4server = NULL;
82 char *v6server = NULL;
83 char *v6prefix = NULL;
84
85 const uint8_t v6listen_linklocal [16] = { 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
86 uint8_t v6listen_linklocal_complete [16] = { 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
87
88 uint8_t lladdr_6bed4 [6];
89
90 struct sockaddr_in  v4name;
91 struct sockaddr_in6 v6name;
92
93 struct in6_addr v6listen;
94 struct in6_addr v6listen_complete;
95 struct in_addr  v4listen;
96
97
98 struct {
99         struct tun_pi tun;
100         union {
101                 struct {
102                         struct ip6_hdr v6hdr;
103                         uint8_t data [MTU - sizeof (struct ip6_hdr)];
104                 } idata;
105                 struct {
106                         struct ip6_hdr v6hdr;
107                         struct icmp6_hdr v6icmphdr;
108                 } ndata;
109         } udata;
110 } v4data6;
111
112 #define v4tunpi6        ( v4data6.tun)
113 #define v4data          ((uint8_t *) &v4data6.udata)
114 #define v4hdr6          (&v4data6.udata.idata.v6hdr)
115 #define v4src6          (&v4data6.udata.idata.v6hdr.ip6_src)
116 #define v4dst6          (&v4data6.udata.idata.v6hdr.ip6_dst)
117
118 #define v4v6plen        ( v4data6.udata.ndata.v6hdr.ip6_plen)
119 #define v4v6nexthdr     ( v4data6.udata.ndata.v6hdr.ip6_nxt)
120 #define v4v6hoplimit    ( v4data6.udata.ndata.v6hdr.ip6_hops)
121
122 #define v4icmp6         (&v4data6.udata.ndata.v6icmphdr)
123 #define v4v6icmpdata    ( v4data6.udata.ndata.v6icmphdr.icmp6_data8)
124 #define v4v6icmptype    ( v4data6.udata.ndata.v6icmphdr.icmp6_type)
125 #define v4v6icmpcode    ( v4data6.udata.ndata.v6icmphdr.icmp6_code)
126 #define v4v6icmpcksum   ( v4data6.udata.ndata.v6icmphdr.icmp6_cksum)
127
128 #define v4ngbsoltarget  (&v4data6.udata.ndata.v6icmphdr.icmp6_data8 [4])
129
130
131 struct {
132         struct tun_pi tun;
133         union {
134                 uint8_t data [MTU];
135                 struct ip6_hdr v6hdr;
136                 struct icmp6_hdr v6icmp;
137         } udata;
138         uint8_t zero;
139 } v6data6;
140
141 #define v6tuncmd        ( v6data6.tun)
142 #define v6data          ( v6data6.udata.data)
143 #define v6hdr6          (&v6data6.udata.v6hdr)
144 #define v6src6          (&v6data6.udata.v6hdr.ip6_src)
145 #define v6dst6          (&v6data6.udata.v6hdr.ip6_dst)
146 #define v6hoplimit      ( v6data6.udata.v6hdr.ip6_hops)
147
148 #define v6nexthdr       ( v6data6.udata.v6hdr.ip6_nxt)
149 #define v6icmptype      ( v6data6.udata.v6icmp.icmp6_type)
150
151
152 uint8_t router_linklocal_address [] = {
153         0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00,
154 };
155
156 uint8_t democlient_linklocal_address [] = {
157         0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x01,
158 };
159
160 uint8_t allnodes_linklocal_address [] = {
161         0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x01,
162 };
163
164 uint8_t allrouters_linklocal_address [] = {
165         0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x02,
166 };
167
168
169 /*
170  *
171  * Driver routines
172  *
173  */
174
175 #ifdef LINUX
176 #define HAVE_SETUP_TUNNEL
177 /* Implement the setup_tunnel() command for Linux.
178  * Return 1 on success, 0 on failure.
179  */
180 int setup_tunnel (void) {
181         v6sox = open ("/dev/net/tun", O_RDWR);
182         if (v6sox == -1) {
183                 fprintf (stderr, "%s: Failed to access tunnel driver on /dev/net/tun: %s\n", program, strerror (errno));
184                 return 0;
185         }
186         int ok = 1;
187         struct ifreq ifreq;
188         memset (&ifreq, 0, sizeof (ifreq));
189         strncpy (ifreq.ifr_name, "6bed4", IFNAMSIZ);
190         ifreq.ifr_flags = IFF_TUN;
191         if (ok && (ioctl (v6sox, TUNSETIFF, (void *) &ifreq) == -1)) {
192                 ok = 0;
193         }
194         ifreq.ifr_name [IFNAMSIZ] = 0;
195         char cmd [512+1];
196         snprintf (cmd, 512, "/sbin/ip -6 addr flush dev %s", ifreq.ifr_name);
197         if (ok && system (cmd) != 0) {
198                 ok = 0;
199         }
200         snprintf (cmd, 512, "/sbin/ip addr add fe80::0 dev %s scope link", ifreq.ifr_name);
201         if (ok && system (cmd) != 0) {
202                 ok = 0;
203         }
204         snprintf (cmd, 512, "/sbin/ip -6 addr add %s dev %s", v6prefix, ifreq.ifr_name);
205         if (ok && system (cmd) != 0) {
206                 ok = 0;
207         }
208         snprintf (cmd, 512, "/sbin/ip link set %s up mtu 1280", ifreq.ifr_name);
209         if (ok && system (cmd) != 0) {
210                 ok = 0;
211         }
212         if (!ok) {
213                 close (v6sox);  /* This removes the tunnel interface */
214         }
215         return ok;
216 }
217 #endif /* LINUX */
218
219
220 /*
221  *
222  * Utility functions
223  *
224  */
225
226
227 /* Calculate the ICMPv6 checksum field
228  */
229 uint16_t icmp6_checksum (size_t payloadlen) {
230         uint16_t plenword = htons (payloadlen);
231         uint16_t nxthword = htons (IPPROTO_ICMPV6);
232         uint16_t *area [] = { (uint16_t *) v4src6, (uint16_t *) v4dst6, &plenword, &nxthword, (uint16_t *) v4icmp6, (uint16_t *) v4v6icmpdata };
233         uint8_t areawords [] = { 8, 8, 1, 1, 1, payloadlen/2 - 2 };
234         uint32_t csum = 0;
235         u_int8_t i, j;
236         for (i=0; i < 6; i++) {
237                 for (j=0; j<areawords [i]; j++) {
238                         csum += ntohs (area [i] [j]);
239                 }
240         }
241         csum = (csum & 0xffff) + (csum >> 16);
242         csum = (csum & 0xffff) + (csum >> 16);
243         csum = htons (~csum);
244         return csum;
245 }
246
247
248 /* Send an ICMPv6 reply.  This is constructed at the tunnel end, from
249  * the incoming message.  The parameter indicates how many bytes the
250  * ICMPv6 package counts after the ICMPv6 header.  It must be 4 (mod 8).
251  *
252  * Actions: v4/udp src becomes dest, set v4/udp/v6 src, len, cksum, send.
253  *          v6 dest is provided (usually v4src6) but if it starts with
254  *          0x00,0x00 it will be replaced with allnodes_linklocal_address.
255  */
256 void icmp6_reply (size_t icmp6bodylen, struct in6_addr *dest) {
257         v4v6hoplimit = 255;
258         if ((icmp6bodylen & 0x07) != 4) {
259                 return;   /* illegal length, drop */
260         }
261         v4v6plen = htons (icmp6bodylen + 4);
262         if ((* (uint16_t *) dest) == htons (0x0000)) {
263                 memcpy (v4dst6, allnodes_linklocal_address, 16);
264         } else {
265                 memcpy (v4dst6, dest, 16);
266         }
267         memcpy (v4src6, router_linklocal_address, 16);
268         v4v6icmpcksum = icmp6_checksum (ntohs (v4v6plen));
269         //
270         // Send the message to the IPv4 originator port
271 printf ("Sending ICMPv6-IPv6-UDP-IPv4 to %d.%d.%d.%d:%d, result = %d\n",
272 ((uint8_t *) &v4name.sin_addr.s_addr) [0],
273 ((uint8_t *) &v4name.sin_addr.s_addr) [1],
274 ((uint8_t *) &v4name.sin_addr.s_addr) [2],
275 ((uint8_t *) &v4name.sin_addr.s_addr) [3],
276 ntohs (v4name.sin_port),
277         sendto (v4sox,
278                         v4data,
279                         sizeof (struct ip6_hdr) + 4 + icmp6bodylen,
280                         MSG_DONTWAIT,
281                         (struct sockaddr *) &v4name, sizeof (v4name)));
282 }
283
284
285 /* Append the current prefix to an ICMPv6 message.  Incoming optidx
286  * and return values signify original and new offset for ICMPv6 options.
287  * The endlife parameter must be set to obtain zero lifetimes, thus
288  * instructing the tunnel client to stop using an invalid prefix.
289  */
290 size_t icmp6_prefix (size_t optidx, uint8_t endlife) {
291         v4v6icmpdata [optidx++] = 3;    // Type
292         v4v6icmpdata [optidx++] = 4;    // Length
293         v4v6icmpdata [optidx++] = 64;   // This is a /64 prefix
294         v4v6icmpdata [optidx++] = 0xc0; // L=1, A=1, Reserved1=0
295         memset (v4v6icmpdata + optidx, endlife? 0x00: 0xff, 8);
296         optidx += 8;
297                                         // Valid Lifetime: Zero / Infinite
298                                         // Preferred Lifetime: Zero / Infinite
299         memset (v4v6icmpdata + optidx, 0, 4);
300         optidx += 4;
301                                         // Reserved2=0
302         memcpy (v4v6icmpdata + optidx + 0, &v6listen, 8);
303         memset (v4v6icmpdata + optidx + 8, 0, 8);
304         optidx += 16;
305         return optidx;
306 }
307
308
309 /*
310  * TODO: DEPRECATED
311  *
312  * Append a Destination Link-Layer Address Option to an ICMPv6
313  * message.  The address is comprised from the remote's UDP port
314  * and IPv4 address, as seen by the router.  They are supplied
315  * in that order, in network byte order.  The resulting address
316  * is 6 bytes, but even though that makes it look like a MAC
317  * address, it really is another beast.
318  * Note that no effort is made in the router to recognise the
319  * "illegal port number" 0x3333 -- the client needs a message
320  * and will recognise it and act on it.
321  */
322 size_t icmp6_dest_linkaddr (size_t optidx) {
323         uint8_t typelen [2] = { ND_OPT_DESTINATION_LINKADDR, 1 };
324         memcpy (v4v6icmpdata + optidx + 0, &typelen, 2);
325         v4v6icmpdata [optidx + 2] = ntohs (v4name.sin_port) % 256;
326         v4v6icmpdata [optidx + 3] = ntohs (v4name.sin_port) / 256;
327         memcpy (v4v6icmpdata + optidx + 4, &v4name.sin_addr, 4);
328         optidx += 8;
329         return optidx;
330 }
331
332
333 /*
334  * Test if the provided IPv6 address matches the prefix used for 6bed4.
335  */
336 static inline bool prefix_6bed4 (struct in6_addr *ip6) {
337         return memcmp (&v6listen, ip6->s6_addr, 8) == 0;
338 }
339
340
341 /*
342  * Validate the originator's IPv6 address.  It should match the
343  * UDP/IPv4 coordinates of the receiving 6bed4 socket.  Also,
344  * the /64 prefix must match that of v6listen.
345  */
346 bool validate_originator (struct sockaddr_in *sin, struct in6_addr *ip6) {
347         uint16_t port = ntohs (sin->sin_port);
348         uint32_t addr = ntohl (sin->sin_addr.s_addr);
349         if (!prefix_6bed4 (ip6)) {
350                 return false;
351         }
352         if ((port % 256) != (ip6->s6_addr [8] ^ 0x02)) {
353                 return false;
354         }
355         if ((port / 256) != ip6->s6_addr [9]) {
356                 return false;
357         }
358         if ((addr >> 24) != ip6->s6_addr [10]) {
359                 return false;
360         }
361         if ((addr & 0x00ffffff) != (htonl (ip6->s6_addr32 [3]) & 0x00ffffff)) {
362                 return false;
363         }
364         return true;
365 }
366
367
368 /*
369  * Major packet processing functions
370  */
371
372
373 /*
374  * Respond to a Router Solicitation received over the 6bed4 Network.
375  */
376 void handle_6bed4_router_solicit (void) {
377         struct in6_addr observed;
378         v4v6icmptype = ND_ROUTER_ADVERT;
379         v4v6icmpdata [0] = 0;                   // Cur Hop Limit: unspec
380         v4v6icmpdata [1] = 0x18;                // M=0, O=0
381                                                 // H=0, Prf=11=Low
382                                                 // Reserved=0
383 // TODO: wire says 0x44 for router_adv.flags
384         size_t writepos = 2;
385         memset (v4v6icmpdata+writepos, 0xff, 2+4+4);
386                                         // Router Lifetime: max, 18.2h
387                                         // Reachable Time: max
388                                         // Retrans Timer: max
389         writepos += 2+4+4;
390         writepos = icmp6_prefix (writepos, 0);
391         //TODO:DEPRECATED// writepos = icmp6_dest_linkaddr (writepos);
392         memcpy (&observed, v6listen_linklocal, 8);
393         observed.s6_addr [8] = htons (v4name.sin_port) % 256 ^ 0x02;
394         observed.s6_addr [9] = htons (v4name.sin_port) / 256;
395         memcpy (&observed.s6_addr32 [3], &v4name.sin_addr, 4);
396         observed.s6_addr [10] = observed.s6_addr [12];
397         observed.s6_addr [11] = 0xff;
398         observed.s6_addr [12] = 0xfe;
399         icmp6_reply (writepos, &observed);
400 }
401
402
403 /* Handle the IPv4 message pointed at by msg as a neighbouring command.
404  *
405  * Type Code    ICMPv6 meaning                  Handling
406  * ---- ----    -----------------------------   ----------------------------
407  * 133  0       Router Solicitation             Send Router Advertisement
408  * 134  0       Router Advertisement            Ignore
409  * 135  0       Neighbour Solicitation          Send Neighbour Advertisement
410  * 136  0       Neighbour Advertisement         Ignore
411  * 137  0       Redirect                        Ignore
412  */
413 void handle_4to6_nd (ssize_t v4ngbcmdlen) {
414         uint16_t srclinklayer;
415         if (v4ngbcmdlen < sizeof (struct ip6_hdr) + sizeof (struct icmp6_hdr)) {
416                 return;
417         }
418         if (v4v6icmpcode != 0) {
419                 return;
420         }
421         if (icmp6_checksum (v4ngbcmdlen - sizeof (struct ip6_hdr)) != v4v6icmpcksum) {
422                 return;
423         }
424         //
425         // Approved.  Perform neighbourly courtesy.
426         switch (v4v6icmptype) {
427         case ND_ROUTER_SOLICIT:
428                 //
429                 // Validate Router Solicitation
430                 srclinklayer = 0;
431                 if (v4ngbcmdlen == sizeof (struct ip6_hdr) + 8 + 8) {
432                         // One option is possible, the source link-layer address
433                         if (v4v6icmpdata [4] != 1 || v4v6icmpdata [5] != 1) {
434                                 break;   /* bad opton, ignore */
435                         }
436                         // The source link-layer address is end-aligned
437                         srclinklayer = (v4v6icmpdata [10] << 8) | v4v6icmpdata [11];
438                         if (srclinklayer == 0) {
439                                 break;   /* illegal, ignore */
440                         }
441                 } else if (v4ngbcmdlen == sizeof (struct ip6_hdr) + 8) {
442                         srclinklayer = 0;   /* set for latter filling */
443                 } else {
444                         break;   /* illegal length, drop */
445                 }
446                 //
447                 // Having accepted the Router Advertisement, respond
448                 handle_6bed4_router_solicit ();
449                 break;
450         case ND_NEIGHBOR_SOLICIT:
451                 //
452                 // Validate Neigbour Solicitation
453                 if (!validate_originator (&v4name, v4src6)) {
454                         break;  /* bad source address, drop */
455                 }
456                 if ((v4ngbcmdlen != sizeof (struct ip6_hdr) + 24) &&
457                     (v4ngbcmdlen != sizeof (struct ip6_hdr) + 24 + 8)) {
458                         break;   /* funny length, drop */
459                 }
460                 if ((memcmp (v4ngbsoltarget, v6listen_linklocal, 16) != 0) &&
461                     (memcmp (v4ngbsoltarget, v6listen_linklocal_complete, 16) != 0) &&
462                     (memcmp (v4ngbsoltarget, &v6listen_complete, 16) != 0)) {
463                         break;  /* target not known here, drop */
464                 }
465                 //
466                 // Construct Neigbour Advertisement
467                 v4v6icmptype = ND_NEIGHBOR_ADVERT;
468                 v4v6icmpdata [0] = 0xc0;
469                 v4v6icmpdata [1] =
470                 v4v6icmpdata [2] =
471                 v4v6icmpdata [3] = 0x00;        // R=1, S=1, O=1, Reserved=0
472                 memcpy (v4v6icmpdata +  4, &v6listen_complete, 16);
473                 // Append option: the target link-layer address
474                 // Note: wire does not include target link-layer address
475                 v4v6icmpdata [20] = 2;          // Type: Target Link-Layer Addr
476                 v4v6icmpdata [21] = 1;          // Length: 1x 8 bytes
477                 memcpy (v4v6icmpdata + 22, lladdr_6bed4, 6);
478                 icmp6_reply (28, v4src6);       // 28 is the ICMPv6 response length
479                 break;
480         case ND_ROUTER_ADVERT:
481         case ND_NEIGHBOR_ADVERT:
482         case ND_REDIRECT:
483                 break;   /* drop */
484         }
485 }
486
487
488 /* 
489  * Forward a message received over the 6bed4 Network over IPv6.
490  * Note that existing checksums will work well, as only the
491  * Hop Limit has been altered, and this is not part of the
492  * checksum calculations.
493  */
494 void handle_4to6_plain_unicast (ssize_t v4datalen) {
495 printf ("Writing IPv6, result = %d\n",
496         write (v6sox, &v4data6, sizeof (struct tun_pi) + v4datalen));
497 }
498
499
500 /*
501  * Forward a 6bed4 message to another 6bed4 destination address.
502  * Note that existing checksums will work well, as only the
503  * Hop Limit has been altered, and this is not part of the
504  * checksum calculations.
505  */
506 void relay_6bed4_plain_unicast (uint8_t* data, ssize_t v4datalen, struct in6_addr *ip6) {
507         v4name.sin_port = htons (ip6->s6_addr [9] << 8 | ip6->s6_addr [8] ^ 0x02);
508         uint8_t *addr = (uint8_t *) &v4name.sin_addr.s_addr;
509         addr [0] = ip6->s6_addr [10];
510         memcpy (addr + 1, ip6->s6_addr + 13, 3);
511 printf ("Relaying over 6bed4 Network to %d.%d.%d.%d:%d, result = %d\n",
512 ((uint8_t *) &v4name.sin_addr.s_addr) [0],
513 ((uint8_t *) &v4name.sin_addr.s_addr) [1],
514 ((uint8_t *) &v4name.sin_addr.s_addr) [2],
515 ((uint8_t *) &v4name.sin_addr.s_addr) [3],
516 ntohs (v4name.sin_port),
517         sendto (v4sox,
518                         data, v4datalen,
519                         MSG_DONTWAIT,
520                         (struct sockaddr *) &v4name, sizeof (v4name)));
521 }
522
523
524 /* Receive a tunnel package, and route it to either the handler for the
525  * tunnel protocol, or to the handler that checks and then unpacks the
526  * contained IPv6.
527  */
528 void handle_4to6 (void) {
529         uint8_t buf [1501];
530         ssize_t buflen;
531         socklen_t adrlen = sizeof (v4name);
532         //
533         // Receive IPv4 package, which may be tunneled or a tunnel request
534         buflen = recvfrom (v4sox,
535                         v4data, MTU,
536                         MSG_DONTWAIT,
537                         (struct sockaddr *) &v4name, &adrlen
538                 );
539         if (buflen == -1) {
540                 printf ("%s: Error receiving IPv4-side package: %s",
541                                 program, strerror (errno));
542                 return;
543         }
544         if (buflen < sizeof (struct ip6_hdr)) {
545                 return;
546         }
547         if ((v4data [0] & 0xf0) != 0x60) {
548                 // Not an IPv6 packet
549                 return;
550         }
551         //
552         // Handle the tunneled IPv6 package (dependent on its class)
553         if ((v4v6nexthdr == IPPROTO_ICMPV6) &&
554                         (v4v6icmptype >= 133) && (v4v6icmptype <= 137)) {
555                 //
556                 // Not Plain: Router Adv/Sol, Neighbor Adv/Sol, Redirect
557                 if (v4v6hoplimit != 255) {
558                         return;
559                 }
560                 handle_4to6_nd (buflen);
561         } else if ((v4dst6->s6_addr [0] != 0xff) && !(v4dst6->s6_addr [8] & 0x01)) {
562                 //
563                 // Plain Unicast
564                 if (validate_originator (&v4name, v4src6)) {
565                         if (v4v6hoplimit-- <= 1) {
566                                 return;
567                         }
568                         if (prefix_6bed4 (v4dst6)) {
569                                 relay_6bed4_plain_unicast (v4data, buflen, v4dst6);
570                         } else {
571                                 handle_4to6_plain_unicast (buflen);
572                         }
573                 } else if (prefix_6bed4 (v4src6)) {
574                         // The sender must not have kept NAT/firewall holes
575                         // open and should be instructed about a change in
576                         // its 6bed4 Link-Local Address.
577                         handle_6bed4_router_solicit ();
578                 }
579         } else {
580                 //
581                 // Plain Multicast
582                 //OPTIONAL// validate_originator, hoplimit, relay_mcast.
583                 return;
584         }
585 }
586
587
588 /* Receive an IPv6 package, check its address and pickup IPv4 address and
589  * port, then package it as a tunnel message and forward it to IPv4:port.
590  */
591 void handle_6to4 (void) {
592         //
593         // Receive the IPv6 package and ensure a consistent size
594         size_t rawlen = read (v6sox, &v6data6, sizeof (v6data6));
595         if (rawlen == -1) {
596                 return;         /* error reading, drop */
597         }
598         if (rawlen < sizeof (struct tun_pi) + sizeof (struct ip6_hdr) + 1) {
599                 return;         /* too small, drop */
600         }
601         if (v6tuncmd.proto != htons (ETH_P_IPV6)) {
602                 return;         /* no IPv6, drop */
603         }
604         if ((v6nexthdr == IPPROTO_ICMPV6) &&
605                         (v6icmptype >= 133) && (v6icmptype <= 137)) {
606                 return;         /* not plain IPv6, drop */
607         }
608         if (v6hoplimit-- <= 1) {
609                 // TODO: Send back an ICMPv6 error message
610                 return;         /* hop limit exceeded, drop */
611         }
612         if ((v6dst6->s6_addr [0] == 0xff) /* TODO:UDP_PORT_NOT_YET_FORCED_TO_EVEN || (v6dst6->s6_addr [8] & 0x01) */ ) {
613 printf ("Received multicast IPv6 data, flags=0x%04x, proto=0x%04x\n", v6tuncmd.flags, v6tuncmd.proto);
614                 //OPTIONAL// handle_6to4_plain_multicast ()
615                 return;         /* multicast, drop */
616         }
617 printf ("Received plain unicast IPv6 data, flags=0x%04x, proto=0x%04x\n", v6tuncmd.flags, v6tuncmd.proto);
618         //
619         // Ensure that the incoming IPv6 address is properly formatted
620         // Note that this avoids access to ::1/128, fe80::/10, fec0::/10
621         if (memcmp (v6dst6, &v6listen, 8) != 0) {
622                 return;
623         }
624         //
625         // Harvest socket address data from destination IPv6, then send
626         relay_6bed4_plain_unicast (v6data, rawlen - sizeof (struct tun_pi), v6dst6);
627 }
628
629
630 /* Run the daemon core code, passing information between IPv4 and IPv6 and
631  * responding to tunnel requests if so requested.
632  */
633 void run_daemon (void) {
634         fd_set io;
635         FD_ZERO (&io);
636         FD_SET (v4sox, &io);
637         FD_SET (v6sox, &io);
638         int nfds = (v4sox < v6sox)? (v6sox + 1): (v4sox + 1);
639         while (1) {
640                 select (nfds, &io, NULL, NULL, NULL);
641                 if (FD_ISSET (v4sox, &io)) {
642                         handle_4to6 ();
643                 } else {
644                         FD_SET (v4sox, &io);
645                 }
646                 if (FD_ISSET (v6sox, &io)) {
647                         handle_6to4 ();
648                 } else {
649                         FD_SET (v6sox, &io);
650                 }
651 fflush (stdout);
652         }
653 }
654
655
656 /* Option descriptive data structures */
657
658 char *short_opt = "l:L:t:h";
659
660 struct option long_opt [] = {
661         { "v4listen", 1, NULL, 'l' },
662         { "v6prefix", 1, NULL, 'L' },
663         { "tundev", 1, NULL, 't' },
664         { "help", 0, NULL, 'h' },
665         { NULL, 0, NULL, 0 }    /* Array termination */
666 };
667
668 /* Parse commandline arguments (and start to process them).
669  * Return 1 on success, 0 on failure.
670  */
671 int process_args (int argc, char *argv []) {
672         int ok = 1;
673         int help = (argc == 1);
674         int done = 0;
675         while (!done) {
676                 switch (getopt_long (argc, argv, short_opt, long_opt, NULL)) {
677                 case -1:
678                         done = 1;
679                         if (optind != argc) {
680                                 fprintf (stderr, "%s: Extra arguments not permitted: %s...\n", program, argv [optind]);
681                                 ok = 0;
682                         }
683                         break;
684                 case 'l':
685                         if (v4sox != -1) {
686                                 ok = 0;
687                                 fprintf (stderr, "%s: Only one -l argument is permitted\n", program);
688                                 break;
689                         }
690                         v4server = optarg;
691                         if (inet_pton (AF_INET, optarg, &v4name.sin_addr) <= 0) {
692                                 ok = 0;
693                                 fprintf (stderr, "%s: Failed to parse IPv4 address %s\n", program, optarg);
694                                 break;
695                         }
696                         memcpy (&v4listen, &v4name.sin_addr, 4);
697                         v4sox = socket (AF_INET, SOCK_DGRAM, 0);
698                         if (v4sox == -1) {
699                                 ok = 0;
700                                 fprintf (stderr, "%s: Failed to allocate UDPv4 socket: %s\n", program, strerror (errno));
701                                 break;
702                         }
703                         if (bind (v4sox, (struct sockaddr *) &v4name, sizeof (v4name)) != 0) {
704                                 ok = 0;
705                                 fprintf (stderr, "%s: Failed to bind to UDPv4 %s:%d: %s\n", program, optarg, ntohs (v4name.sin_port), strerror (errno));
706                                 break;
707                         }
708                         break;
709                 case 'L':
710                         if (v6server) {
711                                 ok = 0;
712                                 fprintf (stderr, "%s: Only one -L argument is permitted\n", program);
713                                 break;
714                         }
715                         char *slash64 = strchr (optarg, '/');
716                         if (!slash64 || strcmp (slash64, "/64") != 0) {
717                                 ok = 0;
718                                 fprintf (stderr, "%s: The -L argument must be an explicit /64 prefix and not %s\n", program, slash64? slash64: "implied");
719                                 break;
720                         }
721                         *slash64 = 0;
722                         v6server = strdup (optarg);
723                         *slash64 = '/';
724                         v6prefix = optarg;
725                         if (!v6server || inet_pton (AF_INET6, v6server, &v6listen) <= 0) {
726                                 ok = 0;
727                                 fprintf (stderr, "%s: Failed to parse IPv6 prefix %s\n", program, optarg);
728                                 break;
729                         }
730                         if (v6listen.s6_addr32 [2] || v6listen.s6_addr32 [3]) {
731                                 ok = 0;
732                                 fprintf (stderr, "%s: IPv6 prefix contains bits beyond its /64 prefix: %s\n", program, optarg);
733                                 break;
734                         }
735                         break;
736                 case 't':
737                         if (v6sox != -1) {
738                                 ok = 0;
739                                 fprintf (stderr, "%s: Multiple -t arguments are not permitted\n", program);
740                                 break;
741                         }
742                         v6sox = open (optarg, O_RDWR);
743                         if (v6sox == -1) {
744                                 ok = 0;
745                                 fprintf (stderr, "%s: Failed to open tunnel device %s: %s\n", program, optarg, strerror (errno));
746                                 break;
747                         }
748                         break;
749                 default:
750                         ok = 0;
751                         help = 1;
752                         /* continue into 'h' to produce usage information */
753                 case 'h':
754                         help = 1;
755                         break;
756                 }
757                 if (help || !ok) {
758                         done = 1;
759                 }
760         }
761         if (help) {
762 #ifdef HAVE_SETUP_TUNNEL
763                 fprintf (stderr, "Usage: %s [-t /dev/tunX] -l <v4server> -L <v6prefix>/64\n       %s -h\n", program, program);
764 #else
765                 fprintf (stderr, "Usage: %s -t /dev/tunX -l <v4server> -L <v6prefix>/64\n       %s -h\n", program, program);
766 #endif
767                 return ok;
768         }
769         if (!ok) {
770                 return 0;
771         }
772         if (v4sox == -1) {
773                 fprintf (stderr, "%s: Use -l to specify an IPv4 address for the tunnel interface\n", program);
774                 return 0;
775         }
776         if (!v6server) {
777                 fprintf (stderr, "%s: Use -L to specify a /64 prefix on the IPv6 side\n", program);
778                 return 0;
779         }
780 #ifdef HAVE_SETUP_TUNNEL
781         if (v6sox == -1) {
782                 if (geteuid () != 0) {
783                         fprintf (stderr, "%s: You should be root, or use -t to specify an accessible tunnel device\n", program);
784                         return 0;
785                 }
786                 ok = setup_tunnel ();
787         }
788 #else /* ! HAVE_SETUP_TUNNEL */
789         if (v6sox == -1) {
790                 fprintf (stderr, "%s: You must specify a tunnel device with -t that is accessible to you\n", program);
791                 return 0;
792         }
793 #endif /* HAVE_SETUP_TUNNEL */
794         return ok;
795 }
796
797
798 /* The main program parses commandline arguments and forks off the daemon
799  */
800 int main (int argc, char *argv []) {
801         //
802         // Initialise
803         program = argv [0];
804         memset (&v4name, 0, sizeof (v4name));
805         memset (&v6name, 0, sizeof (v6name));
806         v4name.sin_family  = AF_INET ;
807         v6name.sin6_family = AF_INET6;
808         v4name.sin_port = htons (UDP_PORT_6BED4);   /* 6BED4 standard port */
809         v4tunpi6.flags = 0;
810         v4tunpi6.proto = htons (ETH_P_IPV6);
811         //
812         // Parse commandline arguments
813         if (!process_args (argc, argv)) {
814                 exit (1);
815         }
816         //
817         // Setup a few addresses for later comparison/reproduction
818         //  * lladdr_6bed4 is the 6bed4 Link-Local Address
819         //  * v6listen_complete is the router's full IPv6 address (with if-id)
820         //  * v6listen_linklocal_complete is fe80::/64 plus the router's if-id
821         // A few others have already been setup at this time
822         //  * v6listen is the router's 6bed4 prefix ending in 64 zero bits
823         //  * v6listen_linklocal is the address fe80::/128
824         //
825         lladdr_6bed4 [0] = UDP_PORT_6BED4 % 256;
826         lladdr_6bed4 [1] = UDP_PORT_6BED4 / 256;
827         memcpy (lladdr_6bed4 + 2, (uint8_t *) &v4name.sin_addr, 4);
828         memcpy (&v6listen_complete, &v6listen, 8);
829         v6listen_complete.s6_addr [8] = lladdr_6bed4 [0] ^ 0x02;
830         v6listen_complete.s6_addr [9] =  lladdr_6bed4 [1];
831         v6listen_complete.s6_addr [10] =  lladdr_6bed4 [2];
832         v6listen_complete.s6_addr [11] = 0xff;
833         v6listen_complete.s6_addr [12] = 0xfe;
834         memcpy (&v6listen_complete.s6_addr [13], lladdr_6bed4 + 3, 3);
835         memcpy (v6listen_linklocal_complete, v6listen_linklocal, 8);
836         memcpy (v6listen_linklocal_complete + 8, &v6listen_complete.s6_addr [8], 8);
837 printf ("LISTEN lladdr_6bed4 = %02x:%02x:%02x:%02x:%02x:%02x\n", lladdr_6bed4 [0], lladdr_6bed4 [1], lladdr_6bed4 [2], lladdr_6bed4 [3], lladdr_6bed4 [4], lladdr_6bed4 [5]);
838 printf ("LISTEN v6listen = %x:%x:%x:%x:%x:%x:%x:%x\n", htons (v6listen.s6_addr16 [0]), htons (v6listen.s6_addr16 [1]), htons (v6listen.s6_addr16 [2]), htons (v6listen.s6_addr16 [3]), htons (v6listen.s6_addr16 [4]), htons (v6listen.s6_addr16 [5]), htons (v6listen.s6_addr16 [6]), htons (v6listen.s6_addr16 [7]));
839 printf ("LISTEN v6listen_complete = %x:%x:%x:%x:%x:%x:%x:%x\n", htons (v6listen_complete.s6_addr16 [0]), htons (v6listen_complete.s6_addr16 [1]), htons (v6listen_complete.s6_addr16 [2]), htons (v6listen_complete.s6_addr16 [3]), htons (v6listen_complete.s6_addr16 [4]), htons (v6listen_complete.s6_addr16 [5]), htons (v6listen_complete.s6_addr16 [6]), htons (v6listen_complete.s6_addr16 [7]));
840 printf ("LISTEN v6listen_linklocal = %x:%x:%x:%x:%x:%x:%x:%x\n", htons (((uint16_t *) v6listen_linklocal) [0]), htons (((uint16_t *) v6listen_linklocal) [1]), htons (((uint16_t *) v6listen_linklocal) [2]), htons (((uint16_t *) v6listen_linklocal) [3]), htons (((uint16_t *) v6listen_linklocal) [4]), htons (((uint16_t *) v6listen_linklocal) [5]), htons (((uint16_t *) v6listen_linklocal) [6]), htons (((uint16_t *) v6listen_linklocal) [7]));
841 printf ("LISTEN v6listen_linklocal_complete = %x:%x:%x:%x:%x:%x:%x:%x\n", htons (((uint16_t *) v6listen_linklocal_complete) [0]), htons (((uint16_t *) v6listen_linklocal_complete) [1]), htons (((uint16_t *) v6listen_linklocal_complete) [2]), htons (((uint16_t *) v6listen_linklocal_complete) [3]), htons (((uint16_t *) v6listen_linklocal_complete) [4]), htons (((uint16_t *) v6listen_linklocal_complete) [5]), htons (((uint16_t *) v6listen_linklocal_complete) [6]), htons (((uint16_t *) v6listen_linklocal_complete) [7]));
842         //
843         // Start the main daemon process
844 #ifdef SKIP_TESTING_KLUDGE_IN_FOREGROUND
845         switch (fork ()) {
846         case -1:                /* Error forking */
847                 fprintf (stderr, "%s: Failed to fork: %s\n", program, strerror (errno));
848                 exit (1);
849         case 0:                 /* Child process */
850                 close (0);
851                 //TODO: tmp.support for ^printf// close (1);
852                 close (2);
853                 setsid ();
854                 run_daemon ();
855                 break;
856         default:                /* Parent process */
857                 close (v4sox);
858                 close (v6sox);
859                 break;
860         }
861 #else
862         run_daemon ();
863 #endif
864         //
865         // Report successful creation of the daemon
866         return 0;
867 }