2711039cfddaccd81fc4fcd0bda51bdffda3f6ff
[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 address
70     struct Allowed *spec;       // Rule being instantiated
71     struct timeval rec_when;    // Last received packet time, in seconds
72 };
73
74 // Details of an interface at a remote.
75 struct Interface  {
76     unsigned char mac[6];       // MAC address used last (key for by_mac table)
77     struct timeval rec_when;    // Last packet time, in seconds
78     struct Remote *remote;
79 };
80
81 // Maximal packet size .. allow for jumbo frames (9000)
82 #define BUFSIZE 10000
83
84 typedef struct _PacketItem {
85     QueueItem base;
86     int fd;
87     struct SockAddr src; // the remote IP for this packet
88     struct SockAddr dst; // the local IP for this packet
89     ssize_t len;
90     unsigned char buffer[ BUFSIZE ];
91 } PacketItem;
92
93 typedef struct _ReaderData {
94     int fd;
95 } ReaderData;
96
97 // heartbeat interval, in seconds
98 #define HEARTBEAT 30
99 #define HEARTBEAT_MICROS ( HEARTBEAT * 1000000 )
100
101 // Macros for timing, for struct timeval variables
102 #define TIME_MICROS(TM) (((int64_t) (TM)->tv_sec * 1000000) + (TM)->tv_usec )
103 #define DIFF_MICROS(TM1,TM2) ( TIME_MICROS(TM1) - TIME_MICROS(TM2) )
104
105 // RECENT_MICROS(T,M) is the time logic for requiring a gap time (in
106 // milliseconds) before shifting a MAC to a new remote. The limit is
107 // 6s for broadcast and 20s for unicast.
108 #define RECENT_MICROS(T,M) ((M) < ((T)? 6000000 : 20000000 ))
109
110 // VERYOLD_MICROSS is used for discarding downlink remotes whose latest
111 // activity is older than this.
112 #define VERYOLD_MICROS 180000000
113
114 ////////// Variables
115
116 // Allowed remote specs are held in a table sorted by IP prefix.
117 static struct {
118     struct Allowed **table;
119     unsigned int count;
120 } allowed;
121
122 // Actual remotes are kept in a hash table keyed by their +uaddr+
123 // field, and another hash table keps Interface records for all MAC
124 // addresses sourced from some remote, keyed by their +mac+ field. The
125 // latter is used both for resolving destinations for outgoing
126 // packets, and for limiting broadcast cycles. The former table is
127 // used for limiting incoming packets to allowed sources, and then
128 // decrypt the payload accordingly.
129 static int hashcode_uaddr(struct _htable *table,unsigned char *key);
130 static int hashcode_mac(struct _htable *table,unsigned char *key);
131 static struct {
132     htable by_mac; // struct Interface hash table
133     htable by_addr; // struct Remote hash table
134 } remotes = {
135     .by_mac = HTABLEINIT( struct Interface, mac, hashcode_mac ),
136     .by_addr = HTABLEINIT( struct Remote, uaddr, hashcode_uaddr )
137 };
138
139 #define Interface_LOCK if ( pthread_mutex_lock( &remotes.by_mac.lock ) ) { \
140         perror( "FATAL" ); exit( 1 ); }
141
142 #define Interface_UNLOCK if (pthread_mutex_unlock( &remotes.by_mac.lock ) ) { \
143         perror( "FATAL" ); exit( 1 ); }
144
145 #define Interface_FIND(m,r) \
146     htfind( &remotes.by_mac, m, (unsigned char **)&r )
147
148 #define Interface_ADD(r) \
149     htadd( &remotes.by_mac, (unsigned char *)r )
150
151 #define Interface_DEL(r) \
152     htdelete( &remotes.by_mac, (unsigned char *) r )
153
154 #define Remote_LOCK if ( pthread_mutex_lock( &remotes.by_addr.lock ) ) { \
155         perror( "FATAL" ); exit( 1 ); }
156
157 #define Remote_UNLOCK if ( pthread_mutex_unlock( &remotes.by_addr.lock ) ) { \
158         perror( "FATAL" ); exit( 1 ); }
159
160 #define Remote_FIND(a,r) \
161     htfind( &remotes.by_addr, (unsigned char *)a, (unsigned char **) &r )
162
163 #define Remote_ADD(r) \
164     htadd( &remotes.by_addr, (unsigned char *) r )
165
166 #define Remote_DEL(r) \
167     htdelete( &remotes.by_addr, (unsigned char *) r )
168
169 #define Ignored_FIND(a,m,x)                             \
170     htfind( &a->ignored_mac, m, (unsigned char **)&x )
171
172 #define Ignored_ADD(a,x) \
173     htadd( &a->ignored_mac, (unsigned char *)x )
174
175 // Input channels
176 static int stdio = 0; // Default is neither stdio nor tap
177 static char *tap = 0; // Name of tap, if any, or "-" for stdio
178 static int tap_fd = 0; // Also used for stdin in stdio mode
179 static int udp_fd;
180 static int threads_count = 0;
181 static int buffers_count = 0;
182
183 // Setup for multicast channel
184 static struct {
185     struct ip_mreqn group;
186     struct SockAddr sock;
187     int fd;
188     struct PSK psk;
189 } mcast;
190
191 // Flag to signal the UDP socket as being ipv6 or not (forced ipv4)
192 static int udp6 = 1;
193
194 // The given UDP source address, if any
195 static struct {
196     int family;
197     unsigned char address[16];
198 } udp_source;
199
200 // Flag to indicate tpg transport patch = avoid UDP payload of 1470
201 // bytes by adding 2 tag-along bytes
202 static int tpg_quirk = 0;
203
204 // Flag whether to make some stderr outputs or not.
205 // 1 = normal verbosity, 2 = more output, 3 = source debug level stuff
206 static int verbose;
207
208 // Note: allows a thread to lock/unlock recursively
209 static pthread_mutex_t crypting = PTHREAD_MUTEX_INITIALIZER;
210
211 // Note: allows a thread to lock/unlock recursively
212 static pthread_mutex_t printing = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
213
214 #define PRINTLOCK \
215     if ( pthread_mutex_lock( &printing ) ) { perror( "FATAL" ); exit(1); }
216
217 #define PRINTUNLOCK \
218     if ( pthread_mutex_unlock( &printing ) ) { perror( "FATAL" ); exit(1); }
219
220 #define PRINT( X ) { PRINTLOCK; X; PRINTUNLOCK; }
221
222 #define VERBOSEOUT(fmt, ...) \
223     if ( verbose >= 1 ) PRINT( fprintf( stderr, fmt, ##__VA_ARGS__ ) )
224
225 #define VERBOSE2OUT(fmt, ...) \
226     if ( verbose >= 2 ) PRINT( fprintf( stderr, fmt, ##__VA_ARGS__ ) )
227
228 #define VERBOSE3OUT(fmt, ...) \
229     if ( verbose >= 3 ) PRINT( fprintf( stderr, fmt, ##__VA_ARGS__ ) )
230
231 // The actual name of this program (argv[0])
232 static unsigned char *progname;
233
234 // Compute a hashcode for the given SockAddr key
235 static int hashcode_uaddr(
236     __attribute__((unused)) struct _htable *table,unsigned char *key)
237 {
238     struct SockAddr *s = (struct SockAddr *) key;
239     key = (unsigned char*) &s->in;
240     unsigned char *e = key + ( ( s->in.sa_family == AF_INET )?
241                                sizeof( struct sockaddr_in ) :
242                                sizeof( struct sockaddr_in6 ) );
243     int x = 0;
244     while ( key < e ) {
245         x += *(key++);
246     }
247     return x;
248 }
249
250 // Compute a hashcode for the given MAC addr key
251 static int hashcode_mac(struct _htable *table,unsigned char *key) {
252     int x = 0;
253     int i = 0;
254     if ( table->size == 256 ) {
255         for ( ; i < 6; i++ ) {
256             x += *(key++);
257         }
258         return x;
259     }
260     uint16_t *p = (uint16_t *) key;
261     for ( ; i < 3; i++ ) {
262         x += *( p++ );
263     }
264     return x;
265 }
266
267 // Make a text representation of bytes as ipv4 or ipv6
268 static char *inet_nmtoa(unsigned char *b,int w) {
269     static char buffer[20000];
270     int i = 0;
271     char * p = buffer;
272     if ( w == 4 ) {
273         sprintf( p,"%d.%d.%d.%d", b[0], b[1], b[2], b[3] );
274     } else if ( w == 16 ){
275         sprintf( p,
276   "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
277                  b[0], b[1], b[2], b[3],
278                  b[4], b[5], b[6], b[7],
279                  b[8], b[9], b[10], b[11],
280                  b[12], b[13], b[14], b[15] );
281     } else {
282         VERBOSE3OUT( "HEX data of %d bytes\n", w );
283         for ( ; i < w && i < 19000; i++, p += 3 ) {
284             sprintf( p, "%02x:", b[i] );
285         }
286         if ( w > 0 ) {
287             *(--p) = 0;
288         }
289     }
290     return buffer;
291 }
292
293 // Form a MAC address string from 6 MAC address bytes, into one of the
294 // 4 static buffer, whose use are cycled.
295 static char *inet_mtoa(unsigned char *mac) {
296     static char buffer[4][30];
297     static int i = 0;
298     if ( i > 3 ) {
299         i = 0;
300     }
301     sprintf( buffer[i], "%02x:%02x:%02x:%02x:%02x:%02x",
302              mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] );
303     return buffer[i++];
304 }
305
306 // Form a socket address string from Sockaddr, into one of the
307 // 4 static buffer, whose use are cycled.
308 static char *inet_stoa(struct SockAddr *a) {
309     static char buffer[1000];
310     static char out[4][1000];
311     static int i = 0;
312     if ( i > 3 ) {
313         i = 0;
314     }
315     if ( a->in.sa_family == AF_INET ) {
316         sprintf( out[i], "%s:%d",
317                  inet_ntop( AF_INET, &a->in4.sin_addr, buffer, 100 ),
318                  ntohs( a->in4.sin_port ) );
319     } else if ( a->in.sa_family == AF_INET6 ) {
320         sprintf( out[i], "[%s]:%d",
321                  inet_ntop( AF_INET6, &a->in6.sin6_addr, buffer, 100 ),
322                  ntohs( a->in6.sin6_port ) );
323     } else {
324         sprintf( out[i], "<tap/stdio>" );
325     }
326     return out[i++];
327 }
328
329 // Debugging: string representation of an Allowed record.
330 static char *show_allowed(struct Allowed *a) {
331     static char buffer[20000];
332     if ( a == 0 ) {
333         sprintf( buffer, "{tap/stdio}" );
334     } else {
335         sprintf( buffer, "%hd (%d) %s %p",
336                  a->port, a->bits, inet_nmtoa( a->addr.bytes, a->addr.width ),
337                  a->psk.key );
338     }
339     return buffer;
340 }
341
342 // Recognize uplink specification
343 static int is_uplink(struct Allowed *a) {
344     return a->bits == (unsigned int) ( a->addr.width * 8 ) && a->port != 0;
345 }
346
347 // Add a new Interface for a Remote. If non-null, the interface is
348 // also added to the interface table.
349 static struct Interface *add_interface(unsigned char *mac,struct Remote *r) {
350     struct Interface *x = calloc( 1, sizeof( struct Interface ) );
351     memcpy( x->mac, mac, sizeof( x->mac ) );
352     x->remote = r;
353     if ( r ) {
354         Interface_ADD( x );
355     }
356     return x;
357 }
358
359 // Add a new remote for a given address and spec.
360 static struct Remote *add_remote(struct SockAddr *a,struct Allowed *s) {
361     struct Remote *r = calloc( 1, sizeof( struct Remote ) );
362     if ( a != 0 ) {
363         memcpy( &r->uaddr, a, sizeof( r->uaddr ) );
364     }
365     r->spec = s;
366     VERBOSE2OUT( "add_remote %s from spec: %s\n",
367                  inet_stoa( &r->uaddr ),
368                  ( s == 0 )? ( (a == 0)? "{tap/stdio}" : "{multicast}" )
369                  : show_allowed( s ) );
370     Remote_ADD( r );
371     return r;
372 }
373
374 // Add a new ignored interface on a channel
375 static int add_ignored(struct Allowed *link,unsigned char *mac) {
376     struct Interface *x = add_interface( mac, 0 );
377     if ( x == 0 ) {
378         return 1; // error: out of memory
379     }
380     Ignored_ADD( link, x );
381     return 0;
382 }
383
384 // Parse ignored interfaces
385 // Comma separated list of MAC addresses
386 static int parse_ignored_interfaces(char *arg,struct Allowed *link) {
387     int a, b, c, d, e, f, g;
388     while ( *arg ) {
389         if ( sscanf( arg,"%x:%x:%x:%x:%x:%x%n",&a,&b,&c,&d,&e,&f,&g ) != 6 ) {
390             // Not a mac addr
391             return 1;
392         }
393         if ( (a|b|c|d|e|f) & ~0xff ) {
394             return 1; // some %x is not hex
395         }
396         unsigned char mac[6] = { a, b, c, d, e, f };
397         if ( add_ignored( link, mac ) ) {
398             // Out of memory ??
399             return 1;
400         }
401         VERBOSEOUT( "Ignoring: %s on channel %s\n",
402                     inet_mtoa( mac ), link->source );
403         arg += g;
404         if ( *arg == 0 ) {
405             break;
406         }
407         if ( *(arg++) != ',' ) {
408             return 1; // Not comma separated
409         }
410     }
411     return 0;
412 }
413
414 //** IP address parsing utility
415 // Clear bits after <bits>
416 static void clearbitsafter(struct CharAddr *a,unsigned int bits) {
417     unsigned int max = a->width * 8;
418     int i;
419     for ( i = a->width; i < 16; i++ ) {
420         a->bytes[ i ] = 0;
421     }
422     for ( i = a->width - 1; i >= 0; i--, max -= 8 ) {
423         if ( max - 8 < bits ) {
424             break;
425         }
426         a->bytes[ i ] = 0;
427     }
428     if ( i >= 0 && max >= bits ) {
429         a->bytes[ i ] &= ( 0xFF << ( bits - max ) );
430     }
431 }
432
433 //** IP address parsing utility
434 // Find the PSK for the given +file+ in the +loaded+ table (of +count+ size)
435 static struct PSK *findLoadedKeyfile(char *file,struct PSK *loaded,int count) {
436     VERBOSE3OUT( "find %s\n", file );
437     for ( count--; count >= 0; count-- ) {
438         if ( strcmp( file, loaded[ count ].keyfile ) ) {
439             VERBOSE3OUT( "found %d\n", count );
440             return &loaded[ count ];
441         }
442     }
443     VERBOSE3OUT( "found nothing\n" );
444     return 0;
445 }
446
447 //** IP address parsing utility
448 // Load a key file into dynamically allocated memory, and update the
449 // given PSK header for it.
450 static void loadkey(struct PSK *psk) {
451     static struct PSK *loaded = 0;
452     static int count = 0;
453     if ( psk->keyfile == 0 ) {
454         return;
455     }
456     struct PSK *old = findLoadedKeyfile( psk->keyfile, loaded, count );
457     if ( old ) {
458         memcpy( psk, old, sizeof( struct PSK ) );
459         return;
460     }
461     int e;
462     unsigned char *p;
463     int n;
464     struct stat filestat;
465     psk->keyfile = strdup( psk->keyfile );
466     int fd = open( (char*) psk->keyfile, O_RDONLY );
467     psk->seed = 0;
468     if ( fd < 0 ) {
469         perror( "open key file" );
470         exit( 1 );
471     }
472     if ( fstat( fd, &filestat ) ) {
473         perror( "stat of key file" );
474         exit( 1 );
475     }
476     psk->key_length = filestat.st_size;
477     if ( psk->key_length < 256 ) {
478         fprintf( stderr, "Too small key file: %d %s\n", psk->key_length,
479                  psk->keyfile );
480         exit( 1 );
481     }
482     psk->key = malloc( psk->key_length );
483     if ( psk->key == 0 ) {
484         fprintf( stderr, "Cannot allocate %d bytes for %s\n",
485                  psk->key_length, psk->keyfile );
486         exit( 1 );
487     }
488     e = psk->key_length;
489     p = psk->key;
490     while ( ( n = read( fd, p, e ) ) > 0 ) {
491         e -= n;
492         p += n;
493     }
494     close( fd );
495     if ( e != 0 ) {
496         fprintf( stderr, "Failed loading key %s\n", psk->keyfile );
497         exit( 1 );
498     }
499     for ( e = 0; (unsigned) e < psk->key_length; e++ ) {
500         psk->seed += psk->key[ e ];
501     }
502     if ( psk->seed == 0 ) {
503         fprintf( stderr, "Bad key %s; adds up to 0\n", psk->keyfile );
504         exit( 1 );
505     }
506     count++;
507     if ( loaded ) {
508         loaded = realloc( loaded, ( count * sizeof( struct PSK ) ) );
509     } else {
510         loaded = malloc( sizeof( struct PSK ) );
511     }
512     memcpy( &loaded[ count-1 ], psk, sizeof( struct PSK ) );
513     VERBOSE3OUT( "%d: %s %d %p %d\n", count-1, psk->keyfile, psk->seed,
514                  psk->key, psk->key_length );
515 }
516
517 //** IP address parsing utility
518 // Fill out a CharAddr and *port from a SockAddr
519 static void set_charaddrport(
520     struct CharAddr *ca,unsigned short *port,struct SockAddr *sa)
521 {
522     memset( ca, 0, sizeof( struct CharAddr ) );
523     ca->width = ( sa->in.sa_family == AF_INET )? 4 : 16;
524     if ( ca->width == 4 ) {
525         memcpy( &ca->in4, &sa->in4.sin_addr, 4 );
526         *port = ntohs( sa->in4.sin_port );
527     } else {
528         memcpy( &ca->in6, &sa->in6.sin6_addr, 16 );
529         *port = ntohs( sa->in6.sin6_port );
530     }
531 }
532
533 //** IP address parsing utility
534 // Fill out a SockAddr from a CharAddr and port
535 static void set_sockaddr(struct SockAddr *sa,struct CharAddr *ca,int port) {
536     memset( sa, 0, sizeof( struct SockAddr ) );
537     if ( ca->width == 4 ) {
538         sa->in4.sin_family = AF_INET;
539         sa->in4.sin_port = htons( port );
540         memcpy( &sa->in4.sin_addr, &ca->in4, 4 );
541     } else {
542         sa->in6.sin6_family = AF_INET6;
543         sa->in6.sin6_port = htons( port );
544         memcpy( &sa->in6.sin6_addr, &ca->in6, 16 );
545     }
546 }
547
548 //** IP address parsing utility
549 // Capture an optional port sub phrase [:<port>]
550 static int parse_port(char *port,struct Allowed *into) {
551     into->port = 0;
552     if ( port ) {
553         *(port++) = 0;
554         int p;
555         if ( sscanf( port, "%d", &p ) != 1 || p < 1 || p > 65535 ) {
556             // Bad port number
557             return 1;
558         }
559         into->port = p;
560     }
561     return 0;
562 }
563
564 //** IP address parsing utility
565 // Capture an optional bits sub phrase [/<bits>]
566 static int parse_bits(char *bits,int max,struct Allowed *into) {
567     into->bits = max;
568     if ( bits ) {
569         *(bits++) = 0;
570         int b;
571         if ( sscanf( bits, "%d", &b ) != 1 || b < 0 || b > max ) {
572             return 1;
573         }
574         into->bits = b;
575     }
576     return 0;
577 }
578
579 //** IP address parsing utility
580 // Parse a command line argument as a declaration of an allowed
581 // remote into the given <addr>.
582 // Return 0 if ok and 1 otherwise
583 // Formats: <ipv4-address>[/<bits>][:<port>][=keyfile]
584 // Formats: <ipv6-address>[/<bits>][=keyfile]
585 // Formats: \[<ipv6-address>[/<bits>]\][:<port>][=keyfile]
586 // Formats: hostname:port[=keyfile]
587 static int parse_allowed(char *arg,struct Allowed *into) {
588     static char buffer[10000];
589     int n = strlen( arg );
590     if ( n > 9000 ) {
591         return 1; // excessively large argument
592     }
593     strcpy( buffer, arg );
594     into->source = arg;
595     char * keyfile = strchr( buffer, '=' );
596     if ( keyfile ) {
597         *(keyfile++) = 0;
598         into->psk.keyfile = keyfile;
599     }
600 #define B(b) b, b+1, b+2, b+3
601     if ( sscanf( buffer, "%hhu.%hhu.%hhu.%hhu", B(into->addr.bytes) ) == 4 ) {
602 #undef B
603         // ipv4 address
604         into->addr.width = 4;
605         if ( parse_port( strchr( buffer, ':' ), into ) ) {
606             fprintf( stderr, "bad port\n" );
607             return 1;
608         }
609         if ( parse_bits( strchr( buffer, '/' ), 32, into ) ) {
610             fprintf( stderr, "bad bits\n" );
611             return 1;
612         }
613         return 0;
614     }
615     // ipv6 address
616     char * address = buffer;
617     into->port = 0;
618     if ( *buffer == '[' ) {
619         // bracketed form, necessary for port
620         char *end = strchr( buffer, ']' );
621         if ( end == 0 ) {
622             return 1; // bad argument
623         }
624         address++;
625         *(end++) = 0;
626         if ( *end == ':' && parse_port( end, into ) ) {
627             return 1;
628         }
629     }
630     into->addr.width = 16;
631     if ( parse_bits( strchr( address, '/' ), 128, into ) ) {
632         return 1;
633     }
634     if ( inet_pton( AF_INET6, address, into->addr.bytes ) != 1 ) {
635         return 1; // Bad IPv6
636     }
637     return 0;
638 }
639
640 //** IP address parsing utility
641 // Add a new channel spec into the <allowed> table
642 // spec == 0 for the tap/stdio channel
643 static struct Allowed *add_allowed(char *spec) {
644     struct Allowed *into = calloc( 1, sizeof(struct Allowed) );
645     htable x = HTABLEINIT( struct Interface, mac, hashcode_mac );
646     into->ignored_mac = x;
647     if ( spec != 0 ) {
648         if ( parse_allowed( spec, into ) ) {
649             fprintf( stderr, "Bad remote spec: %s\n", spec );
650             return 0;
651         }
652     }
653     int i;
654     if ( allowed.table == 0 ) {
655         // First entry.
656         allowed.table = calloc( 1, sizeof(struct Allowed*) );
657         allowed.count = 1;
658         i = 0;
659     } else {
660         i = allowed.count++;
661         allowed.table = realloc( allowed.table,
662                                  allowed.count * sizeof(struct Allowed*) );
663         if ( allowed.table == 0 ) {
664             fprintf( stderr, "OUT OF MEMORY\n" );
665             exit( 1 );
666         }
667     }
668     allowed.table[i] = into;
669
670     loadkey( &into->psk );
671     VERBOSE3OUT( "Allowed %s { %s }\n", into->source, show_allowed( into ) );
672     if ( is_uplink( into ) ) {
673         struct SockAddr addr;
674         set_sockaddr( &addr, &into->addr, into->port );
675         VERBOSEOUT( "Add uplink %s\n", show_allowed( into ) );
676         (void) add_remote( &addr, into );
677     }
678     return into;
679 }
680
681 static int parse_threads_count(char *arg) {
682     if ( ( sscanf( arg, "%u", &threads_count ) != 1 ) || threads_count < 1 ) {
683         return 1;
684     }
685     VERBOSEOUT( "** Threads count = %d\n", threads_count );
686     return 0;
687 }
688
689 static int parse_buffers_count(char *arg) {
690     if ( ( sscanf( arg, "%u", &buffers_count ) != 1 ) || buffers_count < 1 ) {
691         return 1;
692     }
693     VERBOSEOUT( "** Buffers count = %d\n", buffers_count );
694     return 0;
695 }
696
697 //** IP address parsing utility for multicast phrase
698 // Return 0 if ok and 1 otherwise
699 // Formats: <ipv4-address>:<port>[=keyfile]
700 // The ipv4 address should be a multicast address in ranges
701 // 224.0.0.0/22, 232.0.0.0/7, 234.0.0.0/8 or 239.0.0.0/8
702 // though it's not checked here.
703 static int parse_mcast(char *arg) {
704     static char buffer[10000];
705     int n = strlen( arg );
706     if ( n > 9000 ) {
707         return 1; // excessively large argument
708     }
709     memcpy( buffer, arg, n );
710     char *p = buffer + n - 1;
711     for ( ; p > buffer && *p != ':' && *p != '='; p-- ) { }
712     if ( *p == '=' ) {
713         mcast.psk.keyfile = p+1;
714         *p = 0;
715         loadkey( &mcast.psk );
716         for ( ; p > buffer && *p != ':' ; p-- ) { }
717     }
718     if ( *p != ':' ) {
719         fprintf( stderr, "Multicast port is required\n" );
720         return 1; // Port number is required
721     }
722     *(p++) = 0;
723     if ( inet_pton( AF_INET, buffer, &mcast.group.imr_multiaddr.s_addr )==0 ) {
724         fprintf( stderr, "Multicast address required\n" );
725         return 1;
726     }
727     char *e;
728     long int port = strtol( p, &e, 10 );
729     if ( *e != 0 || port < 1 || port > 65535 ) {
730         fprintf( stderr, "Bad multicast port\n" );
731         return 1;
732     }
733     mcast.group.imr_address.s_addr = htonl(INADDR_ANY);
734     mcast.sock.in4.sin_family = AF_INET;
735     mcast.sock.in4.sin_addr.s_addr = htonl(INADDR_ANY);
736     mcast.sock.in4.sin_port = htons( atoi( p ) );
737     return 0;
738 }
739
740 //** IP address parsing utility for UDP source address
741 // Return 0 if ok and 1 otherwise
742 // Formats: <ipv4-address> or <ipv6-address>
743 // The ipv4 address should be a multicast address in ranges
744 // 224.0.0.0/22, 232.0.0.0/7, 234.0.0.0/8 or 239.0.0.0/8
745 // though it's not checked here.
746 static int parse_udp_source(char *arg) {
747     if ( inet_pton( AF_INET6, arg, udp_source.address ) ) {
748         // An ipv6 address is given.
749         if ( udp6 ) {
750             udp_source.family = AF_INET6;
751             return 0;
752         }
753         return 1;
754     }
755     if ( ! inet_pton( AF_INET, arg, udp_source.address ) ) {
756         return 1;
757     }
758
759     // An ipv4 address is given.
760     if ( udp6 ) {
761         // Translate into ipv6-encoded ipv4
762         memmove( udp_source.address + 12, udp_source.address, 4 );
763         memset( udp_source.address, 0, 10 );
764         memset( udp_source.address + 10, -1, 2 );
765         udp_source.family = AF_INET6;
766     } else {
767         udp_source.family = AF_INET;
768     }
769     return 0;
770 }
771
772 // Utility that sets upt the multicast socket, which is used for
773 // receiving multicast packets.
774 static void setup_mcast() {
775     // set up ipv4 socket
776     if ( ( mcast.fd = socket( AF_INET, SOCK_DGRAM, 0 ) ) == 0 ) {
777         perror( "creating socket");
778         exit(1);
779     }
780     if ( setsockopt( mcast.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
781                      (char *) &mcast.group, sizeof( mcast.group ) ) < 0) {
782         perror( "Joining multicast group" );
783         exit( 1 );
784     }
785     int reuse = 1;
786     if ( setsockopt( mcast.fd, SOL_SOCKET, SO_REUSEADDR,
787                      &reuse, sizeof( int ) ) < 0 ) {
788         perror( "SO_REUSEADDR" );
789         exit( 1 );
790     }
791     if ( bind( mcast.fd, (struct sockaddr*) &mcast.sock.in,
792                sizeof( struct sockaddr ) ) ) {
793         fprintf( stderr, "Error binding socket!\n");
794         exit(1);
795     }
796     // Change mcast address to be the group multiaddress, and add
797     // a persistent "remote" for it.
798     mcast.sock.in4.sin_addr.s_addr = mcast.group.imr_multiaddr.s_addr;
799     add_remote( &mcast.sock, 0 );
800 }
801
802 // Find the applicable channel rule for a given ip:port address
803 static struct Allowed *is_allowed_remote(struct SockAddr *addr) {
804     struct CharAddr ca;
805     int width = ( addr->in.sa_family == AF_INET )? 4 : 16;
806     unsigned short port;
807     int i = 0;
808     for ( ; (unsigned) i < allowed.count; i++ ) {
809         struct Allowed *a = allowed.table[i];
810         if ( a->addr.width != width ) {
811             continue;
812         }
813         set_charaddrport( &ca, &port, addr );
814         if ( a->port != 0 && a->port != port ) {
815             continue;
816         }
817         clearbitsafter( &ca, a->bits );
818         if ( memcmp( &ca, &a->addr, sizeof( struct CharAddr ) ) == 0 ) {
819             return a;
820         }
821     }
822     return 0; // Disallowed
823 }
824
825 // Simple PSK encryption:
826 //
827 // First, xor each byte with a key byte that is picked from the key
828 // by means of an index that includes the prior encoding. Also,
829 // compute the sum of encrypted bytes into a "magic" that is added the
830 // "seed" for seeding the random number generator. Secondly reorder
831 // the bytes using successive rand number picks from the seeded
832 // generator.
833 //
834 static void encrypt(unsigned char *buf,unsigned int n,struct PSK *psk) {
835     unsigned int k;
836     unsigned int r;
837     unsigned char b;
838     unsigned int magic;
839     VERBOSE3OUT( "encrypt by %s %p\n", psk->keyfile, psk->key );
840     for ( k = 0, r = 0, magic = 0; k < n; k++ ) {
841         r = ( r + magic + k ) % psk->key_length;
842         buf[k] ^= psk->key[ r ];
843         magic += buf[k];
844     }
845     pthread_mutex_lock( &crypting );
846     srand( psk->seed + magic );
847     for ( k = 0; k < n; k++ ) {
848         r = rand() % n;
849         b = buf[k];
850         buf[k] = buf[r];
851         buf[r] = b;
852     }
853     pthread_mutex_unlock( &crypting );
854 }
855
856 // Corresponding decryption procedure .
857 static void decrypt(unsigned char *buf,unsigned int n,struct PSK *psk) {
858     unsigned int randoms[ BUFSIZE ];
859     unsigned int k;
860     unsigned int r;
861     unsigned char b;
862     unsigned int magic = 0;
863     for ( k = 0; k < n; k++ ) {
864         magic += buf[k];
865     }
866     pthread_mutex_lock( &crypting );
867     srand( psk->seed + magic );
868     for ( k = 0; k < n; k++ ) {
869         randoms[k] = rand() % n;
870     }
871     pthread_mutex_unlock( &crypting );
872     for ( k = n; k > 0; ) {
873         r = randoms[ --k ];
874         b = buf[k];
875         buf[k] = buf[r];
876         buf[r] = b;
877     }
878     for ( k = 0, r = 0, magic = 0; k < n; k++ ) {
879         r = ( r + magic + k ) % psk->key_length;
880         magic += buf[k];
881         buf[k] ^= psk->key[r];
882     }
883 }
884
885 // Write a buffer data to given file descriptor (basically tap_fd in
886 // this program). This is never fragmented.
887 static int dowrite(int fd, unsigned char *buf, int n) {
888     int w;
889     if ( ( w = write( fd, buf, n ) ) < 0){
890         perror( "Writing data" );
891         w = -1;
892     }
893     return w;
894 }
895
896 // Write to the tap/stdio; adding length prefix for stdio
897 static int write_tap(unsigned char *buf, int n) {
898     uint8_t tag0 = *( buf + 12 );
899     if ( tag0 == 8 ) {
900         uint16_t size = ntohs( *(uint16_t*)(buf + 16) );
901         if ( size <= 1500 ) {
902             if ( ( verbose >= 2 ) && ( n != size + 14 ) ) {
903                 VERBOSEOUT( "clip %d to %d\n", n, size + 14 );
904             }
905             n = size + 14; // Clip of any tail
906         }
907     }
908     if ( stdio ) {
909         uint16_t plength = htons( n );
910         if ( dowrite( 1, (unsigned char *) &plength,
911                       sizeof( plength ) ) < 0 ) {
912             return -11;
913         }
914         return dowrite( 1, buf, n );
915     }
916     return dowrite( tap_fd, buf, n );
917 }
918
919 // Write a packet via the given Interface with encryption as specified.
920 static void write_remote(unsigned char *buf, int n,struct Remote *r) {
921     // A packet buffer
922     unsigned char output[ BUFSIZE ];
923     if ( n < 12 ) {
924         VERBOSE2OUT( "SENDing %d bytes to %s\n", n, inet_stoa( &r->uaddr ) );
925     } else {
926         VERBOSE2OUT( "SENDing %d bytes %s -> %s to %s\n", n,
927                      inet_mtoa( buf+6 ), inet_mtoa( buf ),
928                      inet_stoa( &r->uaddr ) );
929     }
930     memcpy( output, buf, n ); // Use the private buffer for delivery
931     // Apply the TPG quirk
932     if ( tpg_quirk && ( n > 1460 ) && ( n < 1478 ) ) {
933         VERBOSE2OUT( "tpg quirk applied\n" );
934         n = 1478; // Add some "random" tag-along bytes
935     }
936     if ( r->spec == 0 ) {
937         if ( r->uaddr.in.sa_family == 0 ) {
938             // Output to tap/stdio
939             if ( write_tap( buf, n ) < 0 ) {
940                 // panic error
941                 fprintf( stderr, "Cannot write to tap/stdio: exiting!\n" );
942                 exit( 1 );
943             }
944             return;
945         }
946         // Fall through for multicast
947         if ( mcast.psk.keyfile ) {
948             encrypt( output, n, &mcast.psk );
949         }
950     } else if ( r->spec->psk.keyfile ) {
951         encrypt( output, n, &r->spec->psk );
952     }
953     // Setup the packet addressing
954     struct in_pktinfo pkt4info = {
955         .ipi_ifindex = 0,  /* Interface index */
956         .ipi_spec_dst.s_addr = 0, /* Local address */
957         .ipi_addr.s_addr = 0,     /* Header Destination address */
958     };
959     struct in6_pktinfo pkt6info = {
960         .ipi6_addr.s6_addr32 = { 0, 0, 0, 0 },
961         .ipi6_ifindex = 0,
962     };
963     void *pktinfo = 0;
964     int pktinfosize = 0;
965     struct sockaddr_in *sock4 = &r->uaddr.in4;
966     struct sockaddr_in6 *sock6 = &r->uaddr.in6;
967     void *sock;
968     size_t size;
969     if ( udp6 ) {
970         // Note that the size of +struct sockaddr_in6+ is actually
971         // larger than the size of +struct sockaddr+ (due to the
972         // addition of the +sin6_flowinfo+ field). It results in the
973         // following cuteness for passing arguments to +sendto+.
974         sock = sock6;
975         size = sizeof( struct sockaddr_in6 );
976         VERBOSE2OUT( "IPv6 UDP %d %s\n",
977                      udp_fd, inet_stoa( &r->laddr ) );
978         if ( r->laddr.in.sa_family ) {
979             memcpy( &pkt6info.ipi6_addr, &sock6->sin6_addr, 16 );
980             pktinfo = &pkt6info;
981             pktinfosize = sizeof( pkt6info );
982         }
983     } else {
984         sock = sock4;
985         size = sizeof( struct sockaddr_in );
986         VERBOSE2OUT( "IPv4 UDP %d %s\n",
987                      udp_fd, inet_stoa( &r->laddr ) );
988         if ( r->laddr.in.sa_family ) {
989             memcpy( &pkt4info.ipi_spec_dst, &sock4->sin_addr, 4 );
990             pktinfo = &pkt4info;
991             pktinfosize = sizeof( pkt4info );
992         }
993     }
994     VERBOSE2OUT( "SEND %d bytes from %s to %s [%s -> %s]\n",
995                  n,
996                  inet_stoa( &r->laddr ),
997                  inet_stoa( &r->uaddr ),
998                  ( n < 12 )? "" : inet_mtoa( buf+6 ),
999                  ( n < 12 )? "" : inet_mtoa( buf )
1000               );
1001     // IS sendmsg thread safe??
1002     struct iovec data[1] = {{ output, n }};
1003     (void)pktinfo;
1004     (void)pktinfosize;
1005     struct msghdr msg = {
1006         .msg_name = sock,
1007         .msg_namelen = size,
1008         .msg_iov = data,
1009         .msg_iovlen = 1,
1010         .msg_control = 0, //pktinfo,
1011         .msg_controllen = 0, //pktinfosize,
1012         .msg_flags = 0 // unused
1013     };
1014     if ( sendmsg( udp_fd, &msg, 0 ) < n ) {
1015         perror( "Writing socket" );
1016         // Invalidate remote temporarily instead? But if it's an
1017         // "uplink" it should be retried eventually...
1018         // For now: just ignore the error.
1019         // exit( 1 );
1020     }
1021 }
1022
1023 // Delete a Remote and all its interfaces
1024 static void delete_remote(struct Remote *r) {
1025     VERBOSE2OUT( "DELETE Remote and all its interfaces %s\n",
1026                  inet_stoa( &r->uaddr ) );
1027     unsigned int i = 0;
1028     struct Interface *x;
1029     Interface_LOCK;
1030     for ( ; i < remotes.by_mac.size; i++ ) {
1031         unsigned char *tmp = remotes.by_mac.data[i];
1032         if ( tmp == 0 || tmp == (unsigned char *)1 ) {
1033             continue;
1034         }
1035         x = (struct Interface *) tmp;
1036         if ( x->remote == r ) {
1037             Interface_DEL( x );
1038             free( x );
1039         }
1040     }
1041     Interface_UNLOCK;
1042     Remote_DEL( r );
1043     free( r );
1044 }
1045
1046 // Unmap an ipv4-mapped ipv6 address
1047 static void unmap_if_mapped(struct SockAddr *s) {
1048     if ( s->in.sa_family != AF_INET6 ||
1049          memcmp( "\000\000\000\000\000\000\000\000\000\000\377\377",
1050                  &s->in6.sin6_addr, 12 ) ) {
1051         return;
1052     }
1053     VERBOSE2OUT( "unmap %s\n",
1054                  inet_nmtoa( (unsigned char*) s, sizeof( struct SockAddr ) ) );
1055     s->in.sa_family = AF_INET;
1056     memcpy( &s->in4.sin_addr, s->in6.sin6_addr.s6_addr + 12, 4 );
1057     memset( s->in6.sin6_addr.s6_addr + 4, 0, 12 );
1058     VERBOSE2OUT( "becomes %s\n",
1059                  inet_nmtoa( (unsigned char*) s, sizeof( struct SockAddr ) ) );
1060 }
1061
1062 // Route the packet from the given src
1063 static struct Interface *input_check(
1064     unsigned char *buf,ssize_t len,struct SockAddr *src )
1065 {
1066     VERBOSE2OUT( "RECV %ld bytes from %s\n", len, inet_stoa( src ) );
1067     struct Remote *r = 0;
1068     struct timeval now = { 0 };
1069     if ( gettimeofday( &now, 0 ) ) {
1070         perror( "RECV time" );
1071         now.tv_sec = time( 0 );
1072     }
1073     Remote_FIND( src, r );
1074     if ( r == 0 ) {
1075         struct Allowed *a = is_allowed_remote( src );
1076         if ( a == 0 ) {
1077             VERBOSEOUT( "Ignoring %s\n", inet_stoa( src ) );
1078             return 0; // Disallowed
1079         }
1080         VERBOSEOUT( "New remote %s by %s\n", inet_stoa( src ), a->source );
1081         r = add_remote( src, a );
1082         //r->rec_when = now; // Set activity stamp of new remote
1083     }
1084     if ( len < 12 ) {
1085         // Ignore short data, but maintain channel
1086         r->rec_when = now; // Update activity stamp touched remote
1087         if ( len > 0 ) {
1088             VERBOSEOUT( "Ignoring %ld bytes from %s\n",
1089                         len, inet_stoa( src ) );
1090         }
1091         return 0;
1092     }
1093     // Now decrypt the data as needed
1094     if ( r->spec ) {
1095         if ( r->spec->psk.seed ) {
1096             decrypt( buf, len, &r->spec->psk );
1097         }
1098     } else if ( r->uaddr.in.sa_family == 0 && mcast.psk.keyfile ) {
1099         decrypt( buf, len, &mcast.psk );
1100     }
1101     VERBOSE2OUT( "RECV %s -> %s from %s\n",
1102                  inet_mtoa( buf+6 ), inet_mtoa( buf ),
1103                  inet_stoa( &r->uaddr ) );
1104     // Note: the payload is now decrypted, and known to be from +r+
1105     struct Interface *x = 0;
1106     // Packets concerning an ignored interface should be ignored.
1107     if ( r->spec && r->spec->ignored_mac.data ) {
1108         Ignored_FIND( r->spec, buf+6, x );
1109         if ( x ) {
1110             VERBOSE2OUT( "Dropped MAC %s from %s on %s\n",
1111                          inet_mtoa( buf+6 ), inet_stoa( &r->uaddr ),
1112                          r->spec->source );
1113             return 0;
1114         }
1115         Ignored_FIND( r->spec, buf, x );
1116         if ( x ) {
1117             VERBOSE2OUT( "Dropped MAC %s to %s on %s\n",
1118                          inet_mtoa( buf ), inet_stoa( &r->uaddr ),
1119                          r->spec->source );
1120             return 0;
1121         }
1122     }
1123     Interface_FIND( buf+6, x );
1124     if ( x == 0 ) {
1125         // Totally new MAC. Should bind it to the remote
1126         VERBOSEOUT( "New MAC %s from %s\n",
1127                     inet_mtoa( buf+6 ), inet_stoa( src ) );
1128         x = add_interface( buf+6, r );
1129         r->rec_when = now; // Update activity stamp for remote
1130         x->rec_when = now;
1131         return x;
1132     }
1133     // Seen that MAC already
1134     if ( x->remote == r ) {
1135         VERBOSE2OUT( "RECV %s from %s again\n",
1136                      inet_mtoa( buf+6 ), inet_stoa( &x->remote->uaddr ) );
1137         r->rec_when = now; // Update activity stamp
1138         x->rec_when = now; // Update activity stamp
1139         return x;
1140     }
1141     // MAC clash from two different connections
1142     // r = current
1143     // x->remote = previous
1144     VERBOSE2OUT( "RECV %s from %s previously from %s\n",
1145               inet_mtoa( buf+6 ),
1146               inet_stoa( &r->uaddr ),
1147               inet_stoa( &x->remote->uaddr ) );
1148     if ( r->spec ) {
1149         // The packet source MAC has arrived on other than its
1150         // previous channel. It thus gets dropped if tap/stdin is the
1151         // primary channel, or the time since the last packet for that
1152         // interface is less than RECENT_MICROS, with different limits
1153         // for broadcast and unicast.
1154         int64_t dmac = DIFF_MICROS( &now, &x->rec_when);
1155         if ( x->remote->spec == 0 || RECENT_MICROS( *buf & 1, dmac ) ) {
1156             if ( verbose >= 2 ) {
1157                 fprintf(
1158                     stderr,
1159                     "Dropped. MAC %s (%ld) from %s, should be %s\n",
1160                     inet_mtoa( buf+6 ), dmac,
1161                     inet_stoa( src ), inet_stoa( &x->remote->uaddr ) );
1162             }
1163             return 0;
1164         }
1165         // Check if previous package on the interface was recent
1166     } else if ( r->uaddr.in.sa_family ) {
1167         // Multicast incoming clashing with tap/stdio
1168         VERBOSE3OUT( "Dropped multicast loopback\n" );
1169         return 0;
1170     }
1171
1172     // New remote takes over the MAC
1173     VERBOSEOUT( "MAC %s from %s cancels previous %s\n",
1174                 inet_mtoa( buf+6 ), inet_stoa( src ),
1175                 inet_stoa( &x->remote->uaddr ) );
1176     x->remote = r; // Change remote for MAC
1177     // Note that this may leave the old x->remote without any interface
1178     r->rec_when = now; // Update activity stamp
1179     x->rec_when = now; // Update activity stamp
1180     return x;
1181 }
1182
1183 // Check packet and deliver out
1184 static void route_packet(PacketItem *pi) {
1185     unsigned char *buf = pi->buffer;
1186     int len = pi->len;
1187     struct SockAddr *src = &pi->src;
1188     struct Interface *x = input_check( buf, len, src );
1189     if ( x == 0 ) {
1190         return; // not a nice packet
1191     }
1192     if ( ( *buf & 1 ) == 0 ) {
1193         // unicast
1194         struct Interface *y = 0; // reuse for destination interface
1195         Interface_FIND( buf, y );
1196         if ( y == 0 ) {
1197             VERBOSE2OUT( "RECV %s -> %s from %s without channel and dropped\n",
1198                         inet_mtoa( buf+6 ), inet_mtoa( buf ),
1199                         inet_stoa( &x->remote->uaddr ) );
1200             return;
1201         }
1202         if ( x->remote == y->remote ) {
1203             VERBOSEOUT( "RECV loop for %s -> %s from %s to %s\n",
1204                         inet_mtoa( buf+6 ), inet_mtoa( buf ),
1205                         inet_stoa( &x->remote->uaddr ),
1206                         inet_stoa( &y->remote->uaddr ) );
1207             Interface_DEL( y ); // Need to see this interface again
1208             return;
1209         }
1210         VERBOSE2OUT( "RECV route %s -> %s to %s\n",
1211                      inet_mtoa( buf+6 ), inet_mtoa( buf ),
1212                      inet_stoa( &y->remote->uaddr ) );
1213         // Set the local address for the remote
1214         memcpy( &y->remote->laddr, &pi->dst, sizeof( pi->dst ) );
1215         write_remote( buf, len, y->remote );
1216         return;
1217     }
1218     // broadcast. +x+ is source interface
1219     // x->rec_when is not updated 
1220     struct timeval now = { 0 };
1221     if ( gettimeofday( &now, 0 ) ) {
1222         perror( "RECV time" );
1223         now.tv_sec = time( 0 );
1224     }
1225     VERBOSE2OUT( "BC %s -> %s from %s\n",
1226                  inet_mtoa( buf+6 ), inet_mtoa( buf ),
1227                  inet_stoa( &x->remote->uaddr ) );
1228     struct Remote *r;
1229     unsigned int i = 0;
1230     Remote_LOCK;
1231     for ( ; i < remotes.by_addr.size; i++ ) {
1232         unsigned char *tmp = remotes.by_addr.data[i];
1233         if ( tmp == 0 || tmp == (unsigned char *)1 ) {
1234             continue;
1235         }
1236         r = (struct Remote *) tmp;
1237         VERBOSE3OUT( "BC check %s\n", inet_stoa( &r->uaddr ) );
1238         if ( r == x->remote ) {
1239             VERBOSE3OUT( "BC r == x->remote\n" );
1240             continue;
1241         }
1242         if ( r->spec && ! is_uplink( r->spec ) &&
1243              DIFF_MICROS( &now, &r->rec_when ) > VERYOLD_MICROS ) {
1244             // remove old downlink connection
1245             VERBOSEOUT( "Old remote discarded %s (%ld)\n",
1246                         inet_stoa( &r->uaddr ),
1247                         TIME_MICROS( &r->rec_when ) );
1248             // Removing a downlink might have threading implications
1249             delete_remote( r );
1250             continue;
1251         }
1252         // Send packet to the remote
1253         // Only no-clash or to the tap/stdin
1254         write_remote( buf, len, r );
1255     }
1256     Remote_UNLOCK;
1257 }
1258
1259 // The packet handling queues
1260 static struct {
1261     Queue full;
1262     Queue free;
1263     sem_t reading;
1264 } todolist;
1265
1266 // The threadcontrol program for handling packets.
1267 static void *packet_handler(void *data) {
1268     (void) data;
1269     for ( ;; ) {
1270         PacketItem *todo = (PacketItem *) Queue_getItem( &todolist.full );
1271         if ( todo->fd == mcast.fd ) {
1272             // Patch in the multicast address as source for multicast packet
1273             memcpy( &todo->src, &mcast.sock, sizeof( todo->src ) );
1274             route_packet( todo );
1275         } else {
1276             if ( udp6 ) {
1277                 unmap_if_mapped( &todo->src );
1278             }
1279             route_packet( todo );
1280         }
1281         Queue_addItem( &todolist.free, (QueueItem*) todo );
1282     }
1283     return 0;
1284 }
1285
1286 void todolist_initialize(int nbuf,int nthr) {
1287     if ( pthread_mutex_init( &todolist.full.mutex, 0 ) ||
1288          sem_init( &todolist.full.count, 0, 0 ) ) {
1289         perror( "FATAL" );
1290         exit( 1 );
1291     }
1292     if ( pthread_mutex_init( &todolist.free.mutex, 0 ) ||
1293          sem_init( &todolist.free.count, 0, 0 ) ) {
1294         perror( "FATAL" );
1295         exit( 1 );
1296     }
1297     if ( sem_init( &todolist.reading, 0, 1 ) ) {
1298         perror( "FATAL" );
1299         exit( 1 );
1300     }
1301     Queue_initialize( &todolist.free, nbuf, sizeof( PacketItem ) );
1302     for ( ; nthr > 0; nthr-- ) {
1303         pthread_t thread; // Temporary thread id
1304         pthread_create( &thread, 0, packet_handler, 0 );
1305     }
1306 }
1307
1308 static ssize_t recvpacket(int fd,PacketItem *p) {
1309     int flags = 0;
1310     socklen_t addrlen =
1311         udp6? sizeof( p->src.in6 ) : sizeof( p->src.in4 );
1312     struct iovec buffer = {
1313         .iov_base = p->buffer,
1314         .iov_len = BUFSIZE
1315     };
1316     char data[1000];
1317     struct msghdr msg = {
1318         .msg_name =  &p->src.in,
1319         .msg_namelen = addrlen,
1320         .msg_iov = &buffer,
1321         .msg_iovlen = 1,
1322         .msg_control = data,
1323         .msg_controllen = sizeof( data ),
1324         .msg_flags = 0 // Return value
1325     };
1326     p->len = recvmsg( fd, &msg, flags );
1327     struct cmsghdr *cmsg = CMSG_FIRSTHDR( &msg );
1328     VERBOSE3OUT( "anc %p %ld\n", cmsg, p->len );
1329     for ( ; cmsg; cmsg = CMSG_NXTHDR( &msg, cmsg ) ) {
1330         VERBOSE3OUT( "anc type = %d\n", cmsg->cmsg_type );
1331     }
1332     cmsg = CMSG_FIRSTHDR( &msg );
1333     if ( cmsg ) {
1334         if ( udp6 ) {
1335             struct in6_pktinfo *pinf = (struct in6_pktinfo*) CMSG_DATA( cmsg );
1336             p->dst.in6.sin6_family = AF_INET6;
1337             memcpy( &p->dst.in6.sin6_addr, &pinf->ipi6_addr, 16 );
1338             VERBOSE3OUT( "DEST= udp6 %d %s\n",
1339                          pinf->ipi6_ifindex, inet_stoa( &p->dst ) );
1340         } else {
1341             struct in_pktinfo *pinf = (struct in_pktinfo*) CMSG_DATA( cmsg );
1342             p->dst.in4.sin_family = AF_INET;
1343             p->dst.in4.sin_addr = pinf->ipi_addr;
1344             VERBOSE3OUT( "DEST= %d %s\n",
1345                          pinf->ipi_ifindex, inet_stoa( &p->dst ) );
1346         }
1347     }
1348     return p->len;
1349 }
1350
1351
1352
1353 // Read a full UDP packet into the given buffer, associate with a
1354 // connection, or create a new connection, the decrypt the as
1355 // specified, and capture the sender MAC address. The connection table
1356 // is updated for the new MAC address, However, if there is then a MAC
1357 // address clash in the connection table, then the associated remote
1358 // is removed, and the packet is dropped.
1359 static void *doreadUDP(void *data) {
1360     int fd = ((ReaderData *) data)->fd;
1361     while ( 1 ) {
1362         PacketItem *todo = (PacketItem *) Queue_getItem( &todolist.free );
1363         todo->fd = fd;
1364         memset( &todo->src, 0, sizeof( struct SockAddr ) );
1365         memset( &todo->dst, 0, sizeof( struct SockAddr ) );
1366         todo->len = 0;
1367         VERBOSE3OUT( "Reading packet\n" );
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 port, 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", &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( 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( 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 }