1 // This program is a UDP based tunneling of stdin/out Ethernet packets.
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
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.
20 #include <linux/if_tun.h>
25 #include <sys/ioctl.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
38 // "Private Shared Key" details.
41 unsigned int seed; // Encryption seed
42 unsigned char *key; // Encryption key
43 unsigned int key_length; // Encryption key length
46 // Compacted IP address ipv4/ipv6
48 int width; // 4=ipv4 and 16=ipv6
50 unsigned char bytes[16];
56 // Details of channel rules.
58 char *source; // Orginal rule
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
66 // Details of actualized connections.
68 struct SockAddr uaddr; // The remote IP address
69 struct SockAddr iaddr; // The receiving IP address
70 struct Allowed *spec; // Rule being instantiated
71 struct timeval rec_when; // Last received packet time, in seconds
74 // Details of an interface at a remote.
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;
81 // Maximal packet size .. allow for jumbo frames (9000)
84 typedef struct _PacketItem {
90 unsigned char buffer[ BUFSIZE ];
93 typedef struct _ReaderData {
97 // heartbeat interval, in seconds
99 #define HEARTBEAT_MICROS ( HEARTBEAT * 1000000 )
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) )
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 ))
110 // VERYOLD_MICROSS is used for discarding downlink remotes whose latest
111 // activity is older than this.
112 #define VERYOLD_MICROS 180000000
116 // Allowed remote specs are held in a table sorted by IP prefix.
118 struct Allowed **table;
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);
132 htable by_mac; // struct Interface hash table
133 htable by_addr; // struct Remote hash table
135 .by_mac = HTABLEINIT( struct Interface, mac, hashcode_mac ),
136 .by_addr = HTABLEINIT( struct Remote, uaddr, hashcode_uaddr )
139 #define Interface_LOCK if ( pthread_mutex_lock( &remotes.by_mac.lock ) ) { \
140 perror( "FATAL" ); exit( 1 ); }
142 #define Interface_UNLOCK if (pthread_mutex_unlock( &remotes.by_mac.lock ) ) { \
143 perror( "FATAL" ); exit( 1 ); }
145 #define Interface_FIND(m,r) \
146 htfind( &remotes.by_mac, m, (unsigned char **)&r )
148 #define Interface_ADD(r) \
149 htadd( &remotes.by_mac, (unsigned char *)r )
151 #define Interface_DEL(r) \
152 htdelete( &remotes.by_mac, (unsigned char *) r )
154 #define Remote_LOCK if ( pthread_mutex_lock( &remotes.by_addr.lock ) ) { \
155 perror( "FATAL" ); exit( 1 ); }
157 #define Remote_UNLOCK if ( pthread_mutex_unlock( &remotes.by_addr.lock ) ) { \
158 perror( "FATAL" ); exit( 1 ); }
160 #define Remote_FIND(a,r) \
161 htfind( &remotes.by_addr, (unsigned char *)a, (unsigned char **) &r )
163 #define Remote_ADD(r) \
164 htadd( &remotes.by_addr, (unsigned char *) r )
166 #define Remote_DEL(r) \
167 htdelete( &remotes.by_addr, (unsigned char *) r )
169 #define Ignored_FIND(a,m,x) \
170 htfind( &a->ignored_mac, m, (unsigned char **)&x )
172 #define Ignored_ADD(a,x) \
173 htadd( &a->ignored_mac, (unsigned char *)x )
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
180 static int threads_count = 0;
181 static int buffers_count = 0;
183 // Setup for multicast channel
185 struct ip_mreqn group;
186 struct SockAddr sock;
191 // Flag to signal the UDP socket as being ipv6 or not (forced ipv4)
194 // The given UDP source address, if any
197 unsigned char address[16];
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;
204 // Flag whether to make some stderr outputs or not.
205 // 1 = normal verbosity, 2 = more output, 3 = source debug level stuff
208 // Note: allows a thread to lock/unlock recursively
209 static pthread_mutex_t crypting = PTHREAD_MUTEX_INITIALIZER;
211 // Note: allows a thread to lock/unlock recursively
212 static pthread_mutex_t printing = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
215 if ( pthread_mutex_lock( &printing ) ) { perror( "FATAL" ); exit(1); }
217 #define PRINTUNLOCK \
218 if ( pthread_mutex_unlock( &printing ) ) { perror( "FATAL" ); exit(1); }
220 #define PRINT( X ) { PRINTLOCK; X; PRINTUNLOCK; }
222 #define VERBOSEOUT(fmt, ...) \
223 if ( verbose >= 1 ) PRINT( fprintf( stderr, fmt, ##__VA_ARGS__ ) )
225 #define VERBOSE2OUT(fmt, ...) \
226 if ( verbose >= 2 ) PRINT( fprintf( stderr, fmt, ##__VA_ARGS__ ) )
228 #define VERBOSE3OUT(fmt, ...) \
229 if ( verbose >= 3 ) PRINT( fprintf( stderr, fmt, ##__VA_ARGS__ ) )
231 // The actual name of this program (argv[0])
232 static unsigned char *progname;
234 // Compute a hashcode for the given SockAddr key
235 static int hashcode_uaddr(
236 __attribute__((unused)) struct _htable *table,unsigned char *key)
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 ) );
250 // Compute a hashcode for the given MAC addr key
251 static int hashcode_mac(struct _htable *table,unsigned char *key) {
254 if ( table->size == 256 ) {
255 for ( ; i < 6; i++ ) {
260 uint16_t *p = (uint16_t *) key;
261 for ( ; i < 3; i++ ) {
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];
273 sprintf( p,"%d.%d.%d.%d", b[0], b[1], b[2], b[3] );
274 } else if ( w == 16 ){
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] );
282 VERBOSE3OUT( "HEX data of %d bytes\n", w );
283 for ( ; i < w && i < 19000; i++, p += 3 ) {
284 sprintf( p, "%02x:", b[i] );
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];
301 sprintf( buffer[i], "%02x:%02x:%02x:%02x:%02x:%02x",
302 mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] );
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];
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 ) );
324 sprintf( out[i], "<tap/stdio>" );
329 // Debugging: string representation of an Allowed record.
330 static char *show_allowed(struct Allowed *a) {
331 static char buffer[20000];
333 sprintf( buffer, "{tap/stdio}" );
335 sprintf( buffer, "%hd (%d) %s %p",
336 a->port, a->bits, inet_nmtoa( a->addr.bytes, a->addr.width ),
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;
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 ) );
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 ) );
363 memcpy( &r->uaddr, a, sizeof( r->uaddr ) );
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 ) );
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 );
378 return 1; // error: out of memory
380 Ignored_ADD( link, x );
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;
389 if ( sscanf( arg,"%x:%x:%x:%x:%x:%x%n",&a,&b,&c,&d,&e,&f,&g ) != 6 ) {
393 if ( (a|b|c|d|e|f) & ~0xff ) {
394 return 1; // some %x is not hex
396 unsigned char mac[6] = { a, b, c, d, e, f };
397 if ( add_ignored( link, mac ) ) {
401 VERBOSEOUT( "Ignoring: %s on channel %s\n",
402 inet_mtoa( mac ), link->source );
407 if ( *(arg++) != ',' ) {
408 return 1; // Not comma separated
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;
419 for ( i = a->width; i < 16; i++ ) {
422 for ( i = a->width - 1; i >= 0; i--, max -= 8 ) {
423 if ( max - 8 < bits ) {
428 if ( i >= 0 && max >= bits ) {
429 a->bytes[ i ] &= ( 0xFF << ( bits - max ) );
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 ];
443 VERBOSE3OUT( "found nothing\n" );
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 ) {
456 struct PSK *old = findLoadedKeyfile( psk->keyfile, loaded, count );
458 memcpy( psk, old, sizeof( struct PSK ) );
464 struct stat filestat;
465 psk->keyfile = strdup( psk->keyfile );
466 int fd = open( (char*) psk->keyfile, O_RDONLY );
469 perror( "open key file" );
472 if ( fstat( fd, &filestat ) ) {
473 perror( "stat of key file" );
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,
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 );
490 while ( ( n = read( fd, p, e ) ) > 0 ) {
496 fprintf( stderr, "Failed loading key %s\n", psk->keyfile );
499 for ( e = 0; (unsigned) e < psk->key_length; e++ ) {
500 psk->seed += psk->key[ e ];
502 if ( psk->seed == 0 ) {
503 fprintf( stderr, "Bad key %s; adds up to 0\n", psk->keyfile );
508 loaded = realloc( loaded, ( count * sizeof( struct PSK ) ) );
510 loaded = malloc( sizeof( struct PSK ) );
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 );
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)
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 );
528 memcpy( &ca->in6, &sa->in6.sin6_addr, 16 );
529 *port = ntohs( sa->in6.sin6_port );
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 );
542 sa->in6.sin6_family = AF_INET6;
543 sa->in6.sin6_port = htons( port );
544 memcpy( &sa->in6.sin6_addr, &ca->in6, 16 );
548 //** IP address parsing utility
549 // Capture an optional port sub phrase [:<port>]
550 static int parse_port(char *port,struct Allowed *into) {
555 if ( sscanf( port, "%d", &p ) != 1 || p < 1 || p > 65535 ) {
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) {
571 if ( sscanf( bits, "%d", &b ) != 1 || b < 0 || b > max ) {
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 );
591 return 1; // excessively large argument
593 strcpy( buffer, arg );
595 char * keyfile = strchr( buffer, '=' );
598 into->psk.keyfile = keyfile;
600 #define B(b) b, b+1, b+2, b+3
601 if ( sscanf( buffer, "%hhu.%hhu.%hhu.%hhu", B(into->addr.bytes) ) == 4 ) {
604 into->addr.width = 4;
605 if ( parse_port( strchr( buffer, ':' ), into ) ) {
606 fprintf( stderr, "bad port\n" );
609 if ( parse_bits( strchr( buffer, '/' ), 32, into ) ) {
610 fprintf( stderr, "bad bits\n" );
616 char * address = buffer;
618 if ( *buffer == '[' ) {
619 // bracketed form, necessary for port
620 char *end = strchr( buffer, ']' );
622 return 1; // bad argument
626 if ( *end == ':' && parse_port( end, into ) ) {
630 into->addr.width = 16;
631 if ( parse_bits( strchr( address, '/' ), 128, into ) ) {
634 if ( inet_pton( AF_INET6, address, into->addr.bytes ) != 1 ) {
635 return 1; // Bad IPv6
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;
648 if ( parse_allowed( spec, into ) ) {
649 fprintf( stderr, "Bad remote spec: %s\n", spec );
654 if ( allowed.table == 0 ) {
656 allowed.table = calloc( 1, sizeof(struct Allowed*) );
661 allowed.table = realloc( allowed.table,
662 allowed.count * sizeof(struct Allowed*) );
663 if ( allowed.table == 0 ) {
664 fprintf( stderr, "OUT OF MEMORY\n" );
668 allowed.table[i] = into;
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 );
681 static int parse_threads_count(char *arg) {
682 if ( ( sscanf( arg, "%u", &threads_count ) != 1 ) || threads_count < 1 ) {
685 VERBOSEOUT( "** Threads count = %d\n", threads_count );
689 static int parse_buffers_count(char *arg) {
690 if ( ( sscanf( arg, "%u", &buffers_count ) != 1 ) || buffers_count < 1 ) {
693 VERBOSEOUT( "** Buffers count = %d\n", buffers_count );
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 );
707 return 1; // excessively large argument
709 memcpy( buffer, arg, n );
710 char *p = buffer + n - 1;
711 for ( ; p > buffer && *p != ':' && *p != '='; p-- ) { }
713 mcast.psk.keyfile = p+1;
715 loadkey( &mcast.psk );
716 for ( ; p > buffer && *p != ':' ; p-- ) { }
719 fprintf( stderr, "Multicast port is required\n" );
720 return 1; // Port number is required
723 if ( inet_pton( AF_INET, buffer, &mcast.group.imr_multiaddr.s_addr )==0 ) {
724 fprintf( stderr, "Multicast address required\n" );
728 long int port = strtol( p, &e, 10 );
729 if ( *e != 0 || port < 1 || port > 65535 ) {
730 fprintf( stderr, "Bad multicast port\n" );
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 ) );
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.
750 udp_source.family = AF_INET6;
755 if ( ! inet_pton( AF_INET, arg, udp_source.address ) ) {
759 // An ipv4 address is given.
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;
767 udp_source.family = AF_INET;
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");
780 if ( setsockopt( mcast.fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
781 (char *) &mcast.group, sizeof( mcast.group ) ) < 0) {
782 perror( "Joining multicast group" );
786 if ( setsockopt( mcast.fd, SOL_SOCKET, SO_REUSEADDR,
787 &reuse, sizeof( int ) ) < 0 ) {
788 perror( "SO_REUSEADDR" );
791 if ( bind( mcast.fd, (struct sockaddr*) &mcast.sock.in,
792 sizeof( struct sockaddr ) ) ) {
793 fprintf( stderr, "Error binding socket!\n");
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 );
802 // Find the applicable channel rule for a given ip:port address
803 static struct Allowed *is_allowed_remote(struct SockAddr *addr) {
805 int width = ( addr->in.sa_family == AF_INET )? 4 : 16;
808 for ( ; (unsigned) i < allowed.count; i++ ) {
809 struct Allowed *a = allowed.table[i];
810 if ( a->addr.width != width ) {
813 set_charaddrport( &ca, &port, addr );
814 if ( a->port != 0 && a->port != port ) {
817 clearbitsafter( &ca, a->bits );
818 if ( memcmp( &ca, &a->addr, sizeof( struct CharAddr ) ) == 0 ) {
822 return 0; // Disallowed
825 // Simple PSK encryption:
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
834 static void encrypt(unsigned char *buf,unsigned int n,struct PSK *psk) {
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 ];
845 pthread_mutex_lock( &crypting );
846 srand( psk->seed + magic );
847 for ( k = 0; k < n; k++ ) {
853 pthread_mutex_unlock( &crypting );
856 // Corresponding decryption procedure .
857 static void decrypt(unsigned char *buf,unsigned int n,struct PSK *psk) {
858 unsigned int randoms[ BUFSIZE ];
862 unsigned int magic = 0;
863 for ( k = 0; k < n; k++ ) {
866 pthread_mutex_lock( &crypting );
867 srand( psk->seed + magic );
868 for ( k = 0; k < n; k++ ) {
869 randoms[k] = rand() % n;
871 pthread_mutex_unlock( &crypting );
872 for ( k = n; k > 0; ) {
878 for ( k = 0, r = 0, magic = 0; k < n; k++ ) {
879 r = ( r + magic + k ) % psk->key_length;
881 buf[k] ^= psk->key[r];
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) {
889 if ( ( w = write( fd, buf, n ) ) < 0){
890 perror( "Writing data" );
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 );
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 );
905 n = size + 14; // Clip of any tail
909 uint16_t plength = htons( n );
910 if ( dowrite( 1, (unsigned char *) &plength,
911 sizeof( plength ) ) < 0 ) {
914 return dowrite( 1, buf, n );
916 return dowrite( tap_fd, buf, n );
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) {
922 unsigned char output[ BUFSIZE ];
924 VERBOSE2OUT( "SEND %d bytes to %s\n", n, inet_stoa( &r->uaddr ) );
926 VERBOSE2OUT( "SEND %d bytes %s -> %s to %s\n", n,
927 inet_mtoa( buf+6 ), inet_mtoa( buf ),
928 inet_stoa( &r->uaddr ) );
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
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 ) {
941 fprintf( stderr, "Cannot write to tap/stdio: exiting!\n" );
946 // Fall through for multicast
947 if ( mcast.psk.keyfile ) {
948 encrypt( output, n, &mcast.psk );
950 } else if ( r->spec->psk.keyfile ) {
951 encrypt( output, n, &r->spec->psk );
953 struct sockaddr *sock = &r->uaddr.in;
955 if ( sock->sa_family == AF_INET6 ) {
956 // Note that the size of +struct sockaddr_in6+ is actually
957 // larger than the size of +struct sockaddr+ (due to the
958 // addition of the +sin6_flowinfo+ field). It results in the
959 // following cuteness for passing arguments to +sendto+.
960 size = sizeof( struct sockaddr_in6 );
961 VERBOSE2OUT( "IPv6 UDP %d %s\n",
962 udp_fd, inet_stoa( (struct SockAddr*) sock ) );
964 size = sizeof( struct sockaddr_in );
965 VERBOSE2OUT( "IPv4 UDP %d %s\n",
966 udp_fd, inet_stoa( (struct SockAddr*) sock ) );
968 VERBOSE2OUT( "SEND %d bytes to %s [%s -> %s]\n",
969 n, inet_stoa( (struct SockAddr*) sock ),
970 ( n < 12 )? "" : inet_mtoa( buf+6 ),
971 ( n < 12 )? "" : inet_mtoa( buf )
973 // IS sendto thread safe??
974 if ( sendto( udp_fd, output, n, 0, sock, size ) < n ) {
975 perror( "Writing socket" );
976 // Invalidate remote temporarily instead? But if it's an
977 // "uplink" it should be retried eventually...
978 // For now: just ignore the error.
983 // Delete a Remote and all its interfaces
984 static void delete_remote(struct Remote *r) {
985 VERBOSE2OUT( "DELETE Remote and all its interfaces %s\n",
986 inet_stoa( &r->uaddr ) );
990 for ( ; i < remotes.by_mac.size; i++ ) {
991 unsigned char *tmp = remotes.by_mac.data[i];
992 if ( tmp == 0 || tmp == (unsigned char *)1 ) {
995 x = (struct Interface *) tmp;
996 if ( x->remote == r ) {
1006 // Unmap an ipv4-mapped ipv6 address
1007 static void unmap_if_mapped(struct SockAddr *s) {
1008 if ( s->in.sa_family != AF_INET6 ||
1009 memcmp( "\000\000\000\000\000\000\000\000\000\000\377\377",
1010 &s->in6.sin6_addr, 12 ) ) {
1013 VERBOSE2OUT( "unmap %s\n",
1014 inet_nmtoa( (unsigned char*) s, sizeof( struct SockAddr ) ) );
1015 s->in.sa_family = AF_INET;
1016 memcpy( &s->in4.sin_addr, s->in6.sin6_addr.s6_addr + 12, 4 );
1017 memset( s->in6.sin6_addr.s6_addr + 4, 0, 12 );
1018 VERBOSE2OUT( "becomes %s\n",
1019 inet_nmtoa( (unsigned char*) s, sizeof( struct SockAddr ) ) );
1022 // Route the packet from the given src
1023 static struct Interface *input_check(
1024 unsigned char *buf,ssize_t len,struct SockAddr *src )
1026 VERBOSE2OUT( "RECV %ld bytes from %s\n", len, inet_stoa( src ) );
1027 struct Remote *r = 0;
1028 struct timeval now = { 0 };
1029 if ( gettimeofday( &now, 0 ) ) {
1030 perror( "RECV time" );
1031 now.tv_sec = time( 0 );
1033 Remote_FIND( src, r );
1035 struct Allowed *a = is_allowed_remote( src );
1037 VERBOSEOUT( "Ignoring %s\n", inet_stoa( src ) );
1038 return 0; // Disallowed
1040 VERBOSEOUT( "New remote %s by %s\n", inet_stoa( src ), a->source );
1041 r = add_remote( src, a );
1042 //r->rec_when = now; // Set activity stamp of new remote
1045 // Ignore short data, but maintain channel
1046 r->rec_when = now; // Update activity stamp touched remote
1048 VERBOSEOUT( "Ignoring %ld bytes from %s\n",
1049 len, inet_stoa( src ) );
1053 // Now decrypt the data as needed
1055 if ( r->spec->psk.seed ) {
1056 decrypt( buf, len, &r->spec->psk );
1058 } else if ( r->uaddr.in.sa_family == 0 && mcast.psk.keyfile ) {
1059 decrypt( buf, len, &mcast.psk );
1061 VERBOSE2OUT( "RECV %s -> %s from %s\n",
1062 inet_mtoa( buf+6 ), inet_mtoa( buf ),
1063 inet_stoa( &r->uaddr ) );
1064 // Note: the payload is now decrypted, and known to be from +r+
1065 struct Interface *x = 0;
1066 // Packets concerning an ignored interface should be ignored.
1067 if ( r->spec && r->spec->ignored_mac.data ) {
1068 Ignored_FIND( r->spec, buf+6, x );
1070 VERBOSE2OUT( "Dropped MAC %s from %s on %s\n",
1071 inet_mtoa( buf+6 ), inet_stoa( &r->uaddr ),
1075 Ignored_FIND( r->spec, buf, x );
1077 VERBOSE2OUT( "Dropped MAC %s to %s on %s\n",
1078 inet_mtoa( buf ), inet_stoa( &r->uaddr ),
1083 Interface_FIND( buf+6, x );
1085 // Totally new MAC. Should bind it to the remote
1086 VERBOSEOUT( "New MAC %s from %s\n",
1087 inet_mtoa( buf+6 ), inet_stoa( src ) );
1088 x = add_interface( buf+6, r );
1089 r->rec_when = now; // Update activity stamp for remote
1093 // Seen that MAC already
1094 if ( x->remote == r ) {
1095 VERBOSE2OUT( "RECV %s from %s again\n",
1096 inet_mtoa( buf+6 ), inet_stoa( &x->remote->uaddr ) );
1097 r->rec_when = now; // Update activity stamp
1098 x->rec_when = now; // Update activity stamp
1101 // MAC clash from two different connections
1103 // x->remote = previous
1104 VERBOSE2OUT( "RECV %s from %s previously from %s\n",
1106 inet_stoa( &r->uaddr ),
1107 inet_stoa( &x->remote->uaddr ) );
1109 // The packet source MAC has arrived on other than its
1110 // previous channel. It thus gets dropped if tap/stdin is the
1111 // primary channel, or the time since the last packet for that
1112 // interface is less than RECENT_MICROS, with different limits
1113 // for broadcast and unicast.
1114 int64_t dmac = DIFF_MICROS( &now, &x->rec_when);
1115 if ( x->remote->spec == 0 || RECENT_MICROS( *buf & 1, dmac ) ) {
1116 if ( verbose >= 2 ) {
1119 "Dropped. MAC %s (%ld) from %s, should be %s\n",
1120 inet_mtoa( buf+6 ), dmac,
1121 inet_stoa( src ), inet_stoa( &x->remote->uaddr ) );
1125 // Check if previous package on the interface was recent
1126 } else if ( r->uaddr.in.sa_family ) {
1127 // Multicast incoming clashing with tap/stdio
1128 VERBOSE3OUT( "Dropped multicast loopback\n" );
1132 // New remote takes over the MAC
1133 VERBOSEOUT( "MAC %s from %s cancels previous %s\n",
1134 inet_mtoa( buf+6 ), inet_stoa( src ),
1135 inet_stoa( &x->remote->uaddr ) );
1136 x->remote = r; // Change remote for MAC
1137 // Note that this may leave the old x->remote without any interface
1138 r->rec_when = now; // Update activity stamp
1139 x->rec_when = now; // Update activity stamp
1143 // Check packet and deliver out
1144 static void route_packet(unsigned char *buf,int len,struct SockAddr *src) {
1145 struct Interface *x = input_check( buf, len, src );
1147 return; // not a nice packet
1149 if ( ( *buf & 1 ) == 0 ) {
1151 struct Interface *y = 0; // reuse for destination interface
1152 Interface_FIND( buf, y );
1154 VERBOSE2OUT( "RECV %s -> %s from %s without channel and dropped\n",
1155 inet_mtoa( buf+6 ), inet_mtoa( buf ),
1156 inet_stoa( &x->remote->uaddr ) );
1159 if ( x->remote == y->remote ) {
1160 VERBOSEOUT( "RECV loop for %s -> %s from %s to %s\n",
1161 inet_mtoa( buf+6 ), inet_mtoa( buf ),
1162 inet_stoa( &x->remote->uaddr ),
1163 inet_stoa( &y->remote->uaddr ) );
1164 Interface_DEL( y ); // Need to see this interface again
1167 VERBOSE2OUT( "RECV route %s -> %s to %s\n",
1168 inet_mtoa( buf+6 ), inet_mtoa( buf ),
1169 inet_stoa( &y->remote->uaddr ) );
1170 write_remote( buf, len, y->remote );
1173 // broadcast. +x+ is source interface
1174 // x->rec_when is not updated
1175 struct timeval now = { 0 };
1176 if ( gettimeofday( &now, 0 ) ) {
1177 perror( "RECV time" );
1178 now.tv_sec = time( 0 );
1180 VERBOSE2OUT( "BC %s -> %s from %s\n",
1181 inet_mtoa( buf+6 ), inet_mtoa( buf ),
1182 inet_stoa( &x->remote->uaddr ) );
1186 for ( ; i < remotes.by_addr.size; i++ ) {
1187 unsigned char *tmp = remotes.by_addr.data[i];
1188 if ( tmp == 0 || tmp == (unsigned char *)1 ) {
1191 r = (struct Remote *) tmp;
1192 VERBOSE3OUT( "BC check %s\n", inet_stoa( &r->uaddr ) );
1193 if ( r == x->remote ) {
1194 VERBOSE3OUT( "BC r == x->remote\n" );
1197 if ( r->spec && ! is_uplink( r->spec ) &&
1198 DIFF_MICROS( &now, &r->rec_when ) > VERYOLD_MICROS ) {
1199 // remove old downlink connection
1200 VERBOSEOUT( "Old remote discarded %s (%ld)\n",
1201 inet_stoa( &r->uaddr ),
1202 TIME_MICROS( &r->rec_when ) );
1203 // Removing a downlink might have threading implications
1207 // Send packet to the remote
1208 // Only no-clash or to the tap/stdin
1209 write_remote( buf, len, r );
1214 // The packet handling queues
1221 // The threadcontrol program for handling packets.
1222 static void *packet_handler(void *data) {
1225 PacketItem *todo = (PacketItem *) Queue_getItem( &todolist.full );
1226 if ( todo->fd == mcast.fd ) {
1227 // Patch multicast address as source for multicast packet
1228 route_packet( todo->buffer, todo->len, &mcast.sock );
1231 unmap_if_mapped( &todo->src );
1233 route_packet( todo->buffer, todo->len, &todo->src );
1235 Queue_addItem( &todolist.free, (QueueItem*) todo );
1240 void todolist_initialize(int nbuf,int nthr) {
1241 if ( pthread_mutex_init( &todolist.full.mutex, 0 ) ||
1242 sem_init( &todolist.full.count, 0, 0 ) ) {
1246 if ( pthread_mutex_init( &todolist.free.mutex, 0 ) ||
1247 sem_init( &todolist.free.count, 0, 0 ) ) {
1251 if ( sem_init( &todolist.reading, 0, 1 ) ) {
1255 Queue_initialize( &todolist.free, nbuf, sizeof( PacketItem ) );
1256 for ( ; nthr > 0; nthr-- ) {
1257 pthread_t thread; // Temporary thread id
1258 pthread_create( &thread, 0, packet_handler, 0 );
1262 static ssize_t recvpacket(int fd,PacketItem *p) {
1263 int flags = udp6? IPV6_PKTINFO : IP_PKTINFO;
1265 udp6? sizeof( p->src.in6 ) : sizeof( p->src.in4 );
1266 struct iovec buffer = {
1267 .iov_base = p->buffer,
1271 struct msghdr msg = {
1272 .msg_name = &p->src.in,
1273 .msg_namelen = addrlen,
1276 .msg_control = data,
1277 .msg_controllen = sizeof( data ),
1278 .msg_flags = flags // Return value
1280 p->len = recvmsg( fd, &msg, flags );
1281 struct cmsghdr *cmsg = CMSG_FIRSTHDR( &msg );
1282 VERBOSE3OUT( "anc %p %ld\n", cmsg, p->len );
1283 for ( ; cmsg; cmsg = CMSG_NXTHDR( &msg, cmsg ) ) {
1284 VERBOSE3OUT( "anc type = %d\n", cmsg->cmsg_type );
1286 cmsg = CMSG_FIRSTHDR( &msg );
1290 struct in_pktinfo* pinf = (struct in_pktinfo*) CMSG_DATA( cmsg );
1291 p->dst.in4.sin_family = AF_INET;
1292 p->dst.in4.sin_addr = pinf->ipi_addr;
1293 VERBOSE3OUT( "DEST= %d %s\n",
1294 pinf->ipi_ifindex, inet_stoa( &p->dst ) );
1302 // Read a full UDP packet into the given buffer, associate with a
1303 // connection, or create a new connection, the decrypt the as
1304 // specified, and capture the sender MAC address. The connection table
1305 // is updated for the new MAC address, However, if there is then a MAC
1306 // address clash in the connection table, then the associated remote
1307 // is removed, and the packet is dropped.
1308 static void *doreadUDP(void *data) {
1309 int fd = ((ReaderData *) data)->fd;
1311 PacketItem *todo = (PacketItem *) Queue_getItem( &todolist.free );
1314 udp6? sizeof( todo->src.in6 ) : sizeof( todo->src.in4 );
1316 memset( &todo->src, 0, sizeof( todo->src ) );
1319 todo->len = recvfrom(
1320 fd, todo->buffer, BUFSIZE, 0, &todo->src.in, &addrlen );
1322 VERBOSE3OUT( "Reading packet\n" );
1323 ssize_t len = recvpacket( fd, todo );
1325 perror( "Receiving UDP" );
1330 memcmp( todo->buffer, "STOPSTOPSTOPSTOP", 16 ) == 0 ) {
1334 Queue_addItem( &todolist.full, (QueueItem*) todo );
1339 // Read up to n bytes from the given file descriptor into the buffer
1340 static int doread(int fd, unsigned char *buf, int n) {
1342 if ( ( len = read( fd, buf, n ) ) < 0 ) {
1343 perror( "Reading stdin" );
1349 // Read n bytes from the given file descriptor into the buffer.
1350 // If partial is allowed, then return amount read, otherwise keep
1351 // reading until full.
1352 static int read_into(int fd, unsigned char *buf, int n,int partial) {
1355 if ( (r = doread( fd, buf, x ) ) == 0 ) {
1367 // Go through all uplinks and issue a "heart beat"
1368 static void heartbeat(int fd) {
1369 static unsigned char data[10];
1370 VERBOSE3OUT( "heartbeat fd=%d\n", fd );
1374 if ( gettimeofday( &now, 0 ) ) {
1375 perror( "HEARTBEAT time" );
1376 now.tv_sec = time( 0 );
1380 for ( ; i < remotes.by_addr.size; i++ ) {
1381 unsigned char *tmp = remotes.by_addr.data[i];
1382 if ( tmp == 0 || tmp == (unsigned char *)1 ) {
1385 r = (struct Remote *) tmp;
1386 VERBOSE3OUT( "heartbeat check %s\n", inet_stoa( &r->uaddr ) );
1387 if ( r->spec && is_uplink( r->spec ) ) {
1388 if ( DIFF_MICROS( &now, &r->rec_when ) > HEARTBEAT_MICROS ) {
1389 VERBOSE3OUT( "heartbeat %s\n", inet_stoa( &r->uaddr ) );
1390 write_remote( data, 0, r );
1397 // Tell how to use this program and exit with failure.
1398 static void usage(void) {
1399 fprintf( stderr, "Packet tunneling over UDP, multiple channels, " );
1400 fprintf( stderr, "version 1.5.3\n" );
1401 fprintf( stderr, "Usage: " );
1402 fprintf( stderr, "%s [options] port [remote]+ \n", progname );
1403 fprintf( stderr, "** options must be given or omitted in order!!\n" );
1404 fprintf( stderr, " -v = verbose log, -vv or -vvv for more logs\n" );
1405 fprintf( stderr, " -tpg = UDP transport quirk: avoid bad sizes\n" );
1406 fprintf( stderr, " -4 = use an ipv4 UDP socket\n" );
1407 fprintf( stderr, " -B n = use n buffers (2*threads) by default\n");
1408 fprintf( stderr, " -T n = use n delivery threads (5 bu default)\n" );
1409 fprintf( stderr, " -m mcast = allow remotes on multicast address\n" );
1410 fprintf( stderr, " -t tap = use the nominated tap (or - for stdio)\n" );
1411 fprintf( stderr, " -S source = use given source address for UDP\n" );
1415 // Open the given tap
1416 static int tun_alloc(char *dev, int flags) {
1419 if ( ( fd = open( "/dev/net/tun", O_RDWR ) ) < 0 ) {
1420 perror( "Opening /dev/net/tun" );
1423 memset( &ifr, 0, sizeof( ifr ) );
1424 ifr.ifr_flags = flags;
1426 strcpy( ifr.ifr_name, dev );
1428 if ( ( err = ioctl( fd, TUNSETIFF, (void *) &ifr ) ) < 0 ) {
1429 perror( "ioctl(TUNSETIFF)" );
1433 strcpy( dev, ifr.ifr_name );
1437 // Handle packet received on the tap/stdio channel
1438 static void initialize_tap() {
1439 // Ensure there is a Remote for this
1440 static struct Remote *tap_remote = 0;
1441 if ( tap_remote == 0 ) {
1443 if ( tap_remote == 0 ) {
1444 tap_remote = add_remote( 0, 0 );
1450 // Thread to handle tap/stdio input
1451 static void *doreadTap(void *data) {
1452 int fd = ((ReaderData*) data)->fd;
1453 unsigned int end = 0; // Packet size
1454 unsigned int cur = 0; // Amount read so far
1456 PacketItem *todo = (PacketItem*) Queue_getItem( &todolist.free );
1460 int n = read_into( 0, (unsigned char *) &plength,
1461 sizeof( plength ), 0 );
1463 // Tap/stdio closed => exit silently
1466 end = ntohs( plength );
1468 while ( ( e = ( end - cur ) ) != 0 ) {
1469 unsigned char *p = todo->buffer + cur;
1470 if ( end > BUFSIZE ) {
1471 // Oversize packets should be read and discarded
1472 if ( e > BUFSIZE ) {
1477 cur += read_into( 0, p, e, 1 );
1480 end = doread( fd, todo->buffer, BUFSIZE );
1483 VERBOSE3OUT( "TAP/stdio input %d bytes\n", end );
1484 if ( end <= BUFSIZE ) {
1487 Queue_addItem( &todolist.full, (QueueItem*) todo );
1488 todo = (PacketItem*) Queue_getItem( &todolist.free );
1495 // Application main function
1496 // Parentheses mark optional
1497 // $* = (-v) (-4) (-B n) (-T n) (-m mcast) (-t port) (ip:)port (remote)+
1498 // remote = ipv4(/maskwidth)(:port)(=key)
1499 // remote = ipv6(/maskwidth)(=key)
1500 // remote = [ipv6(/maskwidth)](:port)(=key)
1501 // ip = ipv4 | [ipv6]
1502 int main(int argc, char *argv[]) {
1503 pthread_t thread; // Temporary thread id
1505 progname = (unsigned char *) argv[0];
1506 ///// Parse command line arguments
1508 #define ENSUREARGS(n) if ( argc < i + n ) usage()
1510 // First: optional -v, -vv or -vvv
1511 if ( strncmp( "-v", argv[i], 2 ) == 0 ) {
1512 if ( strncmp( "-v", argv[i], 3 ) == 0 ) {
1514 } else if ( strncmp( "-vv", argv[i], 4 ) == 0 ) {
1516 } else if ( strncmp( "-vvv", argv[i], 5 ) == 0 ) {
1524 if ( strncmp( "-tpg", argv[i], 4 ) == 0 ) {
1529 // then: optional -4
1530 if ( strncmp( "-4", argv[i], 2 ) == 0 ) {
1535 // then: optional -B buffers
1536 if ( strncmp( "-B", argv[i], 2 ) == 0 ) {
1538 if ( parse_buffers_count( argv[i+1] ) ) {
1544 // then: optional -T threads
1545 if ( strncmp( "-T", argv[i], 2 ) == 0 ) {
1547 if ( parse_threads_count( argv[i+1] ) ) {
1553 // then: optional -m mcast
1554 if ( strncmp( "-m", argv[i], 2 ) == 0 ) {
1556 if ( parse_mcast( argv[i+1] ) ) {
1562 // then: optional -t tap
1563 if ( strncmp( "-t", argv[i], 2 ) == 0 ) {
1569 // Then optional source address for UDP
1570 if ( strncmp( "-S", argv[i], 2 ) == 0 ) {
1572 if ( parse_udp_source( argv[i+1] ) ) {
1578 // then: required port
1579 if ( sscanf( argv[i++], "%d", &port ) != 1 ) {
1580 fprintf( stderr, "Bad local port: %s\n", argv[i-1] );
1583 // then: any number of allowed remotes
1584 struct Allowed *last_allowed = 0;
1585 for ( ; i < argc; i++ ) {
1586 if ( last_allowed ) {
1587 // optionally adding ignored interfaces
1588 if ( strncmp( "-i", argv[i], 2 ) == 0 ) {
1590 if ( parse_ignored_interfaces( argv[i+1], last_allowed ) ) {
1597 if ( ( last_allowed = add_allowed( argv[i] ) ) == 0 ) {
1598 fprintf( stderr, "Cannot load remote %s. Exiting.\n", argv[i] );
1602 // end of command line parsing
1604 // Initialize buffers and threads
1605 if ( threads_count == 0 ) {
1608 if ( buffers_count < threads_count ) {
1609 buffers_count = 2 * threads_count;
1611 todolist_initialize( buffers_count, threads_count );
1613 // Set up the tap/stdio channel
1615 // set up the nominated tap
1616 if ( strcmp( "-", tap ) ) { // Unless "-"
1617 tap_fd = tun_alloc( tap, IFF_TAP | IFF_NO_PI );
1619 fprintf( stderr, "Error connecting to interface %s!\n", tap);
1622 VERBOSEOUT( "Using tap %s at %d\n", tap, tap_fd );
1624 // pretend a zero packet on the tap, for initializing.
1627 // set up for stdin/stdout local traffix
1628 setbuf( stdout, NULL ); // No buffering on stdout.
1629 tap_fd = 0; // actually stdin
1635 // Set up the multicast UDP channel (all interfaces)
1636 if ( mcast.group.imr_multiaddr.s_addr ) {
1638 unsigned char *x = (unsigned char *) &mcast.group.imr_multiaddr.s_addr;
1639 VERBOSEOUT( "Using multicast %s:%d at %d\n",
1640 inet_nmtoa( x, 4 ), ntohs( mcast.sock.in4.sin_port ),
1643 // Set up the unicast UPD channel (all interfaces)
1645 // set up ipv4 socket
1646 if ( ( udp_fd = socket( AF_INET, SOCK_DGRAM, 0 ) ) == 0 ) {
1647 perror( "creating socket");
1650 struct sockaddr_in udp_addr = {
1651 .sin_family = AF_INET,
1652 .sin_port = htons( port ),
1654 if ( udp_source.family == 0 ) {
1655 udp_addr.sin_addr.s_addr = htonl( INADDR_ANY );
1657 udp_addr.sin_addr.s_addr = *((uint32_t*) udp_source.address);
1659 if ( bind( udp_fd, (struct sockaddr*) &udp_addr, sizeof(udp_addr))) {
1660 fprintf( stderr, "Error binding socket!\n");
1663 VERBOSEOUT( "Using ipv4 UDP at %d\n", udp_fd );
1665 if ( setsockopt( udp_fd, IPPROTO_IP, IP_PKTINFO, &opt, sizeof(opt)) ) {
1666 fprintf( stderr, "Error configuring socket!\n");
1670 // set up ipv6 socket
1671 if ( ( udp_fd = socket( AF_INET6, SOCK_DGRAM, 0 ) ) == 0 ) {
1672 perror( "creating socket");
1675 struct sockaddr_in6 udp6_addr = {
1676 .sin6_family = AF_INET6,
1677 .sin6_port = htons( port ),
1679 memcpy( udp6_addr.sin6_addr.s6_addr, udp_source.address, 16 );
1680 if ( bind( udp_fd, (struct sockaddr*) &udp6_addr, sizeof(udp6_addr))) {
1681 fprintf( stderr, "Error binding socket!\n");
1684 VERBOSEOUT( "Using ipv6 UDP at %d\n", udp_fd );
1686 // If not using stdio for local traffic, then stdin and stdout are
1687 // closed here, so as to avoid that any other traffic channel gets
1688 // 0 or 1 as its file descriptor. Note: stderr (2) is left open.
1693 VERBOSE2OUT( "Socket loop tap=%d mcast=%d udp=%d\n",
1694 tap_fd, mcast.fd, udp_fd );
1697 ReaderData udp_reader = { .fd = udp_fd };
1698 pthread_create( &thread, 0, doreadUDP, &udp_reader );
1700 if ( mcast.group.imr_multiaddr.s_addr ) {
1701 ReaderData mcast_reader = { .fd = mcast.fd };
1702 pthread_create( &thread, 0, doreadUDP, &mcast_reader );
1705 if ( tap_fd || stdio ) {
1706 ReaderData tap_reader = { .fd = tap_fd };
1707 pthread_create( &thread, 0, doreadTap, &tap_reader );
1710 // Start heartbeating to uplinks
1713 heartbeat( udp_fd );