7ca26e20fa46fc101a4c48d8203c51bbbf4b0fb9
[6bed4] / 6bed4router.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/tcp.h>
49 #include <netinet/udp.h>
50 #include <netinet/icmp6.h>
51 #include <arpa/inet.h>
52
53 #include <linux/if.h>
54 #include <linux/if_tun.h>
55 #include <linux/if_ether.h>
56
57
58 /* The following will initially fail, due to an IANA obligation to avoid
59  * default builds with non-standard options.
60  */
61 #include "nonstd.h"
62
63
64 #define MTU 1280
65
66 /*
67  * The HAVE_SETUP_TUNNEL variable is used to determine whether absense of
68  * the -d option leads to an error, or to an attempt to setup the tunnel.
69  * The setup_tunnel() function used for that is defined per platform, such
70  * as for LINUX.  Remember to maintain the manpage's optionality for -d.
71  */
72 #undef HAVE_SETUP_TUNNEL
73
74
75 /* Global variables */
76
77 /* SCTP structures are far from standardised, so we define our own header */
78 struct my_sctphdr {
79         uint16_t source, dest;
80         uint32_t vtag;
81         uint32_t cksum;
82 };
83
84 char *program;
85
86 int v4sox = -1;
87 int v6sox = -1;
88
89 char *v4server = NULL;
90 char *v6server = NULL;
91 char *v6prefix = NULL;
92
93 const uint8_t v6listen_linklocal [16] = { 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
94 uint8_t v6listen_linklocal_complete [16] = { 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
95
96 uint8_t lladdr_6bed4 [6];
97
98 struct sockaddr_in  v4name;
99 struct sockaddr_in6 v6name;
100
101 struct in6_addr v6listen;
102 struct in6_addr v6listen_complete;
103 struct in_addr  v4listen;
104
105
106 struct {
107         struct tun_pi tun;
108         union {
109                 struct {
110                         struct ip6_hdr v6hdr;
111                         uint8_t data [MTU - sizeof (struct ip6_hdr)];
112                 } idata;
113                 struct {
114                         struct ip6_hdr v6hdr;
115                         union {
116                                 struct icmp6_hdr  v6icmphdr;
117                                 struct my_sctphdr v6sctphdr;
118                                 struct tcphdr     v6tcphdr ;
119                                 struct udphdr     v6udphdr ;
120                         } adata;
121                 } ndata;
122         } udata;
123 } v4data6;
124
125 #define v4tunpi6        ( v4data6.tun)
126 #define v4data          ((uint8_t *) &v4data6.udata)
127 #define v4hdr6          (&v4data6.udata.idata.v6hdr)
128 #define v4src6          (&v4data6.udata.idata.v6hdr.ip6_src)
129 #define v4dst6          (&v4data6.udata.idata.v6hdr.ip6_dst)
130
131 #define v4v6payload     ((uint16_t *) &v4data6.udata.ndata.adata)
132 #define v4v6plen        ( v4data6.udata.ndata.v6hdr.ip6_plen)
133 #define v4v6nexthdr     ( v4data6.udata.ndata.v6hdr.ip6_nxt)
134 #define v4v6hoplimit    ( v4data6.udata.ndata.v6hdr.ip6_hops)
135
136 #define v4v6icmpdata    ( v4data6.udata.ndata.adata.v6icmphdr.icmp6_data8)
137 #define v4v6icmptype    ( v4data6.udata.ndata.adata.v6icmphdr.icmp6_type)
138 #define v4v6icmpcode    ( v4data6.udata.ndata.adata.v6icmphdr.icmp6_code)
139 #define v4v6icmpcksum   ( v4data6.udata.ndata.adata.v6icmphdr.icmp6_cksum)
140
141 #define v4v6sctpsrcport ( v4data6.udata.ndata.adata.v6sctphdr.source)
142 #define v4v6sctpdstport ( v4data6.udata.ndata.adata.v6sctphdr.dest)
143 #define v4v6sctpcksum   ( v4data6.udata.ndata.adata.v6sctphdr.cksum)
144
145 #define v4v6tcpsrcport  ( v4data6.udata.ndata.adata.v6tcphdr.source)
146 #define v4v6tcpdstport  ( v4data6.udata.ndata.adata.v6tcphdr.dest)
147 #define v4v6tcpcksum    ( v4data6.udata.ndata.adata.v6tcphdr.check)
148
149 #define v4v6udpsrcport  ( v4data6.udata.ndata.adata.v6udphdr.source)
150 #define v4v6udpdstport  ( v4data6.udata.ndata.adata.v6udphdr.dest)
151 #define v4v6udpcksum    ( v4data6.udata.ndata.adata.v6udphdr.check)
152
153 #define v4ngbsoltarget  (&v4data6.udata.ndata.adata.v6icmphdr.icmp6_data8 [4])
154
155
156 struct {
157         struct tun_pi tun;
158         union {
159                 uint8_t data [MTU];
160                 struct {
161                         struct ip6_hdr v6hdr;
162                         union {
163                                 struct icmp6_hdr  v6icmphdr;
164                                 struct my_sctphdr v6sctphdr;
165                                 struct tcphdr     v6tcphdr ;
166                                 struct udphdr     v6udphdr ;
167                         } adata;
168                 } ndata;
169         } udata;
170         uint8_t zero;
171 } v6data6;
172
173 #define v6tuncmd        ( v6data6.tun)
174 #define v6data          ( v6data6.udata.data)
175 #define v6hdr6          (&v6data6.udata.ndata.v6hdr)
176 #define v6src6          (&v6data6.udata.ndata.v6hdr.ip6_src)
177 #define v6dst6          (&v6data6.udata.ndata.v6hdr.ip6_dst)
178 #define v6hoplimit      ( v6data6.udata.ndata.v6hdr.ip6_hops)
179 #define v6nexthdr       ( v6data6.udata.ndata.v6hdr.ip6_nxt)
180
181 #define v6icmptype      ( v6data6.udata.ndata.adata.v6icmphdr.icmp6_type)
182 #define v6icmpcksum     ( v6data6.udata.ndata.adata.v6icmphdr.icmp6_cksum)
183
184 #define v6sctpcksum     ( v6data6.udata.ndata.adata.v6sctphdr.cksum)
185
186 #define v6tcpcksum      ( v6data6.udata.ndata.adata.v6tcphdr.check)
187
188 #define v6udpcksum      ( v6data6.udata.ndata.adata.v6udphdr.check)
189
190
191 uint8_t router_linklocal_address [] = {
192         0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x00,
193 };
194
195 uint8_t democlient_linklocal_address [] = {
196         0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x01,
197 };
198
199 uint8_t allnodes_linklocal_address [] = {
200         0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x01,
201 };
202
203 uint8_t allrouters_linklocal_address [] = {
204         0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x00, 0x02,
205 };
206
207
208
209 #ifndef MAXNUM_MASQHOST
210 #define MAXNUM_MASQHOST 4
211 #endif
212
213 uint16_t num_masqhost = 0;
214 uint8_t masqhost [MAXNUM_MASQHOST][16];
215
216 // ports for 's', 't', 'u' -- SCTP, TCP, UDP have increasing numbers
217
218 #ifndef MAXNUM_PORTPAIRS
219 #define MAXNUM_PORTPAIRS 10
220 #endif
221
222 // masqportpairs holds triples <lowport,highport,masqhostnr>
223 uint16_t num_masqportpairs [3] = { 0, 0, 0 };
224 uint16_t masqportpairs [3][3*MAXNUM_PORTPAIRS];
225
226 // same for ICMPv6
227 uint16_t icmp_num_portpairs = 0;
228 uint16_t icmp_portpairs [3] = { 1, 1, 0 };
229
230
231
232 /*
233  *
234  * Driver routines
235  *
236  */
237
238 #ifndef INTERFACE_NAME_6BED4
239 #define INTERFACE_NAME_6BED4 "6bed4"
240 #endif
241
242 #ifdef LINUX
243 #define HAVE_SETUP_TUNNEL
244 /* Implement the setup_tunnel() command for Linux.
245  * Return 1 on success, 0 on failure.
246  */
247 int setup_tunnel (void) {
248         v6sox = open ("/dev/net/tun", O_RDWR);
249         if (v6sox == -1) {
250                 fprintf (stderr, "%s: Failed to access tunnel driver on /dev/net/tun: %s\n", program, strerror (errno));
251                 return 0;
252         }
253         int ok = 1;
254         struct ifreq ifreq;
255         memset (&ifreq, 0, sizeof (ifreq));
256         strncpy (ifreq.ifr_name, INTERFACE_NAME_6BED4, IFNAMSIZ);
257         ifreq.ifr_flags = IFF_TUN;
258         if (ok && (ioctl (v6sox, TUNSETIFF, (void *) &ifreq) == -1)) {
259                 ok = 0;
260         }
261         ifreq.ifr_name [IFNAMSIZ] = 0;
262         char cmd [512+1];
263         snprintf (cmd, 512, "/sbin/ip -6 addr flush dev %s", ifreq.ifr_name);
264         if (ok && system (cmd) != 0) {
265                 ok = 0;
266         }
267         snprintf (cmd, 512, "/sbin/ip addr add fe80::0 dev %s scope link", ifreq.ifr_name);
268         if (ok && system (cmd) != 0) {
269                 ok = 0;
270         }
271         snprintf (cmd, 512, "/sbin/ip -6 addr add %s dev %s", v6prefix, ifreq.ifr_name);
272         if (ok && system (cmd) != 0) {
273                 ok = 0;
274         }
275         snprintf (cmd, 512, "/sbin/ip link set %s up mtu 1280", ifreq.ifr_name);
276         if (ok && system (cmd) != 0) {
277                 ok = 0;
278         }
279         if (!ok) {
280                 close (v6sox);  /* This removes the tunnel interface */
281                 fprintf (stderr, "Failed to setup tunnel \"%s\"\n", INTERFACE_NAME_6BED4);
282         }
283         return ok;
284 }
285 #endif /* LINUX */
286
287
288 /*
289  *
290  * Utility functions
291  *
292  */
293
294
295 /* Produce an IPv6 address following the 6bed4 structures.
296  *  - The top half is taken from v6listen
297  *  - The bottom contains IPv4 address and port from v4name
298  *  - The last 14 bits are filled with the lanip parameter
299  */
300 void addr_6bed4 (struct in6_addr *dst_ip6, uint16_t lanip) {
301         memcpy (&dst_ip6->s6_addr [0], &v6listen, 8);
302         dst_ip6->s6_addr32 [2] = v4name.sin_addr.s_addr;
303         dst_ip6->s6_addr16 [6] = v4name.sin_port;
304         dst_ip6->s6_addr  [14] = ((dst_ip6->s6_addr [8] & 0x03) << 6)
305                                | ((lanip >> 8) & 0x3f);
306         dst_ip6->s6_addr  [15] = (lanip & 0xff);
307         dst_ip6->s6_addr  [8] &= 0xfc;
308 }
309
310 /* Calculate the ICMPv6 checksum field
311  */
312 uint16_t icmp6_checksum (struct in6_addr *src6, struct in6_addr *dst6,
313                                 uint16_t *payload, size_t payloadlen) {
314         uint16_t plenword = htons (payloadlen); // our ICMPv6 is small
315         uint16_t nxthword = htons (IPPROTO_ICMPV6);
316         uint16_t *area [] = { src6->s6_addr16, dst6->s6_addr16,
317                                 &plenword, &nxthword,
318                                 payload, &payload [2] };
319         uint8_t areawords [] = { 8, 8, 1, 1, 1, (payloadlen >> 1) - 2 };
320         uint32_t csum = 0;
321         u_int8_t i, j;
322         for (i=0; i < 6; i++) {
323                 for (j=0; j<areawords [i]; j++) {
324                         csum += ntohs (area [i] [j]);
325                 }
326         }
327         csum = (csum & 0xffff) + (csum >> 16);
328         csum = (csum & 0xffff) + (csum >> 16);
329         csum = htons (~csum);
330         return csum;
331 }
332
333
334 /* Mangle a packet by replacing an IPv6 address, correcting the checksum.
335  * In all of ICMPv6, UDPv6, TCPv6, SCTPv6, the checksumming is a 1's cpl
336  * of a sum of 16-bit words; the position of the words don't matter and
337  * we can subtract the old address' words and add the new address' words.
338  * Or, as a result of the one's complement, the opposite.  There is some
339  * inclusion of the top half of a 32-bit sum, but that is also neutral.
340  */
341 void masquerade_address (struct in6_addr *var,
342                         const struct in6_addr *new,
343                         uint16_t *csum_field) {
344         int32_t csum = ntohs (~*csum_field);
345         uint8_t i;
346         for (i=0; i<8; i++) {
347                 csum -= ntohs (var->s6_addr16 [i]);
348                 var->s6_addr16 [i] = new->s6_addr16 [i];
349                 csum += ntohs (var->s6_addr16 [i]);
350         }
351         csum = (csum & 0xffff) + (csum >> 16);
352         csum = (csum & 0xffff) + (csum >> 16);
353         *csum_field = htons (~csum);
354 }
355
356
357 /* Send an ICMPv6 reply.  This is constructed at the tunnel end, from
358  * the incoming message.  The parameter indicates how many bytes the
359  * ICMPv6 package counts after the ICMPv6 header.  It must be 4 (mod 8).
360  *
361  * Actions: v4/udp src becomes dest, set v4/udp/v6 src, len, cksum, send.
362  *          reply is always to v4src6, except that if it starts with
363  *          0x00,0x00 it will be replaced with allnodes_linklocal_address.
364  */
365 void icmp6_reply (size_t icmp6bodylen) {
366         v4v6hoplimit = 255;
367         if ((icmp6bodylen & 0x07) != 4) {
368                 return;   /* illegal length, drop */
369         }
370         v4v6plen = htons (icmp6bodylen + 4);
371         memcpy (v4dst6,
372                 (v4src6->s6_addr16 [0])
373                         ? (uint8_t *) v4src6
374                         : allnodes_linklocal_address,
375                 16);
376         memcpy (v4src6, router_linklocal_address, 16);
377         v4v6icmpcksum = icmp6_checksum (v4src6, v4dst6,
378                                 v4v6payload, ntohs (v4v6plen));
379         //
380         // Send the message to the IPv4 originator port
381 printf ("Sending ICMPv6-IPv6-UDP-IPv4 to %d.%d.%d.%d:%d, result = %zd\n",
382 ((uint8_t *) &v4name.sin_addr.s_addr) [0],
383 ((uint8_t *) &v4name.sin_addr.s_addr) [1],
384 ((uint8_t *) &v4name.sin_addr.s_addr) [2],
385 ((uint8_t *) &v4name.sin_addr.s_addr) [3],
386 ntohs (v4name.sin_port),
387         sendto (v4sox,
388                         v4data,
389                         sizeof (struct ip6_hdr) + 4 + icmp6bodylen,
390                         MSG_DONTWAIT,
391                         (struct sockaddr *) &v4name, sizeof (v4name)));
392 }
393
394
395 /* Append the current prefix to an ICMPv6 message.  Incoming optidx
396  * and return values signify original and new offset for ICMPv6 options.
397  * The endlife parameter must be set to obtain zero lifetimes, thus
398  * instructing the tunnel client to stop using an invalid prefix.
399  */
400 size_t icmp6_prefix (size_t optidx, uint8_t endlife) {
401         v4v6icmpdata [optidx++] = 3;    // Type
402         v4v6icmpdata [optidx++] = 4;    // Length
403         v4v6icmpdata [optidx++] = 114;  // This is a /114 prefix
404         v4v6icmpdata [optidx++] = 0xc0; // L=1, A=1, Reserved1=0
405         memset (v4v6icmpdata + optidx, endlife? 0x00: 0xff, 8);
406         optidx += 8;
407                                         // Valid Lifetime: Zero / Infinite
408                                         // Preferred Lifetime: Zero / Infinite
409         memset (v4v6icmpdata + optidx, 0, 4);
410         optidx += 4;
411                                         // Reserved2=0
412         addr_6bed4 ((struct in6_addr *) (v4v6icmpdata + optidx), 0);
413                                         // Set IPv6 prefix
414         optidx += 16;
415         return optidx;
416 }
417
418
419 /*
420  * TODO: DEPRECATED
421  *
422  * Append a Destination Link-Layer Address Option to an ICMPv6
423  * message.  The address is comprised from the remote's UDP port
424  * and IPv4 address, as seen by the router.  They are supplied
425  * in that order, in network byte order.  The resulting address
426  * is 6 bytes, but even though that makes it look like a MAC
427  * address, it really is another beast.
428  * Note that no effort is made in the router to recognise the
429  * "illegal port number" 0x3333 -- the client needs a message
430  * and will recognise it and act on it.
431  */
432 size_t icmp6_dest_linkaddr (size_t optidx) {
433         uint8_t typelen [2] = { ND_OPT_DESTINATION_LINKADDR, 1 };
434         memcpy (v4v6icmpdata + optidx + 0, &typelen, 2);
435         v4v6icmpdata [optidx + 2] = ntohs (v4name.sin_port) & 0xff;
436         v4v6icmpdata [optidx + 3] = ntohs (v4name.sin_port) >> 8;
437         memcpy (v4v6icmpdata + optidx + 4, &v4name.sin_addr, 4);
438         optidx += 8;
439         return optidx;
440 }
441
442
443 /*
444  * Test if an address is a local override.  This function is compiled-in
445  * to support hosts with a /64 from their own ISP and nothing more; they
446  * need to access local IPv6 addresses.  We rely on the 6bed4 port being
447  * 0 to decide that an address cannot be anything but a local override.
448  * Define LOCAL_OVERRIDES_PORT0 to enable this feature.
449  */
450 #ifdef LOCAL_OVERRIDES_PORT0
451 static inline bool is_local_override (struct in6_addr *ip6) {
452         return (ip6->s6_addr16 [6] == 0) && (memcmp (ip6->s6_addr, &v6listen, 8) == 0);
453 }
454 #else
455 #define is_local_override(_) false
456 #endif
457
458
459 /*
460  * Test if the provided IPv6 address matches the prefix used for 6bed4.
461  *TODO: This is oversimplistic, it only cares for the Hetzner /64
462  */
463 static inline bool is_6bed4 (struct in6_addr *ip6) {
464         return memcmp (&v6listen, ip6->s6_addr, 8) == 0;
465 }
466
467 /* Test if the provided IPv6 address matches the fc64::/16 prefix.
468  * If so, the traffic may be bounced using 6bed4 traffic, but it
469  * must not be relayed to the native IPv6 side.
470  * TODO: Perhaps allow only configured <netid>, so fc64:<netid>::/32
471  */
472 static inline bool is_fc64 (struct in6_addr *ip6) {
473         return ip6->s6_addr16 [0] == htons (0xfc64);
474 }
475
476 /* Test if the src and destination share the same /114 and the destination
477  * fills up the rest with zero bits; in other words, test that this is a
478  * package targeted from a 6bed4peer node to its 6bed4router.  This is used
479  * to distinguish special ICMPv6 messages, as well as masquerading targets.
480  */
481 static inline bool is_mine (struct in6_addr *src6, struct in6_addr *dst6) {
482         return ((dst6->s6_addr [15] == 0x00)
483                 && ((dst6->s6_addr [14] & 0x3f) == 0x00)
484                 && (memcmp (dst6->s6_addr, src6->s6_addr, 14) == 0));
485 }
486
487
488 /*
489  * Validate the originator's IPv6 address.  It should match the
490  * UDP/IPv4 coordinates of the receiving 6bed4 socket.  Also,
491  * the /64 prefix (but not the /114 prefix!) must match v6listen.
492  */
493 bool validate_originator (struct in6_addr *ip6) {
494         uint32_t addr;
495         //
496         // Require non-local top halves to match our v6listen_linklocal address
497         // We will enforce our own fallback address (and fc64:<netid>::/32)
498         if (memcmp (ip6, v6listen_linklocal, 8) != 0) {
499                 if (memcmp (&v6listen, ip6->s6_addr, 8) != 0) {
500                         return false;
501                 }
502         }
503         //
504         // Require the sender port to appear in its IPv6 address
505         if (v4name.sin_port != ip6->s6_addr16 [6]) {
506                 return false;
507         }
508         //
509         // Require the sender address to appear in its IPv6 address
510         addr = ntohl (ip6->s6_addr32 [2]) & 0xfcffffff;
511         addr |= ((uint32_t) (ip6->s6_addr [14] & 0xc0)) << (24-6);
512         if (addr != ntohl (v4name.sin_addr.s_addr)) {
513                 return false;
514         }
515         //
516         // We passed with flying colours
517         return true;
518 }
519
520
521
522 /*
523  * Given a protocol and a port number, locate the masqhost that would match.
524  * The protocol is 0 for SCTP, 1 for TCP, 2 for UDP (alphabetic sequence).
525  * Returns a pointer to the address or NULL if not found.
526  */
527 uint8_t *protoport2masqhost (uint8_t proto, uint16_t port) {
528         //NOTUSED// TODO:IMPLEMENT
529         return NULL;
530 }
531
532
533
534 /*
535  * Major packet processing functions
536  */
537
538
539 /*
540  * Respond to a Router Solicitation received over the 6bed4 Network.
541  */
542 void handle_6bed4_router_solicit (void) {
543         struct in6_addr observed;
544         v4v6icmptype = ND_ROUTER_ADVERT;
545         v4v6icmpdata [0] = 0;                   // Cur Hop Limit: unspec
546         v4v6icmpdata [1] = 0x18;                // M=0, O=0
547                                                 // H=0, Prf=11=Low
548                                                 // Reserved=0
549 // TODO: wire says 0x44 for router_adv.flags
550         size_t writepos = 2;
551         memset (v4v6icmpdata+writepos, 0xff, 2+4+4);
552                                         // Router Lifetime: max, 18.2h
553                                         // Reachable Time: max
554                                         // Retrans Timer: max
555         writepos += 2+4+4;
556         writepos = icmp6_prefix (writepos, 0);
557         icmp6_reply (writepos);
558 }
559
560
561 /* Handle the IPv4 message pointed at by msg as a neighbouring command.
562  *
563  * Type Code    ICMPv6 meaning                  Handling
564  * ---- ----    -----------------------------   ----------------------------
565  * 133  0       Router Solicitation             Send Router Advertisement
566  * 134  0       Router Advertisement            Ignore
567  * 135  0       Neighbour Solicitation          Send Neighbour Advertisement
568  * 136  0       Neighbour Advertisement         Ignore
569  * 137  0       Redirect                        Ignore
570  */
571 void handle_4to6_nd (ssize_t v4ngbcmdlen) {
572         uint16_t srclinklayer;
573         if (v4ngbcmdlen < sizeof (struct ip6_hdr) + sizeof (struct icmp6_hdr)) {
574                 return;
575         }
576         if (v4v6icmpcode != 0) {
577                 return;
578         }
579         if (icmp6_checksum (v4src6, v4dst6,
580                                 v4v6payload, v4ngbcmdlen-sizeof (struct ip6_hdr)
581                         ) != v4v6icmpcksum) {
582                 return;
583         }
584         //
585         // Approved.  Perform neighbourly courtesy.
586         switch (v4v6icmptype) {
587         case ND_ROUTER_SOLICIT:
588                 //
589                 // Validate Router Solicitation
590                 srclinklayer = 0;
591                 if (v4ngbcmdlen == sizeof (struct ip6_hdr) + 8 + 8) {
592                         // One option is possible, the source link-layer address
593                         if (v4v6icmpdata [4] != 1 || v4v6icmpdata [5] != 1) {
594                                 break;   /* bad opton, ignore */
595                         }
596                         // The source link-layer address is end-aligned
597                         srclinklayer = (v4v6icmpdata [10] << 8) | v4v6icmpdata [11];
598                         if (srclinklayer == 0) {
599                                 break;   /* illegal, ignore */
600                         }
601                 } else if (v4ngbcmdlen == sizeof (struct ip6_hdr) + 8) {
602                         srclinklayer = 0;   /* set for latter filling */
603                 } else {
604                         break;   /* illegal length, drop */
605                 }
606                 //
607                 // Having accepted the Router Advertisement, respond
608                 handle_6bed4_router_solicit ();
609                 break;
610         case ND_NEIGHBOR_SOLICIT:
611                 //
612                 // Validate Neigbour Solicitation
613                 if (!validate_originator (v4src6)) {
614                         break;  /* bad source address, drop */
615                 }
616                 if ((v4ngbcmdlen != sizeof (struct ip6_hdr) + 24) &&
617                     (v4ngbcmdlen != sizeof (struct ip6_hdr) + 24 + 8)) {
618                         break;   /* funny length, drop */
619                 }
620                 if ((memcmp (v4ngbsoltarget, v6listen_linklocal, 16) != 0) &&
621                     (memcmp (v4ngbsoltarget, v6listen_linklocal_complete, 16) != 0) &&
622                     (memcmp (v4ngbsoltarget, &v6listen_complete, 16) != 0)) {
623                         break;  /* target not known here, drop */
624                 }
625                 //
626                 // Construct Neigbour Advertisement
627                 v4v6icmptype = ND_NEIGHBOR_ADVERT;
628                 v4v6icmpdata [0] = 0xc0;
629                 v4v6icmpdata [1] =
630                 v4v6icmpdata [2] =
631                 v4v6icmpdata [3] = 0x00;        // R=1, S=1, O=1, Reserved=0
632                 memcpy (v4v6icmpdata +  4, &v6listen_complete, 16);
633                 // Append option: the target link-layer address
634                 // Note: wire does not include target link-layer address
635                 v4v6icmpdata [20] = 2;          // Type: Target Link-Layer Addr
636                 v4v6icmpdata [21] = 1;          // Length: 1x 8 bytes
637                 memcpy (v4v6icmpdata + 22, lladdr_6bed4, 6);
638                 icmp6_reply (28);       // 28 is the ICMPv6 response length
639                 break;
640         case ND_ROUTER_ADVERT:
641         case ND_NEIGHBOR_ADVERT:
642         case ND_REDIRECT:
643                 break;   /* drop */
644         }
645 }
646
647
648 /*
649  * Forward a message to the masquerading target, or drop it.  This is done
650  * with non-6bed4 packets that are sent from a 6bed4peer node to its
651  * 6bed4router address; see is_mine() for the definition.  The general idea
652  * is that the address that is to be masqueraded can later be reconstructed
653  * from the 6bed4peer's address.
654  */
655 void handle_4to6_masquerading (ssize_t v4datalen) {
656         fprintf (stderr, "Traffic to 6bed4router may be fit for masquerading\n");
657         uint16_t *portpairs = NULL;
658         uint16_t numpairs = 0;
659         uint16_t port = 0;
660         uint16_t *csum_field = NULL;
661         switch (v4v6nexthdr) {
662 #ifdef CHECKSUM_SCTP_WOULD_BE_LIKE_FOR_OTHERS
663         case IPPROTO_SCTP:
664                 portpairs = masqportpairs [0];  // 's'
665                 numpairs  = num_masqportpairs [0];
666                 port = ntohs (v4v6sctpdstport);
667                 csum_field = &v4v6sctpcksum;
668                 break;
669 #endif
670         case IPPROTO_TCP:
671                 portpairs = masqportpairs [1];  // 't'
672                 numpairs  = num_masqportpairs [1];
673                 port = ntohs (v4v6tcpdstport);
674                 csum_field = &v4v6tcpcksum;
675                 break;
676         case IPPROTO_UDP:
677                 portpairs = masqportpairs [2];  // 'u'
678                 numpairs  = num_masqportpairs [2];
679                 port = ntohs (v4v6udpdstport);
680                 csum_field = &v4v6udpcksum;
681                 break;
682         case IPPROTO_ICMPV6:
683                 portpairs = icmp_portpairs;
684                 numpairs = icmp_num_portpairs;
685                 port = icmp_portpairs [0];
686                 csum_field = &v4v6icmpcksum;
687                 break;
688         default:
689                 return;
690         }
691         fprintf (stderr, "DEBUG: Looking for masquerading of port %d in %d entries\n", port, numpairs);
692         while (numpairs-- > 0) {
693                 if ((port >= portpairs [0]) && (port <= portpairs [1])) {
694                         //
695                         // Replace masqueraded address by 6bed4router's
696                         fprintf (stderr, "DEBUG: Passing traffic to masquerading address number %d\n", portpairs [2]);
697                         masquerade_address (v4dst6,
698                                 (struct in6_addr *) masqhost [portpairs [2]],
699                                 csum_field);
700                         //
701                         // Forward immediately, and return from this function
702 printf ("Writing Masqueraded IPv6, result = %zd\n",
703                         write (v6sox, &v4data6, sizeof (struct tun_pi) + v4datalen));
704                         return;
705                 }
706                 portpairs += 3;
707         }
708         //
709         // Silently skip the offered packet
710 }
711
712
713 /* 
714  * Forward a message received over the 6bed4 Network over IPv6.
715  * Note that existing checksums will work well, as only the
716  * Hop Limit has been altered, and this is not part of the
717  * checksum calculations.
718  */
719 void handle_4to6_plain_unicast (ssize_t v4datalen) {
720 printf ("Writing IPv6, result = %zd\n",
721         write (v6sox, &v4data6, sizeof (struct tun_pi) + v4datalen));
722 }
723
724
725 /*
726  * Forward a 6bed4 message to another 6bed4 destination address.
727  * Local address prefixes fc64:<netid>:<ipv4>::/64 are also relayed.
728  * Note that existing checksums will work well, as only the
729  * Hop Limit has been altered, and this is not part of the
730  * checksum calculations.
731  */
732 void relay_4to4_plain_unicast (uint8_t* data, ssize_t v4datalen, struct in6_addr *ip6) {
733         v4name.sin_port = htons (ip6->s6_addr [12] << 8 | ip6->s6_addr [13]);
734         uint8_t *addr = (uint8_t *) &v4name.sin_addr.s_addr;
735         addr [0] = (ip6->s6_addr [8] & 0xfc) | ip6->s6_addr [14] >> 6;
736         memcpy (addr + 1, ip6->s6_addr + 9, 3);
737 printf ("Relaying over 6bed4 Network to %d.%d.%d.%d:%d, result = %zd\n",
738 ((uint8_t *) &v4name.sin_addr.s_addr) [0],
739 ((uint8_t *) &v4name.sin_addr.s_addr) [1],
740 ((uint8_t *) &v4name.sin_addr.s_addr) [2],
741 ((uint8_t *) &v4name.sin_addr.s_addr) [3],
742 ntohs (v4name.sin_port),
743         sendto (v4sox,
744                         data, v4datalen,
745                         MSG_DONTWAIT,
746                         (struct sockaddr *) &v4name, sizeof (v4name)));
747 }
748
749
750 /* Receive a tunnel package, and route it to either the handler for the
751  * tunnel protocol, or to the handler that checks and then unpacks the
752  * contained IPv6.
753  */
754 void handle_4to6 (void) {
755         uint8_t buf [1501];
756         ssize_t buflen;
757         socklen_t adrlen = sizeof (v4name);
758         //
759         // Receive IPv4 package, which may be tunneled or a tunnel request
760         buflen = recvfrom (v4sox,
761                         v4data, MTU,
762                         MSG_DONTWAIT,
763                         (struct sockaddr *) &v4name, &adrlen
764                 );
765         if (buflen == -1) {
766                 printf ("%s: Error receiving IPv4-side package: %s",
767                                 program, strerror (errno));
768                 return;
769         }
770         if (buflen < sizeof (struct ip6_hdr)) {
771                 return;
772         }
773         if ((v4data [0] & 0xf0) != 0x60) {
774                 // Not an IPv6 packet
775                 return;
776         }
777         //
778         // Handle the tunneled IPv6 package (dependent on its class)
779         if ((v4v6nexthdr == IPPROTO_ICMPV6) &&
780                         (v4v6icmptype >= 133) && (v4v6icmptype <= 137)) {
781                 //
782                 // Not Plain: Router Adv/Sol, Neighbor Adv/Sol, Redirect
783                 if (v4v6hoplimit != 255) {
784                         return;
785                 }
786                 handle_4to6_nd (buflen);
787         } else if (is_mine (v4src6, v4dst6)) {
788                 handle_4to6_masquerading (buflen);
789         } else if ((v4dst6->s6_addr [0] != 0xff) && !(v4dst6->s6_addr [8] & 0x01)) {
790                 //
791                 // Plain Unicast
792                 if (is_local_override (v4dst6)) {
793                         handle_4to6_plain_unicast (buflen);
794                 } else if (validate_originator (v4src6)) {
795                         if (v4v6hoplimit-- <= 1) {
796                                 return;
797                         }
798                         if (is_6bed4 (v4dst6) || is_fc64 (v4dst6)) {
799                                 relay_4to4_plain_unicast (v4data, buflen, v4dst6);
800                         } else {
801                                 handle_4to6_plain_unicast (buflen);
802                         }
803                 } else if (is_6bed4 (v4src6)) {
804                         // The sender must not have kept NAT/firewall holes
805                         // open and should be instructed about a change in
806                         // its 6bed4 Link-Local Address.
807                         handle_6bed4_router_solicit ();
808                 }
809         } else {
810                 //
811                 // Plain Multicast
812                 //OPTIONAL// validate_originator, hoplimit, relay_mcast.
813                 return;
814         }
815 }
816
817
818 /* Receive an IPv6 package, check its address and pickup IPv4 address and
819  * port, then package it as a tunnel message and forward it to IPv4:port.
820  */
821 void handle_6to4 (void) {
822         uint16_t mqh;
823         //
824         // Receive the IPv6 package and ensure a consistent size
825         size_t rawlen = read (v6sox, &v6data6, sizeof (v6data6));
826         if (rawlen == -1) {
827                 return;         /* error reading, drop */
828         }
829         if (rawlen < sizeof (struct tun_pi) + sizeof (struct ip6_hdr) + 1) {
830                 return;         /* too small, drop */
831         }
832         if (v6tuncmd.proto != htons (ETH_P_IPV6)) {
833                 return;         /* no IPv6, drop */
834         }
835         if ((v6nexthdr == IPPROTO_ICMPV6) &&
836                         (v6icmptype >= 133) && (v6icmptype <= 137)) {
837                 return;         /* not plain IPv6, drop */
838         }
839         if (v6hoplimit-- <= 1) {
840                 // TODO: Send back an ICMPv6 error message
841                 return;         /* hop limit exceeded, drop */
842         }
843         if ((v6dst6->s6_addr [0] == 0xff) /* TODO:UDP_PORT_NOT_YET_FORCED_TO_EVEN || (v6dst6->s6_addr [8] & 0x01) */ ) {
844 printf ("Received multicast IPv6 data, flags=0x%04x, proto=0x%04x\n", v6tuncmd.flags, v6tuncmd.proto);
845                 //OPTIONAL// handle_6to4_plain_multicast ()
846                 return;         /* multicast, drop */
847         }
848 printf ("Received plain unicast IPv6 data, flags=0x%04x, proto=0x%04x\n", v6tuncmd.flags, v6tuncmd.proto);
849         //
850         // Replace masqueraded addresses configured with -m and its default ::1
851         //TODO// Better use the port number to find the find the masqhost
852         for (mqh=0; mqh<num_masqhost; mqh++) {
853                 if (memcmp (v6src6, masqhost [mqh], 16) == 0) {
854 printf ("Masqueraded sender address in 6to4 set to the client's 6bed4router address\n");
855                         uint16_t *csum_field = NULL;
856                         struct in6_addr masq_src;
857                         switch (v6nexthdr) {
858 #ifdef CHECKSUM_SCTP_WOULD_BE_LIKE_FOR_OTHERS
859                         case IPPROTO_SCTP:
860                                 csum_field = &v6sctpcksum;
861                                 break;
862 #endif
863                         case IPPROTO_TCP:
864                                 csum_field = &v6tcpcksum;
865                                 break;
866                         case IPPROTO_UDP:
867                                 csum_field = &v6udpcksum;
868                                 break;
869                         case IPPROTO_ICMPV6:
870                                 csum_field = &v6icmpcksum;
871                                 break;
872                         default:
873                                 continue;
874                         }
875                         //
876                         // Construct v6src6 from v6dst6, ending in 14 zero bits
877                         memcpy (&masq_src, v6dst6, 16);
878                         masq_src.s6_addr16 [7] &= htons (0xc000);
879                         fprintf (stderr, "Masquerading cksum.old = 0x%04x, ", ntohs (*csum_field));
880                         masquerade_address (v6src6, &masq_src, csum_field);
881                         fprintf (stderr, "cksum.new = 0x%04x\n", ntohs (*csum_field));
882                         break;
883                 }
884         }
885         //
886         // Ensure that the incoming IPv6 address is properly formatted
887         // Note that this avoids access to ::1/128, fe80::/10, fec0::/10
888 #ifndef TODO_PERMIT_BOUNCE_FOR_32BIT_PREFIX
889         if (memcmp (v6dst6, &v6listen, 8) != 0) {
890                 return;
891         }
892 #else
893         if (v6dst6->s6_addr32 [0] != v6listen.s6_addr32 [0]) {
894                 // Mismatch /32 so this is not going to fly (anywhere)
895                 return;
896         } else if (v6dst6->s6_addr32 [1] != v6listen.s6_addr32 [1]) {
897                 // Match /32 but mismatch /64 -- relay to proper fallback
898                 // that fc64::/16 is not welcome in 6to4 processing
899                 //TODO//OVER_6bed4// relay_6to6_plain_unicast (v6data, rawlen - sizeof (struct tun_pi), v6dst6);
900         }
901 #endif
902         //
903         // Harvest socket address data from destination IPv6, then send
904         relay_4to4_plain_unicast (v6data, rawlen - sizeof (struct tun_pi), v6dst6);
905 }
906
907
908 /* Run the daemon core code, passing information between IPv4 and IPv6 and
909  * responding to tunnel requests if so requested.
910  */
911 void run_daemon (void) {
912         fd_set io;
913         FD_ZERO (&io);
914         FD_SET (v4sox, &io);
915         FD_SET (v6sox, &io);
916         int nfds = (v4sox < v6sox)? (v6sox + 1): (v4sox + 1);
917         while (1) {
918                 select (nfds, &io, NULL, NULL, NULL);
919                 if (FD_ISSET (v4sox, &io)) {
920                         handle_4to6 ();
921                 } else {
922                         FD_SET (v4sox, &io);
923                 }
924                 if (FD_ISSET (v6sox, &io)) {
925                         handle_6to4 ();
926                 } else {
927                         FD_SET (v6sox, &io);
928                 }
929 fflush (stdout);
930         }
931 }
932
933
934 /* Option descriptive data structures */
935
936 char *short_opt = "l:L:d:hit:u:s:m:";
937
938 struct option long_opt [] = {
939         { "v4listen", 1, NULL, 'l' },
940         { "v6prefix", 1, NULL, 'L' },
941         { "tundev", 1, NULL, 'd' },
942         { "help", 0, NULL, 'h' },
943         { "icmp", 0, NULL, 'i' },
944         { "tcp", 1, NULL, 't' },
945         { "udp", 1, NULL, 'u' },
946         { "sctp", 1, NULL, 's' },
947         { "masqhost", 1, NULL, 'm' },
948         // { "fallback4", 1 NULL, 'f' },
949         // { "fallback6", 1, NULL, 'F' },
950         { NULL, 0, NULL, 0 }    /* Array termination */
951 };
952
953 /* Parse commandline arguments (and start to process them).
954  * Return 1 on success, 0 on failure.
955  */
956 int process_args (int argc, char *argv []) {
957         int ok = 1;
958         int help = (argc == 1);
959         int done = 0;
960         int opt;
961         while (!done) {
962                 switch (opt = getopt_long (argc, argv, short_opt, long_opt, NULL)) {
963                 case -1:
964                         done = 1;
965                         if (optind != argc) {
966                                 fprintf (stderr, "%s: Extra arguments not permitted: %s...\n", program, argv [optind]);
967                                 ok = 0;
968                         }
969                         break;
970                 case 'l':
971                         if (v4sox != -1) {
972                                 ok = 0;
973                                 fprintf (stderr, "%s: Only one -l argument is permitted\n", program);
974                                 break;
975                         }
976                         v4server = optarg;
977                         if (inet_pton (AF_INET, optarg, &v4name.sin_addr) <= 0) {
978                                 ok = 0;
979                                 fprintf (stderr, "%s: Failed to parse IPv4 address %s\n", program, optarg);
980                                 break;
981                         }
982                         memcpy (&v4listen, &v4name.sin_addr, 4);
983                         v4sox = socket (AF_INET, SOCK_DGRAM, 0);
984                         if (v4sox == -1) {
985                                 ok = 0;
986                                 fprintf (stderr, "%s: Failed to allocate UDPv4 socket: %s\n", program, strerror (errno));
987                                 break;
988                         }
989                         if (bind (v4sox, (struct sockaddr *) &v4name, sizeof (v4name)) != 0) {
990                                 ok = 0;
991                                 fprintf (stderr, "%s: Failed to bind to UDPv4 %s:%d: %s\n", program, optarg, ntohs (v4name.sin_port), strerror (errno));
992                                 break;
993                         }
994                         break;
995                 case 'L':
996                         if (v6server) {
997                                 ok = 0;
998                                 fprintf (stderr, "%s: Only one -L argument is permitted\n", program);
999                                 break;
1000                         }
1001                         char *slash64 = strchr (optarg, '/');
1002                         if (!slash64 || strcmp (slash64, "/64") != 0) {
1003                                 ok = 0;
1004                                 fprintf (stderr, "%s: The -L argument must be an explicit /64 prefix and not %s\n", program, slash64? slash64: "implied");
1005                                 break;
1006                         }
1007                         *slash64 = 0;
1008                         v6server = strdup (optarg);
1009                         *slash64 = '/';
1010                         v6prefix = optarg;
1011                         if (!v6server || (inet_pton (AF_INET6, v6server, &v6listen) <= 0)) {
1012                                 ok = 0;
1013                                 fprintf (stderr, "%s: Failed to parse IPv6 prefix %s\n", program, optarg);
1014                                 break;
1015                         }
1016                         if (v6listen.s6_addr32 [2] || v6listen.s6_addr32 [3]) {
1017                                 ok = 0;
1018                                 fprintf (stderr, "%s: IPv6 prefix contains bits beyond its /64 prefix: %s\n", program, optarg);
1019                                 break;
1020                         }
1021                         break;
1022                 case 'd':
1023                         if (v6sox != -1) {
1024                                 ok = 0;
1025                                 fprintf (stderr, "%s: Multiple -d arguments are not permitted\n", program);
1026                                 break;
1027                         }
1028                         v6sox = open (optarg, O_RDWR);
1029                         if (v6sox == -1) {
1030                                 ok = 0;
1031                                 fprintf (stderr, "%s: Failed to open tunnel device %s: %s\n", program, optarg, strerror (errno));
1032                                 break;
1033                         }
1034                         break;
1035                 case 's':
1036                 case 't':
1037                 case 'u':
1038                 case 'i':
1039                         // Masqueraded port (range) for SCTP, TCP, UDP
1040                         //TODO// Should we support ICMPv6 as well? [honeypots]
1041                         if (num_masqhost == 0) {
1042                                 //TODO// Reference v6listen instead of ::1
1043                                 inet_pton (AF_INET6, "::1", masqhost [0]);
1044                                 num_masqhost = 1;
1045                         }
1046                         // Temporary variables in local scope
1047                         if (opt == 'i') {
1048                                 if (icmp_num_portpairs > 0) {
1049                                         fprintf (stderr, "%s: Only one ICMP masquerading setting is possible\n", program);
1050                                         ok = 0;
1051                                         break;
1052                                 }
1053                                 icmp_portpairs [2] = num_masqhost - 1;
1054                                 icmp_num_portpairs++;
1055                         } else {
1056                                 unsigned long fromport, toport;
1057                                 uint16_t *portpairs;
1058                                 errno = 0;
1059                                 if (*optarg != ':') {
1060                                         fromport = strtoul (optarg, &optarg, 10);
1061                                 } else {
1062                                         fromport = 1;
1063                                 }
1064                                 if (*optarg != ':') {
1065                                         toport = fromport;
1066                                 } else if (*++optarg) {
1067                                         toport = strtoul (optarg, &optarg, 10);
1068                                 } else {
1069                                         toport = 65535;
1070                                 }
1071                                 if (errno || *optarg) {
1072                                         fprintf (stderr, "%s: Failed to parse port or port:port\n", program);
1073                                         ok = 0;
1074                                         break;
1075                                 }
1076                                 if ((fromport < 1) || (fromport > toport) || (toport > 65535)) {
1077                                         fprintf (stderr, "%s: Invalid port or port range\n", program);
1078                                         ok = 0;
1079                                         break;
1080                                 }
1081                                 if (++num_masqportpairs [opt-'s'] >= MAXNUM_PORTPAIRS) {
1082                                         fprintf (stderr, "%s: You cannot define so many ports / port pairs\n", program);
1083                                         ok = 0;
1084                                         break;
1085                                 }
1086                                 portpairs = &masqportpairs [opt-'s'][3*(num_masqportpairs [opt-'s']-1)];
1087                                 portpairs [0] = fromport;
1088                                 portpairs [1] = toport;
1089                                 portpairs [2] = num_masqhost-1;
1090                         }
1091                         break;
1092                 case 'm':
1093                         // Masqueraded host for TCP, UDP, SCTP (default is ::1)
1094                         if (++num_masqhost >= MAXNUM_MASQHOST) {
1095                                 fprintf (stderr, "%s: No more than %d masquering hosts can be specified\n", program, MAXNUM_MASQHOST);
1096                                 ok = 0;
1097                                 break;
1098                         }
1099                         if (inet_pton (AF_INET6, optarg, masqhost [num_masqhost]) != 1) {
1100                                 fprintf (stderr, "%s: Unsupported masquerading host \"%s\"\n", program, optarg);
1101                                 ok = 0;
1102                                 break;
1103                         }
1104                         num_masqhost++;
1105                         break;
1106                 // case 'f':
1107                 // case 'F':
1108                 //      // Fallback addresses for IPv4, IPv6
1109                 //      ok = 0; //TODO:IMPLEMENT//
1110                 //      help = 1;
1111                 //      break;
1112                 default:
1113                         ok = 0;
1114                         /* continue into 'h' to produce usage information */
1115                 case 'h':
1116                         help = 1;
1117                         break;
1118                 }
1119                 if (help || !ok) {
1120                         done = 1;
1121                 }
1122         }
1123         if (help) {
1124 #ifdef HAVE_SETUP_TUNNEL
1125                 fprintf (stderr, "Usage: %s [-d /dev/tunX] -l <v4server> -L <v6prefix>/64\n       %s -h\n", program, program);
1126                 fprintf (stderr, "\tUse -s|-t|-u to masquerade a port (range) to last -m host or ::1\n");
1127 #else
1128                 fprintf (stderr, "Usage: %s -d /dev/tunX -l <v4server> -L <v6prefix>/64\n       %s -h\n", program, program);
1129                 fprintf (stderr, "\tUse -s|-t|-u to masquerade a port (range) to last -m host of ::1\n");
1130 #endif
1131                 return ok;
1132         }
1133         if (!ok) {
1134                 return 0;
1135         }
1136         if (v4sox == -1) {
1137                 fprintf (stderr, "%s: Use -l to specify an IPv4 address for the tunnel interface\n", program);
1138                 return 0;
1139         }
1140         if (!v6server) {
1141                 fprintf (stderr, "%s: Use -L to specify a /64 prefix on the IPv6 side\n", program);
1142                 return 0;
1143         }
1144 #ifdef HAVE_SETUP_TUNNEL
1145         if (v6sox == -1) {
1146                 if (geteuid () != 0) {
1147                         fprintf (stderr, "%s: You should be root, or use -d to specify an accessible tunnel device\n", program);
1148                         return 0;
1149                 }
1150                 ok = setup_tunnel ();
1151         }
1152 #else /* ! HAVE_SETUP_TUNNEL */
1153         if (v6sox == -1) {
1154                 fprintf (stderr, "%s: You must specify a tunnel device with -d that is accessible to you\n", program);
1155                 return 0;
1156         }
1157 #endif /* HAVE_SETUP_TUNNEL */
1158         return ok;
1159 }
1160
1161
1162 /* The main program parses commandline arguments and forks off the daemon
1163  */
1164 int main (int argc, char *argv []) {
1165         //
1166         // Initialise
1167         program = argv [0];
1168         memset (&v4name, 0, sizeof (v4name));
1169         memset (&v6name, 0, sizeof (v6name));
1170         v4name.sin_family  = AF_INET ;
1171         v6name.sin6_family = AF_INET6;
1172         v4name.sin_port = htons (UDP_PORT_6BED4);   /* 6BED4 standard port */
1173         v4tunpi6.flags = 0;
1174         v4tunpi6.proto = htons (ETH_P_IPV6);
1175         //
1176         // Parse commandline arguments
1177         if (!process_args (argc, argv)) {
1178                 exit (1);
1179         }
1180         //
1181         // Setup a few addresses for later comparison/reproduction
1182         //  * lladdr_6bed4 is the 6bed4 Link-Local Address
1183         //  * v6listen_complete is the router's full IPv6 address (with if-id)
1184         //  * v6listen_linklocal_complete is fe80::/64 plus the router's if-id
1185         // A few others have already been setup at this time
1186         //  * v6listen is the router's 6bed4 prefix ending in 64 zero bits
1187         //  * v6listen_linklocal is the address fe80::/128
1188         //
1189         lladdr_6bed4 [0] = UDP_PORT_6BED4 & 0xff;
1190         lladdr_6bed4 [1] = UDP_PORT_6BED4 >> 8;
1191         memcpy (lladdr_6bed4 + 2, (uint8_t *) &v4name.sin_addr, 4);
1192         addr_6bed4 (&v6listen_complete, 0);
1193
1194         memcpy (v6listen_linklocal_complete, v6listen_linklocal, 8);
1195         memcpy (v6listen_linklocal_complete + 8, &v6listen_complete.s6_addr [8], 8);
1196 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]);
1197 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]));
1198 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]));
1199 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]));
1200 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]));
1201         //
1202         // Start the main daemon process
1203 #ifdef SKIP_TESTING_KLUDGE_IN_FOREGROUND
1204         switch (fork ()) {
1205         case -1:                /* Error forking */
1206                 fprintf (stderr, "%s: Failed to fork: %s\n", program, strerror (errno));
1207                 exit (1);
1208         case 0:                 /* Child process */
1209                 close (0);
1210                 //TODO: tmp.support for ^printf// close (1);
1211                 close (2);
1212                 setsid ();
1213                 run_daemon ();
1214                 break;
1215         default:                /* Parent process */
1216                 close (v4sox);
1217                 close (v6sox);
1218                 break;
1219         }
1220 #else
1221         run_daemon ();
1222 #endif
1223         //
1224         // Report successful creation of the daemon
1225         return 0;
1226 }