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