rework and refactor; ipv4 working
[rrq/rrqnet.git] / rrqnet.c
1 // This program is a UDP based tunneling of stdin/out Ethernet packets.
2 //
3 // A rrqnet program is a bi-directional networking plug that channels
4 // packets between a UDP port and stdin/out. It is configured on the
5 // command line with channel rules that declares which remotes it may
6 // communicate with. Allowed remotes are specified in the format
7 // "ip[/n][:port][=key]", to indicate which subnet and port to accept,
8 // and nominating the associated keyfile to use for channel
9 // encryption.
10 //
11 // The program maintains a table of actualized connections, as an
12 // association between MAC addresses and IP:port addresses. This table
13 // is used for resolving destination for outgoing packets, including
14 // the forwarding of broadcasts.
15 //
16
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <linux/if.h>
20 #include <linux/if_tun.h>
21 #include <stddef.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/ioctl.h>
26 #include <sys/stat.h>
27 #include <sys/time.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <time.h>
31 #include <unistd.h>
32
33 #include "htable.h"
34 #include "queue.h"
35
36 //// Data structures
37
38 // "Private Shared Key" details.
39 struct PSK {
40     char *keyfile;
41     unsigned int seed;          // Encryption seed
42     unsigned char *key;         // Encryption key
43     unsigned int key_length;    // Encryption key length
44 };
45
46 // Compacted IP address ipv4/ipv6
47 struct CharAddr {
48     int width; // 4=ipv4 and 16=ipv6
49     union {
50         unsigned char bytes[16];
51         struct in_addr in4; 
52         struct in6_addr in6;
53     };
54 };
55
56 // Details of channel rules.
57 struct Allowed {
58     char *source;               // Orginal rule
59     struct CharAddr addr;
60     unsigned int bits;          // Bits of IP prefix
61     unsigned short port;        // Port (0=any)
62     struct PSK psk;             // Associated key
63     htable ignored_mac;         // MAC to ignore by this spec
64 };
65
66 // Details of actualized connections.
67 struct Remote {
68     struct SockAddr uaddr;      // The remote IP address
69     struct SockAddr laddr;      // The local IP for this remote
70     int ifindex;                // The local interface index
71     struct Allowed *spec;       // Rule being instantiated
72     struct timeval rec_when;    // Last received packet time, in seconds
73 };
74
75 // Details of an interface at a remote.
76 struct Interface  {
77     unsigned char mac[6];       // MAC address used last (key for by_mac table)
78     struct timeval rec_when;    // Last packet time, in seconds
79     struct Remote *remote;
80 };
81
82 // Maximal packet size .. allow for jumbo frames (9000)
83 #define BUFSIZE 10000
84
85 typedef struct _PacketItem {
86     QueueItem base;
87     int fd;
88     struct SockAddr src; // the remote IP for this packet
89     union {
90         struct in_pktinfo in4;
91         struct in6_pktinfo in6;
92     } dstinfo;          // The PKTINFO for this packet
93     ssize_t len;
94     unsigned char buffer[ BUFSIZE ];
95 } PacketItem;
96
97 typedef struct _ReaderData {
98     int fd;
99 } ReaderData;
100
101 // heartbeat interval, in seconds
102 #define HEARTBEAT 30
103 #define HEARTBEAT_MICROS ( HEARTBEAT * 1000000 )
104
105 // Macros for timing, for struct timeval variables
106 #define TIME_MICROS(TM) (((int64_t) (TM)->tv_sec * 1000000) + (TM)->tv_usec )
107 #define DIFF_MICROS(TM1,TM2) ( TIME_MICROS(TM1) - TIME_MICROS(TM2) )
108
109 // RECENT_MICROS(T,M) is the time logic for requiring a gap time (in
110 // milliseconds) before shifting a MAC to a new remote. The limit is
111 // 6s for broadcast and 20s for unicast.
112 #define RECENT_MICROS(T,M) ((M) < ((T)? 6000000 : 20000000 ))
113
114 // VERYOLD_MICROSS is used for discarding downlink remotes whose latest
115 // activity is older than this.
116 #define VERYOLD_MICROS 180000000
117
118 ////////// Variables
119
120 // Allowed remote specs are held in a table sorted by IP prefix.
121 static struct {
122     struct Allowed **table;
123     unsigned int count;
124 } allowed;
125
126 // Actual remotes are kept in a hash table keyed by their +uaddr+
127 // field, and another hash table keps Interface records for all MAC
128 // addresses sourced from some remote, keyed by their +mac+ field. The
129 // latter is used both for resolving destinations for outgoing
130 // packets, and for limiting broadcast cycles. The former table is
131 // used for limiting incoming packets to allowed sources, and then
132 // decrypt the payload accordingly.
133 static int hashcode_uaddr(struct _htable *table,unsigned char *key);
134 static int hashcode_mac(struct _htable *table,unsigned char *key);
135 static struct {
136     htable by_mac; // struct Interface hash table
137     htable by_addr; // struct Remote hash table
138 } remotes = {
139     .by_mac = HTABLEINIT( struct Interface, mac, hashcode_mac ),
140     .by_addr = HTABLEINIT( struct Remote, uaddr, hashcode_uaddr )
141 };
142
143 #define Interface_LOCK if ( pthread_mutex_lock( &remotes.by_mac.lock ) ) { \
144         perror( "FATAL" ); exit( 1 ); }
145
146 #define Interface_UNLOCK if (pthread_mutex_unlock( &remotes.by_mac.lock ) ) { \
147         perror( "FATAL" ); exit( 1 ); }
148
149 #define Interface_FIND(m,r) \
150     htfind( &remotes.by_mac, m, (unsigned char **)&r )
151
152 #define Interface_ADD(r) \
153     htadd( &remotes.by_mac, (unsigned char *)r )
154
155 #define Interface_DEL(r) \
156     htdelete( &remotes.by_mac, (unsigned char *) r )
157
158 #define Remote_LOCK if ( pthread_mutex_lock( &remotes.by_addr.lock ) ) { \
159         perror( "FATAL" ); exit( 1 ); }
160
161 #define Remote_UNLOCK if ( pthread_mutex_unlock( &remotes.by_addr.lock ) ) { \
162         perror( "FATAL" ); exit( 1 ); }
163
164 #define Remote_FIND(a,r) \
165     htfind( &remotes.by_addr, (unsigned char *)a, (unsigned char **) &r )
166
167 #define Remote_ADD(r) \
168     htadd( &remotes.by_addr, (unsigned char *) r )
169
170 #define Remote_DEL(r) \
171     htdelete( &remotes.by_addr, (unsigned char *) r )
172
173 #define Ignored_FIND(a,m,x)                             \
174     htfind( &a->ignored_mac, m, (unsigned char **)&x )
175
176 #define Ignored_ADD(a,x) \
177     htadd( &a->ignored_mac, (unsigned char *)x )
178
179 // Input channels
180 static int stdio = 0; // Default is neither stdio nor tap
181 static char *tap = 0; // Name of tap, if any, or "-" for stdio
182 static int tap_fd = 0; // Also used for stdin in stdio mode
183 static int udp_fd;
184 static int udp_port;
185 static int threads_count = 0;
186 static int buffers_count = 0;
187
188 // Setup for multicast channel
189 static struct {
190     struct ip_mreqn group;
191     struct SockAddr sock;
192     int fd;
193     struct PSK psk;
194 } mcast;
195
196 // Flag to signal the UDP socket as being ipv6 or not (forced ipv4)
197 static int udp6 = 1;
198
199 // The given UDP source address, if any
200 static struct {
201     int family;
202     unsigned char address[16];
203 } udp_source;
204
205 // Flag to indicate tpg transport patch = avoid UDP payload of 1470
206 // bytes by adding 2 tag-along bytes
207 static int tpg_quirk = 0;
208
209 // Flag whether to make some stderr outputs or not.
210 // 1 = normal verbosity, 2 = more output, 3 = source debug level stuff
211 static int verbose;
212
213 // Note: allows a thread to lock/unlock recursively
214 static pthread_mutex_t crypting = PTHREAD_MUTEX_INITIALIZER;
215
216 // Note: allows a thread to lock/unlock recursively
217 static pthread_mutex_t printing = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
218
219 #define PRINTLOCK \
220     if ( pthread_mutex_lock( &printing ) ) { perror( "FATAL" ); exit(1); }
221
222 #define PRINTUNLOCK \
223     if ( pthread_mutex_unlock( &printing ) ) { perror( "FATAL" ); exit(1); }
224
225 #define PRINT( X ) { PRINTLOCK; X; PRINTUNLOCK; }
226
227 #define VERBOSEOUT(fmt, ...) \
228     if ( verbose >= 1 ) PRINT( fprintf( stderr, fmt, ##__VA_ARGS__ ) )
229
230 #define VERBOSE2OUT(fmt, ...) \
231     if ( verbose >= 2 ) PRINT( fprintf( stderr, fmt, ##__VA_ARGS__ ) )
232
233 #define VERBOSE3OUT(fmt, ...) \
234     if ( verbose >= 3 ) PRINT( fprintf( stderr, fmt, ##__VA_ARGS__ ) )
235
236 // The actual name of this program (argv[0])
237 static unsigned char *progname;
238
239 // Compute a hashcode for the given SockAddr key
240 static int hashcode_uaddr(
241     __attribute__((unused)) struct _htable *table,unsigned char *key)
242 {
243     struct SockAddr *s = (struct SockAddr *) key;
244     key = (unsigned char*) &s->in;
245     unsigned char *e = key + ( ( s->in.sa_family == AF_INET )?
246                                sizeof( struct sockaddr_in ) :
247                                sizeof( struct sockaddr_in6 ) );
248     int x = 0;
249     while ( key < e ) {
250         x += *(key++);
251     }
252     return x;
253 }
254
255 // Compute a hashcode for the given MAC addr key
256 static int hashcode_mac(struct _htable *table,unsigned char *key) {
257     int x = 0;
258     int i = 0;
259     if ( table->size == 256 ) {
260         for ( ; i < 6; i++ ) {
261             x += *(key++);
262         }
263         return x;
264     }
265     uint16_t *p = (uint16_t *) key;
266     for ( ; i < 3; i++ ) {
267         x += *( p++ );
268     }
269     return x;
270 }
271
272 // Make a text representation of bytes as ipv4 or ipv6
273 static char *inet_nmtoa(unsigned char *b,int w) {
274     static char buffer[20000];
275     int i = 0;
276     char * p = buffer;
277     if ( w == 4 ) {
278         sprintf( p,"%d.%d.%d.%d", b[0], b[1], b[2], b[3] );
279     } else if ( w == 16 ){
280         sprintf( p,
281   "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
282                  b[0], b[1], b[2], b[3],
283                  b[4], b[5], b[6], b[7],
284                  b[8], b[9], b[10], b[11],
285                  b[12], b[13], b[14], b[15] );
286     } else {
287         VERBOSE3OUT( "HEX data of %d bytes\n", w );
288         for ( ; i < w && i < 19000; i++, p += 3 ) {
289             sprintf( p, "%02x:", b[i] );
290         }
291         if ( w > 0 ) {
292             *(--p) = 0;
293         }
294     }
295     return buffer;
296 }
297
298 // Form a MAC address string from 6 MAC address bytes, into one of the
299 // 4 static buffer, whose use are cycled.
300 static char *inet_mtoa(unsigned char *mac) {
301     static char buffer[4][30];
302     static int i = 0;
303     if ( i > 3 ) {
304         i = 0;
305     }
306     sprintf( buffer[i], "%02x:%02x:%02x:%02x:%02x:%02x",
307              mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] );
308     return buffer[i++];
309 }
310
311 // Form a socket address string from Sockaddr, into one of the
312 // 4 static buffer, whose use are cycled.
313 static char *inet_stoa(struct SockAddr *a) {
314     static char buffer[1000];
315     static char out[4][1000];
316     static int i = 0;
317     if ( i > 3 ) {
318         i = 0;
319     }
320     if ( a->in.sa_family == AF_INET ) {
321         sprintf( out[i], "%s:%d",
322                  inet_ntop( AF_INET, &a->in4.sin_addr, buffer, 100 ),
323                  ntohs( a->in4.sin_port ) );
324     } else if ( a->in.sa_family == AF_INET6 ) {
325         sprintf( out[i], "[%s]:%d",
326                  inet_ntop( AF_INET6, &a->in6.sin6_addr, buffer, 100 ),
327                  ntohs( a->in6.sin6_port ) );
328     } else {
329         sprintf( out[i], "<tap/stdio>" );
330     }
331     return out[i++];
332 }
333
334 // Debugging: string representation of an Allowed record.
335 static char *show_allowed(struct Allowed *a) {
336     static char buffer[20000];
337     if ( a == 0 ) {
338         sprintf( buffer, "{tap/stdio}" );
339     } else {
340         sprintf( buffer, "%hd (%d) %s %p",
341                  a->port, a->bits, inet_nmtoa( a->addr.bytes, a->addr.width ),
342                  a->psk.key );
343     }
344     return buffer;
345 }
346
347 // Recognize uplink specification
348 static int is_uplink(struct Allowed *a) {
349     return a->bits == (unsigned int) ( a->addr.width * 8 ) && a->port != 0;
350 }
351
352 // Add a new Interface for a Remote. If non-null, the interface is
353 // also added to the interface table.
354 static struct Interface *add_interface(unsigned char *mac,struct Remote *r) {
355     struct Interface *x = calloc( 1, sizeof( struct Interface ) );
356     memcpy( x->mac, mac, sizeof( x->mac ) );
357     x->remote = r;
358     if ( r ) {
359         Interface_ADD( x );
360     }
361     return x;
362 }
363
364 // Add a new remote for a given address and spec.
365 static struct Remote *add_remote(struct SockAddr *a,struct Allowed *s) {
366     struct Remote *r = calloc( 1, sizeof( struct Remote ) );
367     if ( a != 0 ) {
368         memcpy( &r->uaddr, a, sizeof( r->uaddr ) );
369     }
370     r->spec = s;
371     VERBOSE2OUT( "add_remote %s from spec: %s\n",
372                  inet_stoa( &r->uaddr ),
373                  ( s == 0 )? ( (a == 0)? "{tap/stdio}" : "{multicast}" )
374                  : show_allowed( s ) );
375     Remote_ADD( r );
376     return r;
377 }
378
379 // Add a new ignored interface on a channel
380 static int add_ignored(struct Allowed *link,unsigned char *mac) {
381     struct Interface *x = add_interface( mac, 0 );
382     if ( x == 0 ) {
383         return 1; // error: out of memory
384     }
385     Ignored_ADD( link, x );
386     return 0;
387 }
388
389 // Parse ignored interfaces
390 // Comma separated list of MAC addresses
391 static int parse_ignored_interfaces(char *arg,struct Allowed *link) {
392     int a, b, c, d, e, f, g;
393     while ( *arg ) {
394         if ( sscanf( arg,"%x:%x:%x:%x:%x:%x%n",&a,&b,&c,&d,&e,&f,&g ) != 6 ) {
395             // Not a mac addr
396             return 1;
397         }
398         if ( (a|b|c|d|e|f) & ~0xff ) {
399             return 1; // some %x is not hex
400         }
401         unsigned char mac[6] = { a, b, c, d, e, f };
402         if ( add_ignored( link, mac ) ) {
403             // Out of memory ??
404             return 1;
405         }
406         VERBOSEOUT( "Ignoring: %s on channel %s\n",
407                     inet_mtoa( mac ), link->source );
408         arg += g;
409         if ( *arg == 0 ) {
410             break;
411         }
412         if ( *(arg++) != ',' ) {
413             return 1; // Not comma separated
414         }
415     }
416     return 0;
417 }
418
419 //** IP address parsing utility
420 // Clear bits after <bits>
421 static void clearbitsafter(struct CharAddr *a,unsigned int bits) {
422     unsigned int max = a->width * 8;
423     int i;
424     for ( i = a->width; i < 16; i++ ) {
425         a->bytes[ i ] = 0;
426     }
427     for ( i = a->width - 1; i >= 0; i--, max -= 8 ) {
428         if ( max - 8 < bits ) {
429             break;
430         }
431         a->bytes[ i ] = 0;
432     }
433     if ( i >= 0 && max >= bits ) {
434         a->bytes[ i ] &= ( 0xFF << ( bits - max ) );
435     }
436 }
437
438 //** IP address parsing utility
439 // Find the PSK for the given +file+ in the +loaded+ table (of +count+ size)
440 static struct PSK *findLoadedKeyfile(char *file,struct PSK *loaded,int count) {
441     VERBOSE3OUT( "find %s\n", file );
442     for ( count--; count >= 0; count-- ) {
443         if ( strcmp( file, loaded[ count ].keyfile ) ) {
444             VERBOSE3OUT( "found %d\n", count );
445             return &loaded[ count ];
446         }
447     }
448     VERBOSE3OUT( "found nothing\n" );
449     return 0;
450 }
451
452 //** IP address parsing utility
453 // Load a key file into dynamically allocated memory, and update the
454 // given PSK header for it.
455 static void loadkey(struct PSK *psk) {
456     static struct PSK *loaded = 0;
457     static int count = 0;
458     if ( psk->keyfile == 0 ) {
459         return;
460     }
461     struct PSK *old = findLoadedKeyfile( psk->keyfile, loaded, count );
462     if ( old ) {
463         memcpy( psk, old, sizeof( struct PSK ) );
464         return;
465     }
466     int e;
467     unsigned char *p;
468     int n;
469     struct stat filestat;
470     psk->keyfile = strdup( psk->keyfile );
471     int fd = open( (char*) psk->keyfile, O_RDONLY );
472     psk->seed = 0;
473     if ( fd < 0 ) {
474         perror( "open key file" );
475         exit( 1 );
476     }
477     if ( fstat( fd, &filestat ) ) {
478         perror( "stat of key file" );
479         exit( 1 );
480     }
481     psk->key_length = filestat.st_size;
482     if ( psk->key_length < 256 ) {
483         fprintf( stderr, "Too small key file: %d %s\n", psk->key_length,
484                  psk->keyfile );
485         exit( 1 );
486     }
487     psk->key = malloc( psk->key_length );
488     if ( psk->key == 0 ) {
489         fprintf( stderr, "Cannot allocate %d bytes for %s\n",
490                  psk->key_length, psk->keyfile );
491         exit( 1 );
492     }
493     e = psk->key_length;
494     p = psk->key;
495     while ( ( n = read( fd, p, e ) ) > 0 ) {
496         e -= n;
497         p += n;
498     }
499     close( fd );
500     if ( e != 0 ) {
501         fprintf( stderr, "Failed loading key %s\n", psk->keyfile );
502         exit( 1 );
503     }
504     for ( e = 0; (unsigned) e < psk->key_length; e++ ) {
505         psk->seed += psk->key[ e ];
506     }
507     if ( psk->seed == 0 ) {
508         fprintf( stderr, "Bad key %s; adds up to 0\n", psk->keyfile );
509         exit( 1 );
510     }
511     count++;
512     if ( loaded ) {
513         loaded = realloc( loaded, ( count * sizeof( struct PSK ) ) );
514     } else {
515         loaded = malloc( sizeof( struct PSK ) );
516     }
517     memcpy( &loaded[ count-1 ], psk, sizeof( struct PSK ) );
518     VERBOSE3OUT( "%d: %s %d %p %d\n", count-1, psk->keyfile, psk->seed,
519                  psk->key, psk->key_length );
520 }
521
522 //** IP address parsing utility
523 // Fill out a CharAddr and *port from a SockAddr
524 static void set_charaddrport(
525     struct CharAddr *ca,unsigned short *port,struct SockAddr *sa)
526 {
527     memset( ca, 0, sizeof( struct CharAddr ) );
528     ca->width = ( sa->in.sa_family == AF_INET )? 4 : 16;
529     if ( ca->width == 4 ) {
530         memcpy( &ca->in4, &sa->in4.sin_addr, 4 );
531         *port = ntohs( sa->in4.sin_port );
532     } else {
533         memcpy( &ca->in6, &sa->in6.sin6_addr, 16 );
534         *port = ntohs( sa->in6.sin6_port );
535     }
536 }
537
538 //** IP address parsing utility
539 // Fill out a SockAddr from a CharAddr and port
540 static void set_sockaddr(struct SockAddr *sa,struct CharAddr *ca,int port) {
541     memset( sa, 0, sizeof( struct SockAddr ) );
542     if ( ca->width == 4 ) {
543         sa->in4.sin_family = AF_INET;
544         sa->in4.sin_port = htons( port );
545         memcpy( &sa->in4.sin_addr, &ca->in4, 4 );
546     } else {
547         sa->in6.sin6_family = AF_INET6;
548         sa->in6.sin6_port = htons( port );
549         memcpy( &sa->in6.sin6_addr, &ca->in6, 16 );
550     }
551 }
552
553 //** IP address parsing utility
554 // Capture an optional port sub phrase [:<port>]
555 static int parse_port(char *port,struct Allowed *into) {
556     into->port = 0;
557     if ( port ) {
558         *(port++) = 0;
559         int p;
560         if ( sscanf( port, "%d", &p ) != 1 || p < 1 || p > 65535 ) {
561             // Bad port number
562             return 1;
563         }
564         into->port = p;
565     }
566     return 0;
567 }
568
569 //** IP address parsing utility
570 // Capture an optional bits sub phrase [/<bits>]
571 static int parse_bits(char *bits,int max,struct Allowed *into) {
572     into->bits = max;
573     if ( bits ) {
574         *(bits++) = 0;
575         int b;
576         if ( sscanf( bits, "%d", &b ) != 1 || b < 0 || b > max ) {
577             return 1;
578         }
579         into->bits = b;
580     }
581     return 0;
582 }
583
584 //** IP address parsing utility
585 // Parse a command line argument as a declaration of an allowed
586 // remote into the given <addr>.
587 // Return 0 if ok and 1 otherwise
588 // Formats: <ipv4-address>[/<bits>][:<port>][=keyfile]
589 // Formats: <ipv6-address>[/<bits>][=keyfile]
590 // Formats: \[<ipv6-address>[/<bits>]\][:<port>][=keyfile]
591 // Formats: hostname:port[=keyfile]
592 static int parse_allowed(char *arg,struct Allowed *into) {
593     static char buffer[10000];
594     int n = strlen( arg );
595     if ( n > 9000 ) {
596         return 1; // excessively large argument
597     }
598     strcpy( buffer, arg );
599     into->source = arg;
600     char * keyfile = strchr( buffer, '=' );
601     if ( keyfile ) {
602         *(keyfile++) = 0;
603         into->psk.keyfile = keyfile;
604     }
605 #define B(b) b, b+1, b+2, b+3
606     if ( sscanf( buffer, "%hhu.%hhu.%hhu.%hhu", B(into->addr.bytes) ) == 4 ) {
607 #undef B
608         // ipv4 address
609         into->addr.width = 4;
610         if ( parse_port( strchr( buffer, ':' ), into ) ) {
611             fprintf( stderr, "bad port\n" );
612             return 1;
613         }
614         if ( parse_bits( strchr( buffer, '/' ), 32, into ) ) {
615             fprintf( stderr, "bad bits\n" );
616             return 1;
617         }
618         return 0;
619     }
620     // ipv6 address
621     char * address = buffer;
622     into->port = 0;
623     if ( *buffer == '[' ) {
624         // bracketed form, necessary for port
625         char *end = strchr( buffer, ']' );
626         if ( end == 0 ) {
627             return 1; // bad argument
628         }
629         address++;
630         *(end++) = 0;
631         if ( *end == ':' && parse_port( end, into ) ) {
632             return 1;
633         }
634     }
635     into->addr.width = 16;
636     if ( parse_bits( strchr( address, '/' ), 128, into ) ) {
637         return 1;
638     }
639     if ( inet_pton( AF_INET6, address, into->addr.bytes ) != 1 ) {
640         return 1; // Bad IPv6
641     }
642     return 0;
643 }
644
645 //** IP address parsing utility
646 // Add a new channel spec into the <allowed> table
647 // spec == 0 for the tap/stdio channel
648 static struct Allowed *add_allowed(char *spec) {
649     struct Allowed *into = calloc( 1, sizeof(struct Allowed) );
650     htable x = HTABLEINIT( struct Interface, mac, hashcode_mac );
651     into->ignored_mac = x;
652     if ( spec != 0 ) {
653         if ( parse_allowed( spec, into ) ) {
654             fprintf( stderr, "Bad remote spec: %s\n", spec );
655             return 0;
656         }
657     }
658     int i;
659     if ( allowed.table == 0 ) {
660         // First entry.
661         allowed.table = calloc( 1, sizeof(struct Allowed*) );
662         allowed.count = 1;
663         i = 0;
664     } else {
665         i = allowed.count++;
666         allowed.table = realloc( allowed.table,
667                                  allowed.count * sizeof(struct Allowed*) );
668         if ( allowed.table == 0 ) {
669             fprintf( stderr, "OUT OF MEMORY\n" );
670             exit( 1 );
671         }
672     }
673     allowed.table[i] = into;
674
675     loadkey( &into->psk );
676     VERBOSE3OUT( "Allowed %s { %s }\n", into->source, show_allowed( into ) );
677     if ( is_uplink( into ) ) {
678         struct SockAddr addr;
679         set_sockaddr( &addr, &into->addr, into->port );
680         VERBOSEOUT( "Add uplink %s\n", show_allowed( into ) );
681         (void) add_remote( &addr, into );
682     }
683     return into;
684 }
685
686 static int parse_threads_count(char *arg) {
687     if ( ( sscanf( arg, "%u", &threads_count ) != 1 ) || threads_count < 1 ) {
688         return 1;
689     }
690     VERBOSEOUT( "** Threads count = %d\n", threads_count );
691     return 0;
692 }
693
694 static int parse_buffers_count(char *arg) {
695     if ( ( sscanf( arg, "%u", &buffers_count ) != 1 ) || buffers_count < 1 ) {
696         return 1;
697     }
698     VERBOSEOUT( "** Buffers count = %d\n", buffers_count );
699     return 0;
700 }
701
702 //** IP address parsing utility for multicast phrase
703 // Return 0 if ok and 1 otherwise
704 // Formats: <ipv4-address>:<port>[=keyfile]
705 // The ipv4 address should be a multicast address in ranges
706 // 224.0.0.0/22, 232.0.0.0/7, 234.0.0.0/8 or 239.0.0.0/8
707 // though it's not checked here.
708 static int parse_mcast(char *arg) {
709     static char buffer[10000];
710     int n = strlen( arg );
711     if ( n > 9000 ) {
712         return 1; // excessively large argument
713     }
714     memcpy( buffer, arg, n );
715     char *p = buffer + n - 1;
716     for ( ; p > buffer && *p != ':' && *p != '='; p-- ) { }
717     if ( *p == '=' ) {
718         mcast.psk.keyfile = p+1;
719         *p = 0;
720         loadkey( &mcast.psk );
721         for ( ; p > buffer && *p != ':' ; p-- ) { }
722     }
723     if ( *p != ':' ) {
724         fprintf( stderr, "Multicast port is required\n" );
725         return 1; // Port number is required
726     }
727     *(p++) = 0;
728     if ( inet_pton( AF_INET, buffer, &mcast.group.imr_multiaddr.s_addr )==0 ) {
729         fprintf( stderr, "Multicast address required\n" );
730         return 1;
731     }
732     char *e;
733     long int port = strtol( p, &e, 10 );
734     if ( *e != 0 || port < 1 || port > 65535 ) {
735         fprintf( stderr, "Bad multicast port\n" );
736         return 1;
737     }
738     mcast.group.imr_address.s_addr = htonl(INADDR_ANY);
739     mcast.sock.in4.sin_family = AF_INET;
740     mcast.sock.in4.sin_addr.s_addr = htonl(INADDR_ANY);
741     mcast.sock.in4.sin_port = htons( atoi( p ) );
742     return 0;
743 }
744
745 //** IP address parsing utility for UDP source address
746 // Return 0 if ok and 1 otherwise
747 // Formats: <ipv4-address> or <ipv6-address>
748 // The ipv4 address should be a multicast address in ranges
749 // 224.0.0.0/22, 232.0.0.0/7, 234.0.0.0/8 or 239.0.0.0/8
750 // though it's not checked here.
751 static int parse_udp_source(char *arg) {
752     if ( inet_pton( AF_INET6, arg, udp_source.address ) ) {
753         // An ipv6 address is given.
754         if ( udp6 ) {
755             udp_source.family = AF_INET6;
756             return 0;
757         }
758         return 1;
759     }
760     if ( ! inet_pton( AF_INET, arg, udp_source.address ) ) {
761         return 1;
762     }
763
764     // An ipv4 address is given.
765     if ( udp6 ) {
766         // Translate into ipv6-encoded ipv4
767         memmove( udp_source.address + 12, udp_source.address, 4 );
768         memset( udp_source.address, 0, 10 );
769         memset( udp_source.address + 10, -1, 2 );
770         udp_source.family = AF_INET6;
771     } else {
772         udp_source.family = AF_INET;
773     }
774     return 0;
775 }
776
777 // Utility that sets upt the multicast socket, which is used for
778 // receiving multicast packets.
779 static void setup_mcast() {
780     // set up ipv4 socket
781     if ( ( mcast.fd = socket( AF_INET, SOCK_DGRAM, 0 ) ) == 0 ) {
782         perror( "creating socket");
783         exit(1);
784     }
785     if ( setsockopt( mcast.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
786                      (char *) &mcast.group, sizeof( mcast.group ) ) < 0) {
787         perror( "Joining multicast group" );
788         exit( 1 );
789     }
790     int reuse = 1;
791     if ( setsockopt( mcast.fd, SOL_SOCKET, SO_REUSEADDR,
792                      &reuse, sizeof( int ) ) < 0 ) {
793         perror( "SO_REUSEADDR" );
794         exit( 1 );
795     }
796     if ( bind( mcast.fd, (struct sockaddr*) &mcast.sock.in,
797                sizeof( struct sockaddr ) ) ) {
798         fprintf( stderr, "Error binding socket!\n");
799         exit(1);
800     }
801     // Change mcast address to be the group multiaddress, and add
802     // a persistent "remote" for it.
803     mcast.sock.in4.sin_addr.s_addr = mcast.group.imr_multiaddr.s_addr;
804     add_remote( &mcast.sock, 0 );
805 }
806
807 // Find the applicable channel rule for a given ip:port address
808 static struct Allowed *is_allowed_remote(struct SockAddr *addr) {
809     struct CharAddr ca;
810     int width = ( addr->in.sa_family == AF_INET )? 4 : 16;
811     unsigned short port;
812     int i = 0;
813     for ( ; (unsigned) i < allowed.count; i++ ) {
814         struct Allowed *a = allowed.table[i];
815         if ( a->addr.width != width ) {
816             continue;
817         }
818         set_charaddrport( &ca, &port, addr );
819         if ( a->port != 0 && a->port != port ) {
820             continue;
821         }
822         clearbitsafter( &ca, a->bits );
823         if ( memcmp( &ca, &a->addr, sizeof( struct CharAddr ) ) == 0 ) {
824             return a;
825         }
826     }
827     return 0; // Disallowed
828 }
829
830 // Simple PSK encryption:
831 //
832 // First, xor each byte with a key byte that is picked from the key
833 // by means of an index that includes the prior encoding. Also,
834 // compute the sum of encrypted bytes into a "magic" that is added the
835 // "seed" for seeding the random number generator. Secondly reorder
836 // the bytes using successive rand number picks from the seeded
837 // generator.
838 //
839 static void encrypt(unsigned char *buf,unsigned int n,struct PSK *psk) {
840     unsigned int k;
841     unsigned int r;
842     unsigned char b;
843     unsigned int magic;
844     VERBOSE3OUT( "encrypt by %s %p\n", psk->keyfile, psk->key );
845     for ( k = 0, r = 0, magic = 0; k < n; k++ ) {
846         r = ( r + magic + k ) % psk->key_length;
847         buf[k] ^= psk->key[ r ];
848         magic += buf[k];
849     }
850     pthread_mutex_lock( &crypting );
851     srand( psk->seed + magic );
852     for ( k = 0; k < n; k++ ) {
853         r = rand() % n;
854         b = buf[k];
855         buf[k] = buf[r];
856         buf[r] = b;
857     }
858     pthread_mutex_unlock( &crypting );
859 }
860
861 // Corresponding decryption procedure .
862 static void decrypt(unsigned char *buf,unsigned int n,struct PSK *psk) {
863     unsigned int randoms[ BUFSIZE ];
864     unsigned int k;
865     unsigned int r;
866     unsigned char b;
867     unsigned int magic = 0;
868     for ( k = 0; k < n; k++ ) {
869         magic += buf[k];
870     }
871     pthread_mutex_lock( &crypting );
872     srand( psk->seed + magic );
873     for ( k = 0; k < n; k++ ) {
874         randoms[k] = rand() % n;
875     }
876     pthread_mutex_unlock( &crypting );
877     for ( k = n; k > 0; ) {
878         r = randoms[ --k ];
879         b = buf[k];
880         buf[k] = buf[r];
881         buf[r] = b;
882     }
883     for ( k = 0, r = 0, magic = 0; k < n; k++ ) {
884         r = ( r + magic + k ) % psk->key_length;
885         magic += buf[k];
886         buf[k] ^= psk->key[r];
887     }
888 }
889
890 // Write a buffer data to given file descriptor (basically tap_fd in
891 // this program). This is never fragmented.
892 static int dowrite(int fd, unsigned char *buf, int n) {
893     int w;
894     if ( ( w = write( fd, buf, n ) ) < 0){
895         perror( "Writing data" );
896         w = -1;
897     }
898     return w;
899 }
900
901 // Write to the tap/stdio; adding length prefix for stdio
902 static int write_tap(unsigned char *buf, int n) {
903     uint8_t tag0 = *( buf + 12 );
904     if ( tag0 == 8 ) {
905         uint16_t size = ntohs( *(uint16_t*)(buf + 16) );
906         if ( size <= 1500 ) {
907             if ( ( verbose >= 2 ) && ( n != size + 14 ) ) {
908                 VERBOSEOUT( "clip %d to %d\n", n, size + 14 );
909             }
910             n = size + 14; // Clip of any tail
911         }
912     }
913     if ( stdio ) {
914         uint16_t plength = htons( n );
915         if ( dowrite( 1, (unsigned char *) &plength,
916                       sizeof( plength ) ) < 0 ) {
917             return -11;
918         }
919         return dowrite( 1, buf, n );
920     }
921     return dowrite( tap_fd, buf, n );
922 }
923
924
925 // All sorts of fiddling is needed to set the source address for UDP
926 // And 2 different ways for pure ipv4 versus ipv6 sockets
927 static void sendpacket4(unsigned char *buf, int n,struct Remote *r) {
928     // The UDP socket is pure ipv4
929     struct iovec data[1] = {{ .iov_base = buf, .iov_len = n }};
930     struct {
931         struct cmsghdr hdr;
932         struct in_pktinfo data;
933     } control = {
934         .hdr.cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)),
935         .hdr.cmsg_level = IPPROTO_IP,
936         .hdr.cmsg_type = IP_PKTINFO,
937         .data.ipi_ifindex = r->ifindex,
938         .data.ipi_spec_dst = r->laddr.in4.sin_addr
939     };
940     struct msghdr msg = {
941         .msg_name = &r->uaddr.in4,
942         .msg_namelen = sizeof( struct sockaddr_in ),
943         .msg_iov = data,
944         .msg_iovlen = 1,
945         .msg_control =  &control,
946         .msg_controllen = CMSG_SPACE( sizeof( struct in_pktinfo ) ),
947         .msg_flags = 0 // unused
948     };
949     if ( r->laddr.in.sa_family && 0 ) {
950         msg.msg_control = &control;
951         msg.msg_controllen = CMSG_SPACE( sizeof( struct in_pktinfo ) );
952     }
953     VERBOSE2OUT( "sendmsg %lu from %s to %s\n",
954                  msg.msg_controllen,
955                  inet_stoa( &r->laddr ),
956                  inet_stoa( &r->uaddr ) );
957     if ( sendmsg( udp_fd, &msg, 0 ) < n ) {
958         perror( "Writing socket" );
959     }
960 #if 0 // ILLUSTRATION
961     struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg);
962     cmsg->cmsg_level = IPPROTO_IP;
963     cmsg->cmsg_type = IP_PKTINFO;
964     cmsg->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo));
965     struct in_pktinfo *pktinfo = (struct in_pktinfo*) CMSG_DATA(cmsg);
966     pktinfo->ipi_ifindex = src_interface_index;
967     pktinfo->ipi_spec_dst = src_addr;
968     msg.msg_controllen = 
969         return sendmsg( fd, &msg, IP_PKTINFO );
970 #endif
971 }
972
973 static void sendpacket6(unsigned char *buf, int n,struct Remote *r) {
974     //NYI
975     (void)buf;
976     (void)n;
977     (void)r;
978 }
979
980 // Write a packet via the given Interface with encryption as specified.
981 static void write_remote(unsigned char *buf, int n,struct Remote *r) {
982     // A packet buffer
983     unsigned char output[ BUFSIZE ];
984     if ( n < 12 ) {
985         VERBOSE2OUT( "SENDing %d bytes to %s\n", n, inet_stoa( &r->uaddr ) );
986     } else {
987         VERBOSE2OUT( "SENDing %d bytes %s -> %s to %s\n", n,
988                      inet_mtoa( buf+6 ), inet_mtoa( buf ),
989                      inet_stoa( &r->uaddr ) );
990     }
991     memcpy( output, buf, n ); // Use the private buffer for delivery
992     // Apply the TPG quirk
993     if ( tpg_quirk && ( n > 1460 ) && ( n < 1478 ) ) {
994         VERBOSE2OUT( "tpg quirk applied\n" );
995         n = 1478; // Add some "random" tag-along bytes
996     }
997     if ( r->spec == 0 ) {
998         if ( r->uaddr.in.sa_family == 0 ) {
999             // Output to tap/stdio
1000             if ( write_tap( buf, n ) < 0 ) {
1001                 // panic error
1002                 fprintf( stderr, "Cannot write to tap/stdio: exiting!\n" );
1003                 exit( 1 );
1004             }
1005             return;
1006         }
1007         // Fall through for multicast
1008         if ( mcast.psk.keyfile ) {
1009             encrypt( output, n, &mcast.psk );
1010         }
1011     } else if ( r->spec->psk.keyfile ) {
1012         encrypt( output, n, &r->spec->psk );
1013     }
1014     if ( udp6 ) {
1015         sendpacket6( output, n, r );
1016     } else {
1017         sendpacket4( output, n, r );
1018     }
1019 }
1020
1021 // Delete a Remote and all its interfaces
1022 static void delete_remote(struct Remote *r) {
1023     VERBOSE2OUT( "DELETE Remote and all its interfaces %s\n",
1024                  inet_stoa( &r->uaddr ) );
1025     unsigned int i = 0;
1026     struct Interface *x;
1027     Interface_LOCK;
1028     for ( ; i < remotes.by_mac.size; i++ ) {
1029         unsigned char *tmp = remotes.by_mac.data[i];
1030         if ( tmp == 0 || tmp == (unsigned char *)1 ) {
1031             continue;
1032         }
1033         x = (struct Interface *) tmp;
1034         if ( x->remote == r ) {
1035             Interface_DEL( x );
1036             free( x );
1037         }
1038     }
1039     Interface_UNLOCK;
1040     Remote_DEL( r );
1041     free( r );
1042 }
1043
1044 // Unmap an ipv4-mapped ipv6 address
1045 static void unmap_if_mapped(struct SockAddr *s) {
1046     if ( s->in.sa_family != AF_INET6 ||
1047          memcmp( "\000\000\000\000\000\000\000\000\000\000\377\377",
1048                  &s->in6.sin6_addr, 12 ) ) {
1049         return;
1050     }
1051     VERBOSE2OUT( "unmap %s\n",
1052                  inet_nmtoa( (unsigned char*) s, sizeof( struct SockAddr ) ) );
1053     s->in.sa_family = AF_INET;
1054     memcpy( &s->in4.sin_addr, s->in6.sin6_addr.s6_addr + 12, 4 );
1055     memset( s->in6.sin6_addr.s6_addr + 4, 0, 12 );
1056     VERBOSE2OUT( "becomes %s\n",
1057                  inet_nmtoa( (unsigned char*) s, sizeof( struct SockAddr ) ) );
1058 }
1059
1060 // Route the packet from the given src
1061 static struct Interface *input_check(
1062     unsigned char *buf,ssize_t len,struct SockAddr *src )
1063 {
1064     VERBOSE2OUT( "RECV %ld bytes from %s\n", len, inet_stoa( src ) );
1065     struct Remote *r = 0;
1066     struct timeval now = { 0 };
1067     if ( gettimeofday( &now, 0 ) ) {
1068         perror( "RECV time" );
1069         now.tv_sec = time( 0 );
1070     }
1071     Remote_FIND( src, r );
1072     if ( r == 0 ) {
1073         struct Allowed *a = is_allowed_remote( src );
1074         if ( a == 0 ) {
1075             VERBOSEOUT( "Ignoring %s\n", inet_stoa( src ) );
1076             return 0; // Disallowed
1077         }
1078         VERBOSEOUT( "New remote %s by %s\n", inet_stoa( src ), a->source );
1079         r = add_remote( src, a );
1080         //r->rec_when = now; // Set activity stamp of new remote
1081     }
1082     if ( len < 12 ) {
1083         // Ignore short data, but maintain channel
1084         r->rec_when = now; // Update activity stamp touched remote
1085         if ( len > 0 ) {
1086             VERBOSEOUT( "Ignoring %ld bytes from %s\n",
1087                         len, inet_stoa( src ) );
1088         }
1089         return 0;
1090     }
1091     // Now decrypt the data as needed
1092     if ( r->spec ) {
1093         if ( r->spec->psk.seed ) {
1094             decrypt( buf, len, &r->spec->psk );
1095         }
1096     } else if ( r->uaddr.in.sa_family == 0 && mcast.psk.keyfile ) {
1097         decrypt( buf, len, &mcast.psk );
1098     }
1099     VERBOSE2OUT( "RECV %s -> %s from %s\n",
1100                  inet_mtoa( buf+6 ), inet_mtoa( buf ),
1101                  inet_stoa( &r->uaddr ) );
1102     // Note: the payload is now decrypted, and known to be from +r+
1103     struct Interface *x = 0;
1104     // Packets concerning an ignored interface should be ignored.
1105     if ( r->spec && r->spec->ignored_mac.data ) {
1106         Ignored_FIND( r->spec, buf+6, x );
1107         if ( x ) {
1108             VERBOSE2OUT( "Dropped MAC %s from %s on %s\n",
1109                          inet_mtoa( buf+6 ), inet_stoa( &r->uaddr ),
1110                          r->spec->source );
1111             return 0;
1112         }
1113         Ignored_FIND( r->spec, buf, x );
1114         if ( x ) {
1115             VERBOSE2OUT( "Dropped MAC %s to %s on %s\n",
1116                          inet_mtoa( buf ), inet_stoa( &r->uaddr ),
1117                          r->spec->source );
1118             return 0;
1119         }
1120     }
1121     Interface_FIND( buf+6, x );
1122     if ( x == 0 ) {
1123         // Totally new MAC. Should bind it to the remote
1124         VERBOSEOUT( "New MAC %s from %s\n",
1125                     inet_mtoa( buf+6 ), inet_stoa( src ) );
1126         x = add_interface( buf+6, r );
1127         r->rec_when = now; // Update activity stamp for remote
1128         x->rec_when = now;
1129         return x;
1130     }
1131     // Seen that MAC already
1132     if ( x->remote == r ) {
1133         VERBOSE2OUT( "RECV %s from %s again\n",
1134                      inet_mtoa( buf+6 ), inet_stoa( &x->remote->uaddr ) );
1135         r->rec_when = now; // Update activity stamp
1136         x->rec_when = now; // Update activity stamp
1137         return x;
1138     }
1139     // MAC clash from two different connections
1140     // r = current
1141     // x->remote = previous
1142     VERBOSE2OUT( "RECV %s from %s previously from %s\n",
1143               inet_mtoa( buf+6 ),
1144               inet_stoa( &r->uaddr ),
1145               inet_stoa( &x->remote->uaddr ) );
1146     if ( r->spec ) {
1147         // The packet source MAC has arrived on other than its
1148         // previous channel. It thus gets dropped if tap/stdin is the
1149         // primary channel, or the time since the last packet for that
1150         // interface is less than RECENT_MICROS, with different limits
1151         // for broadcast and unicast.
1152         int64_t dmac = DIFF_MICROS( &now, &x->rec_when);
1153         if ( x->remote->spec == 0 || RECENT_MICROS( *buf & 1, dmac ) ) {
1154             if ( verbose >= 2 ) {
1155                 fprintf(
1156                     stderr,
1157                     "Dropped. MAC %s (%ld) from %s, should be %s\n",
1158                     inet_mtoa( buf+6 ), dmac,
1159                     inet_stoa( src ), inet_stoa( &x->remote->uaddr ) );
1160             }
1161             return 0;
1162         }
1163         // Check if previous package on the interface was recent
1164     } else if ( r->uaddr.in.sa_family ) {
1165         // Multicast incoming clashing with tap/stdio
1166         VERBOSE3OUT( "Dropped multicast loopback\n" );
1167         return 0;
1168     }
1169
1170     // New remote takes over the MAC
1171     VERBOSEOUT( "MAC %s from %s cancels previous %s\n",
1172                 inet_mtoa( buf+6 ), inet_stoa( src ),
1173                 inet_stoa( &x->remote->uaddr ) );
1174     x->remote = r; // Change remote for MAC
1175     // Note that this may leave the old x->remote without any interface
1176     r->rec_when = now; // Update activity stamp
1177     x->rec_when = now; // Update activity stamp
1178     return x;
1179 }
1180
1181 // Check packet and deliver out
1182 static void route_packet(PacketItem *pi) {
1183     unsigned char *buf = pi->buffer;
1184     int len = pi->len;
1185     struct SockAddr *src = &pi->src;
1186     struct Interface *x = input_check( buf, len, src );
1187     if ( x == 0 ) {
1188         VERBOSE2OUT( "not a nice packet\n" );
1189         return; // not a nice packet
1190     }
1191     // Set the local addressing for the remote
1192     if ( udp6 ) {
1193         x->remote->ifindex = pi->dstinfo.in6.ipi6_ifindex;
1194         x->remote->laddr.in6.sin6_family = AF_INET6;
1195         x->remote->laddr.in6.sin6_port = htons( udp_port );
1196         memcpy( &x->remote->laddr.in6.sin6_addr,
1197                 &pi->dstinfo.in6.ipi6_addr,
1198                 16 );
1199     } else {
1200         x->remote->ifindex = pi->dstinfo.in4.ipi_ifindex;
1201         x->remote->laddr.in4.sin_family = AF_INET;
1202         x->remote->laddr.in4.sin_port = htons( udp_port );
1203         memcpy( &x->remote->laddr.in4.sin_addr,
1204                 &pi->dstinfo.in4.ipi_spec_dst,
1205                 4 );
1206     }
1207     if ( ( *buf & 1 ) == 0 ) {
1208         // unicast
1209         struct Interface *y = 0; // reuse for destination interface
1210         Interface_FIND( buf, y );
1211         if ( y == 0 ) {
1212             VERBOSE2OUT( "RECV %s -> %s from %s without channel and dropped\n",
1213                         inet_mtoa( buf+6 ), inet_mtoa( buf ),
1214                         inet_stoa( &x->remote->uaddr ) );
1215             return;
1216         }
1217         if ( x->remote == y->remote ) {
1218             VERBOSEOUT( "RECV loop for %s -> %s from %s to %s\n",
1219                         inet_mtoa( buf+6 ), inet_mtoa( buf ),
1220                         inet_stoa( &x->remote->uaddr ),
1221                         inet_stoa( &y->remote->uaddr ) );
1222             Interface_DEL( y ); // Need to see this interface again
1223             return;
1224         }
1225         VERBOSE2OUT( "RECV route %s -> %s\n",
1226                      inet_mtoa( buf+6 ),
1227                      inet_mtoa( buf ) );
1228         write_remote( buf, len, y->remote );
1229         return;
1230     }
1231     // broadcast. +x+ is source interface
1232     // x->rec_when is not updated 
1233     struct timeval now = { 0 };
1234     if ( gettimeofday( &now, 0 ) ) {
1235         perror( "RECV time" );
1236         now.tv_sec = time( 0 );
1237     }
1238     VERBOSE2OUT( "BC %s -> %s from %s to %s\n",
1239                  inet_mtoa( buf+6 ), inet_mtoa( buf ),
1240                  inet_stoa( &x->remote->uaddr ),
1241                  inet_stoa( &x->remote->laddr ) );
1242     struct Remote *r;
1243     unsigned int i = 0;
1244     Remote_LOCK;
1245     for ( ; i < remotes.by_addr.size; i++ ) {
1246         unsigned char *tmp = remotes.by_addr.data[i];
1247         if ( tmp == 0 || tmp == (unsigned char *)1 ) {
1248             continue;
1249         }
1250         r = (struct Remote *) tmp;
1251         VERBOSE3OUT( "BC check %s\n", inet_stoa( &r->uaddr ) );
1252         if ( r == x->remote ) {
1253             VERBOSE3OUT( "BC r == x->remote\n" );
1254             continue;
1255         }
1256         if ( r->spec && ! is_uplink( r->spec ) &&
1257              DIFF_MICROS( &now, &r->rec_when ) > VERYOLD_MICROS ) {
1258             // remove old downlink connection
1259             VERBOSEOUT( "Old remote discarded %s (%ld)\n",
1260                         inet_stoa( &r->uaddr ),
1261                         TIME_MICROS( &r->rec_when ) );
1262             // Removing a downlink might have threading implications
1263             delete_remote( r );
1264             continue;
1265         }
1266         // Send packet to the remote
1267         // Only no-clash or to the tap/stdin
1268         write_remote( buf, len, r );
1269     }
1270     Remote_UNLOCK;
1271 }
1272
1273 // The packet handling queues
1274 static struct {
1275     Queue full;
1276     Queue free;
1277     sem_t reading;
1278 } todolist;
1279
1280 // The threadcontrol program for handling packets.
1281 static void *packet_handler(void *data) {
1282     (void) data;
1283     for ( ;; ) {
1284         PacketItem *todo = (PacketItem *) Queue_getItem( &todolist.full );
1285         if ( todo->fd == mcast.fd ) {
1286             // Patch in the multicast address as source for multicast packet
1287             memcpy( &todo->src, &mcast.sock, sizeof( todo->src ) );
1288             route_packet( todo );
1289         } else {
1290             if ( udp6 ) {
1291                 unmap_if_mapped( &todo->src );
1292             }
1293             route_packet( todo );
1294         }
1295         memset( &todo->src, 0, sizeof( struct SockAddr ) );
1296         memset( &todo->dstinfo, 0, sizeof( todo->dstinfo ) );
1297         Queue_addItem( &todolist.free, (QueueItem*) todo );
1298     }
1299     return 0;
1300 }
1301
1302 void todolist_initialize(int nbuf,int nthr) {
1303     if ( pthread_mutex_init( &todolist.full.mutex, 0 ) ||
1304          sem_init( &todolist.full.count, 0, 0 ) ) {
1305         perror( "FATAL" );
1306         exit( 1 );
1307     }
1308     if ( pthread_mutex_init( &todolist.free.mutex, 0 ) ||
1309          sem_init( &todolist.free.count, 0, 0 ) ) {
1310         perror( "FATAL" );
1311         exit( 1 );
1312     }
1313     if ( sem_init( &todolist.reading, 0, 1 ) ) {
1314         perror( "FATAL" );
1315         exit( 1 );
1316     }
1317     Queue_initialize( &todolist.free, nbuf, sizeof( PacketItem ) );
1318     for ( ; nthr > 0; nthr-- ) {
1319         pthread_t thread; // Temporary thread id
1320         pthread_create( &thread, 0, packet_handler, 0 );
1321     }
1322 }
1323
1324 // Reads a UDP packet on the given file descriptor and captures the
1325 // source and destination addresses of the UDP message.
1326 inline static ssize_t recvpacket(int fd,PacketItem *p) {
1327     char data[100]; // Data area for "pktinfo"
1328     struct iovec buffer[1] = {{ p->buffer, BUFSIZE }};
1329     struct msghdr msg = {
1330         .msg_name =  &p->src.in,
1331         .msg_namelen = udp6? sizeof( p->src.in6 ) : sizeof( p->src.in4 ),
1332         .msg_iov = buffer,
1333         .msg_iovlen = 1,
1334         .msg_control = data,
1335         .msg_controllen = sizeof( data ),
1336         .msg_flags = 0 // Return value
1337     };
1338     p->len = recvmsg( fd, &msg, udp6? 0 : IP_PKTINFO );
1339     struct cmsghdr *cmsg = CMSG_FIRSTHDR( &msg );
1340     if ( cmsg ) {
1341         if ( udp6 ) {
1342             memcpy( &p->dstinfo.in6, CMSG_DATA( cmsg ),
1343                     sizeof( struct in6_pktinfo ) );
1344             VERBOSE2OUT( "DEST= udp6 %d\n", p->dstinfo.in6.ipi6_ifindex );
1345         } else {
1346             memcpy( &p->dstinfo.in4, CMSG_DATA( cmsg ),
1347                     sizeof( struct in_pktinfo ) );
1348             VERBOSE2OUT( "DEST= %d\n", p->dstinfo.in4.ipi_ifindex );
1349         }
1350     }
1351     return p->len;
1352 }
1353
1354
1355
1356 // Read a full UDP packet into the given buffer, associate with a
1357 // connection, or create a new connection, the decrypt the as
1358 // specified, and capture the sender MAC address. The connection table
1359 // is updated for the new MAC address, However, if there is then a MAC
1360 // address clash in the connection table, then the associated remote
1361 // is removed, and the packet is dropped.
1362 static void *doreadUDP(void *data) {
1363     int fd = ((ReaderData *) data)->fd;
1364     while ( 1 ) {
1365         PacketItem *todo = (PacketItem *) Queue_getItem( &todolist.free );
1366         todo->fd = fd;
1367         VERBOSE3OUT( "Reading packet on %d\n", fd );
1368         ssize_t len = recvpacket( fd, todo );
1369         if ( len == -1) {
1370             perror( "Receiving UDP" );
1371             exit( 1 );
1372         }
1373 #ifdef GPROF
1374         if ( len == 17 &&
1375              memcmp( todo->buffer, "STOPSTOPSTOPSTOP", 16 ) == 0 ) {
1376             exit( 0 );
1377         }
1378 #endif
1379         Queue_addItem( &todolist.full, (QueueItem*) todo );
1380     }
1381     return 0;
1382 }
1383
1384 // Read up to n bytes from the given file descriptor into the buffer
1385 static int doread(int fd, unsigned char *buf, int n) {
1386     ssize_t len;
1387     if ( ( len = read( fd, buf, n ) ) < 0 ) {
1388         perror( "Reading stdin" );
1389         exit( 1 );
1390     }
1391     return len;
1392 }
1393
1394 // Read n bytes from the given file descriptor into the buffer.
1395 // If partial is allowed, then return amount read, otherwise keep
1396 // reading until full.
1397 static int read_into(int fd, unsigned char *buf, int n,int partial) {
1398     int r, x = n;
1399     while( x > 0 ) {
1400         if ( (r = doread( fd, buf, x ) ) == 0 ) {
1401             return 0 ;
1402         }
1403         x -= r;
1404         buf += r;
1405         if ( partial ) {
1406             return n - x;
1407         }
1408     }
1409     return n;
1410 }
1411
1412 // Go through all uplinks and issue a "heart beat"
1413 static void heartbeat(int fd) {
1414     static unsigned char data[10];
1415     VERBOSE3OUT( "heartbeat fd=%d\n", fd );
1416     struct Remote *r;
1417     unsigned int i = 0;
1418     struct timeval now;
1419     if ( gettimeofday( &now, 0 ) ) {
1420         perror( "HEARTBEAT time" );
1421         now.tv_sec = time( 0 );
1422         now.tv_usec = 0;
1423     }
1424     Remote_LOCK;
1425     for ( ; i < remotes.by_addr.size; i++ ) {
1426         unsigned char *tmp = remotes.by_addr.data[i];
1427         if ( tmp == 0 || tmp == (unsigned char *)1 ) {
1428             continue;
1429         }
1430         r = (struct Remote *) tmp;
1431         VERBOSE3OUT( "heartbeat check %s\n", inet_stoa( &r->uaddr ) );
1432         if ( r->spec && is_uplink( r->spec ) ) {
1433             if ( DIFF_MICROS( &now, &r->rec_when ) > HEARTBEAT_MICROS ) {
1434                 VERBOSE3OUT( "heartbeat %s\n", inet_stoa( &r->uaddr ) );
1435                 write_remote( data, 0, r );
1436             }
1437         }
1438     }
1439     Remote_UNLOCK;
1440 }
1441
1442 // Tell how to use this program and exit with failure.
1443 static void usage(void) {
1444     fprintf( stderr, "Packet tunneling over UDP, multiple channels, " );
1445     fprintf( stderr, "version 1.5.3\n" );
1446     fprintf( stderr, "Usage: " );
1447     fprintf( stderr, "%s [options] port [remote]+ \n", progname );
1448     fprintf( stderr, "** options must be given or omitted in order!!\n" );
1449     fprintf( stderr, " -v        = verbose log, -vv or -vvv for more logs\n" );
1450     fprintf( stderr, " -tpg      = UDP transport quirk: avoid bad sizes\n" );
1451     fprintf( stderr, " -4        = use an ipv4 UDP socket\n" );
1452     fprintf( stderr, " -B n      = use n buffers (2*threads) by default\n");
1453     fprintf( stderr, " -T n      = use n delivery threads (5 bu default)\n" );
1454     fprintf( stderr, " -m mcast  = allow remotes on multicast address\n" );
1455     fprintf( stderr, " -t tap    = use the nominated tap (or - for stdio)\n" );
1456     fprintf( stderr, " -S source = use given source address for UDP\n" );
1457     exit( 1 );
1458 }
1459
1460 // Open the given tap
1461 static int tun_alloc(char *dev, int flags) {
1462     struct ifreq ifr;
1463     int fd, err;
1464     if ( ( fd = open( "/dev/net/tun", O_RDWR ) ) < 0 ) {
1465         perror( "Opening /dev/net/tun" );
1466         return fd;
1467     }
1468     memset( &ifr, 0, sizeof( ifr ) );
1469     ifr.ifr_flags = flags;
1470     if ( *dev ) {
1471         strcpy( ifr.ifr_name, dev );
1472     }
1473     if ( ( err = ioctl( fd, TUNSETIFF, (void *) &ifr ) ) < 0 ) {
1474         perror( "ioctl(TUNSETIFF)" );
1475         close( fd );
1476         return err;
1477     }
1478     strcpy( dev, ifr.ifr_name );
1479     return fd;
1480 }
1481
1482 // Handle packet received on the tap/stdio channel
1483 static void initialize_tap() {
1484     // Ensure there is a Remote for this
1485     static struct Remote *tap_remote = 0;
1486     if ( tap_remote == 0 ) {
1487         Remote_LOCK;
1488         if ( tap_remote == 0 ) {
1489             tap_remote = add_remote( 0, 0 );
1490         }
1491         Remote_UNLOCK;
1492     }
1493 }
1494
1495 // Thread to handle tap/stdio input
1496 static void *doreadTap(void *data) {
1497     int fd = ((ReaderData*) data)->fd;
1498     unsigned int end = 0; // Packet size
1499     unsigned int cur = 0; // Amount read so far
1500     size_t e;
1501     PacketItem *todo = (PacketItem*) Queue_getItem( &todolist.free );
1502     while ( 1 ) {
1503         if ( stdio ) {
1504             uint16_t plength;
1505             int n = read_into( 0, (unsigned char *) &plength,
1506                                sizeof( plength ), 0 );
1507             if ( n == 0 ) {
1508                 // Tap/stdio closed => exit silently
1509                 exit( 0 );
1510             }
1511             end = ntohs( plength );
1512             cur = 0;
1513             while ( ( e = ( end - cur ) ) != 0 ) {
1514                 unsigned char *p = todo->buffer + cur;
1515                 if ( end > BUFSIZE ) {
1516                     // Oversize packets should be read and discarded
1517                     if ( e > BUFSIZE ) {
1518                         e = BUFSIZE;
1519                     }
1520                     p = todo->buffer;
1521                 }
1522                 cur += read_into( 0, p, e, 1 );
1523             }
1524         } else {
1525             end = doread( fd, todo->buffer, BUFSIZE );
1526             cur = end;
1527         }
1528         VERBOSE3OUT( "TAP/stdio input %d bytes\n", end );
1529         if ( end <= BUFSIZE ) {
1530             todo->fd = 0;
1531             todo->len = end;
1532             Queue_addItem( &todolist.full, (QueueItem*) todo );
1533             todo = (PacketItem*) Queue_getItem( &todolist.free );
1534         }
1535         // End handling tap
1536     }
1537     return 0;
1538 }
1539
1540 // Application main function
1541 // Parentheses mark optional
1542 // $* = (-v) (-4) (-B n) (-T n) (-m mcast) (-t port) (ip:)port (remote)+
1543 // remote = ipv4(/maskwidth)(:port)(=key)
1544 // remote = ipv6(/maskwidth)(=key)
1545 // remote = [ipv6(/maskwidth)](:port)(=key)
1546 // ip = ipv4 | [ipv6]
1547 int main(int argc, char *argv[]) {
1548     pthread_t thread; // Temporary thread id
1549     int i;
1550     progname = (unsigned char *) argv[0];
1551     ///// Parse command line arguments
1552     i = 1;
1553 #define ENSUREARGS(n) if ( argc < i + n ) usage()
1554     ENSUREARGS( 1 );
1555     // First: optional -v, -vv or -vvv
1556     if ( strncmp( "-v", argv[i], 2 ) == 0 ) {
1557         if ( strncmp( "-v", argv[i], 3 ) == 0 ) {
1558             verbose = 1;
1559         } else if ( strncmp( "-vv", argv[i], 4 ) == 0 ) {
1560             verbose = 2;
1561         } else if ( strncmp( "-vvv", argv[i], 5 ) == 0 ) {
1562             verbose = 3;
1563         } else {
1564             usage();
1565         }
1566         i++;
1567         ENSUREARGS( 1 );
1568     }
1569     if ( strncmp( "-tpg", argv[i], 4 ) == 0 ) {
1570         tpg_quirk = 1;
1571         i++;
1572         ENSUREARGS( 1 );
1573     }
1574     // then: optional -4
1575     if ( strncmp( "-4", argv[i], 2 ) == 0 ) {
1576         udp6 = 0;
1577         i++;
1578         ENSUREARGS( 1 );
1579     }
1580     // then: optional -B buffers
1581     if ( strncmp( "-B", argv[i], 2 ) == 0 ) {
1582         ENSUREARGS( 2 );
1583         if ( parse_buffers_count( argv[i+1] ) ) {
1584             usage();
1585         }
1586         i += 2;
1587         ENSUREARGS( 1 );
1588     }
1589     // then: optional -T threads
1590     if ( strncmp( "-T", argv[i], 2 ) == 0 ) {
1591         ENSUREARGS( 2 );
1592         if ( parse_threads_count( argv[i+1] ) ) {
1593             usage();
1594         }
1595         i += 2;
1596         ENSUREARGS( 1 );
1597     }
1598     // then: optional -m mcast
1599     if ( strncmp( "-m", argv[i], 2 ) == 0 ) {
1600         ENSUREARGS( 2 );
1601         if ( parse_mcast( argv[i+1] ) ) {
1602             usage();
1603         }
1604         i += 2;
1605         ENSUREARGS( 1 );
1606     }
1607     // then: optional -t tap
1608     if ( strncmp( "-t", argv[i], 2 ) == 0 ) {
1609         ENSUREARGS( 2 );
1610         tap = argv[i+1];
1611         i += 2;
1612         ENSUREARGS( 1 );
1613     }
1614     // Then optional source address for UDP
1615     if ( strncmp( "-S", argv[i], 2 ) == 0 ) {
1616         ENSUREARGS( 2 );
1617         if ( parse_udp_source( argv[i+1] ) ) {
1618             usage();
1619         }
1620         i += 2;
1621         ENSUREARGS( 1 );
1622     }
1623     // then: required port
1624     if ( sscanf( argv[i++], "%d", &udp_port ) != 1 ) {
1625         fprintf( stderr, "Bad local port: %s\n", argv[i-1] );
1626         usage();
1627     }
1628     // then: any number of allowed remotes
1629     struct Allowed *last_allowed = 0;
1630     for ( ; i < argc; i++ ) {
1631         if ( last_allowed ) {
1632             // optionally adding ignored interfaces
1633             if ( strncmp( "-i", argv[i], 2 ) == 0 ) {
1634                 ENSUREARGS( 2 );
1635                 if ( parse_ignored_interfaces( argv[i+1], last_allowed ) ) {
1636                     usage();
1637                 }
1638                 i += 1;
1639                 continue;
1640             }
1641         }
1642         if ( ( last_allowed = add_allowed( argv[i] ) ) == 0 ) {
1643             fprintf( stderr, "Cannot load remote %s. Exiting.\n", argv[i] );
1644             exit( 1 );
1645         }
1646     }
1647     // end of command line parsing
1648
1649     // Initialize buffers and threads
1650     if ( threads_count == 0 ) {
1651         threads_count = 5;
1652     }
1653     if ( buffers_count < threads_count ) {
1654         buffers_count = 2 * threads_count;
1655     }
1656     todolist_initialize( buffers_count, threads_count );
1657
1658     // Set up the tap/stdio channel
1659     if ( tap ) {
1660         // set up the nominated tap
1661         if ( strcmp( "-", tap ) ) { // Unless "-"
1662             tap_fd = tun_alloc( tap, IFF_TAP | IFF_NO_PI );
1663             if ( tap_fd < 0 ) {
1664                 fprintf( stderr, "Error connecting to interface %s!\n", tap);
1665                 exit(1);
1666             }
1667             VERBOSEOUT( "Using tap %s at %d\n", tap, tap_fd );
1668             stdio = 0;
1669             // pretend a zero packet on the tap, for initializing.
1670             initialize_tap(); 
1671         } else {
1672             // set up for stdin/stdout local traffix
1673             setbuf( stdout, NULL ); // No buffering on stdout.
1674             tap_fd = 0; // actually stdin
1675             stdio = 1;
1676         }
1677     } else {
1678         stdio = 0;
1679     }
1680     // Set up the multicast UDP channel (all interfaces)
1681     if ( mcast.group.imr_multiaddr.s_addr ) {
1682         setup_mcast();
1683         unsigned char *x = (unsigned char *) &mcast.group.imr_multiaddr.s_addr;
1684         VERBOSEOUT( "Using multicast %s:%d at %d\n",
1685                     inet_nmtoa( x, 4 ), ntohs( mcast.sock.in4.sin_port ),
1686                     mcast.fd );
1687     }
1688     // Set up the unicast UPD channel (all interfaces)
1689     if ( udp6 == 0 ) {
1690         // set up ipv4 socket
1691         if ( ( udp_fd = socket( AF_INET, SOCK_DGRAM, 0 ) ) == 0 ) {
1692             perror( "creating socket");
1693             exit(1);
1694         }
1695         struct sockaddr_in udp_addr = {
1696             .sin_family = AF_INET,
1697             .sin_port = htons( udp_port ),
1698         };
1699         if ( udp_source.family == 0 ) {
1700             udp_addr.sin_addr.s_addr = htonl( INADDR_ANY );
1701         } else {
1702             udp_addr.sin_addr.s_addr = *((uint32_t*) udp_source.address); 
1703         }
1704         if ( bind( udp_fd, (struct sockaddr*) &udp_addr, sizeof(udp_addr))) {
1705             fprintf( stderr, "Error binding socket!\n");
1706             exit(1);
1707         }
1708         VERBOSEOUT( "Using ipv4 UDP at %d\n", udp_fd );
1709         int opt = 1;
1710         if ( setsockopt( udp_fd, IPPROTO_IP, IP_PKTINFO, &opt, sizeof(opt)) ) {
1711             fprintf( stderr, "Error configuring socket!\n");
1712             exit(1);
1713         }
1714     } else {
1715         // set up ipv6 socket
1716         if ( ( udp_fd = socket( AF_INET6, SOCK_DGRAM, 0 ) ) == 0 ) {
1717             perror( "creating socket");
1718             exit(1);
1719         }
1720         struct sockaddr_in6 udp6_addr = {
1721             .sin6_family = AF_INET6,
1722             .sin6_port = htons( udp_port ),
1723         };
1724         memcpy( udp6_addr.sin6_addr.s6_addr, udp_source.address, 16 );
1725         if ( bind( udp_fd, (struct sockaddr*) &udp6_addr, sizeof(udp6_addr))) {
1726             fprintf( stderr, "Error binding socket!\n");
1727             exit(1);
1728         }
1729         VERBOSEOUT( "Using ipv6 UDP at %d\n", udp_fd );
1730         int opt = 1;
1731         if ( setsockopt(
1732                  udp_fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &opt, sizeof(opt)) ) {
1733             fprintf( stderr, "Error configuring socket!\n");
1734             exit(1);
1735         }
1736     }
1737     // If not using stdio for local traffic, then stdin and stdout are
1738     // closed here, so as to avoid that any other traffic channel gets
1739     // 0 or 1 as its file descriptor. Note: stderr (2) is left open.
1740     if ( ! stdio ) {
1741         close( 0 );
1742         close( 1 );
1743     }
1744     VERBOSE2OUT( "Socket loop tap=%d mcast=%d udp=%d\n",
1745                  tap_fd, mcast.fd, udp_fd );
1746
1747     // Handle packets
1748     ReaderData udp_reader = { .fd = udp_fd };
1749     pthread_create( &thread, 0, doreadUDP, &udp_reader );
1750
1751     if ( mcast.group.imr_multiaddr.s_addr ) {
1752         ReaderData mcast_reader = { .fd = mcast.fd };
1753         pthread_create( &thread, 0, doreadUDP, &mcast_reader );
1754     }
1755
1756     if ( tap_fd || stdio ) {
1757         ReaderData tap_reader = { .fd = tap_fd };
1758         pthread_create( &thread, 0, doreadTap, &tap_reader );
1759     }
1760
1761     // Start heartbeating to uplinks
1762     for ( ;; ) {
1763         sleep( HEARTBEAT );
1764         heartbeat( udp_fd );
1765     }
1766     return 0;
1767 }