Compare commits

...

47 Commits

Author SHA1 Message Date
angt
a78089ba10 Version 0.0.5 2015-11-23 12:13:42 +01:00
angt
128aaae368 Add daemon option (only one fork) 2015-11-23 12:12:28 +01:00
angt
230c9fa26a Little fix and cleanup 2015-11-21 19:09:21 +01:00
angt
9834498d94 Avoid str_cmp() in sk_set() 2015-11-20 10:17:26 +01:00
angt
9454b5c9e1 Code cleanup 2015-11-19 23:38:13 +01:00
angt
ca3ed9ff1a Group ip packets for encryption 2015-11-19 19:07:42 +01:00
angt
836ffaad37 Increment listener backlog 2015-11-19 09:51:29 +01:00
angt
4c02e38954 Defer accept on listener 2015-11-19 09:51:29 +01:00
angt
540d0e2dff Flag is just an empty option 2015-11-19 09:51:29 +01:00
angt
0c1e3a5f09 Version 0.0.4 2015-11-18 10:39:15 +01:00
angt
4337251218 Code cleanup 2015-11-18 10:17:50 +01:00
angt
baca343fdf Simplify setsockopt() code 2015-11-18 09:24:30 +01:00
angt
c20a2a5a13 Code cleanup 2015-11-17 23:58:19 +01:00
angt
7fc368cf3c Make keepalive an option (and not a flag) 2015-11-17 23:48:55 +01:00
angt
25b62bf4c6 Simplify and generalize option_usage() 2015-11-17 23:36:03 +01:00
angt
47432ecafa Add gt_print() 2015-11-17 23:29:56 +01:00
angt
e4f2a92c5b Add ka-count, ka-idle and ka-interval options to setup keepalive 2015-11-17 22:14:35 +01:00
angt
89d2edb61b Try again to open() on EINTR 2015-11-17 21:39:56 +01:00
angt
310e499234 Version 0.0.3 2015-11-17 21:22:24 +01:00
angt
9ff87109f9 Add buffer-size option 2015-11-17 21:19:16 +01:00
angt
bfcf38f380 Try to be more robust on restart but accept some lost for now 2015-11-17 21:04:26 +01:00
angt
286f54aed4 Try to close nicely, waiting for a real proto 2015-11-17 13:10:09 +01:00
angt
6ef8ca45d7 Merge pull request #9 from jedisct1/pointer-arith
Avoid pointer arithmetic on void *
2015-11-17 07:58:19 +01:00
Frank Denis
85ddb8a8d6 Avoid pointer arithmetic on void * 2015-11-17 07:38:11 +01:00
angt
a261f1a8b1 Code cleanup 2015-11-17 07:15:59 +01:00
angt
53a55e83c4 Merge pull request #8 from jedisct1/scalarmult-check
Check crypto_scalarmult() return code
2015-11-17 06:40:13 +01:00
Frank Denis
20bdaa22e8 Check crypto_scalarmult() return code 2015-11-17 01:31:52 +01:00
angt
246f1bd7c0 Add a very simple client and server authentication 2015-11-16 16:35:43 +01:00
angt
6095cc021a Include missing uio.h in tun.c 2015-11-16 16:08:44 +01:00
angt
2ad21e9375 Include missing ip-static.h in tun.c 2015-11-16 16:05:05 +01:00
angt
21ae1f34c3 Add common.c 2015-11-16 16:00:33 +01:00
angt
a8ebefbef3 Add tun.[ch] 2015-11-16 15:44:16 +01:00
angt
14c0c2edb1 Add ip-static.h 2015-11-16 12:53:47 +01:00
angt
b8148600f2 Add keepalive option 2015-11-16 11:44:28 +01:00
angt
164c32c23c Code cleanup 2015-11-16 11:42:53 +01:00
angt
a5e415736d Merge pull request #7 from jedisct1/keepalive
Set `SO_KEEPALIVE` on the socket
2015-11-16 10:50:50 +01:00
angt
0359c21643 Merge pull request #6 from jedisct1/dd
Use /dev/urandom
2015-11-16 10:50:39 +01:00
angt
725a8e2fd0 Merge pull request #5 from jedisct1/bsd-osx
Complete support for OSX & BSD
2015-11-16 10:50:22 +01:00
Frank Denis
dae5d4a800 Set SO_KEEPALIVE on the socket so that we don't hang forever 2015-11-16 09:56:11 +01:00
Frank Denis
704e663d6a Use /dev/urandom
http://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/
https://speakerdeck.com/filosottile/the-plain-simple-reality-of-entropy

Also remove the iflag=fullblock GNUism that doesn't exist on BSD and OSX
2015-11-16 02:06:21 +01:00
Frank Denis
c63885a748 Add support for the native OSX utun interface 2015-11-16 01:52:33 +01:00
Frank Denis
8530e4c378 On OSX and BSD, packets sent to the tun interface have to be prefixed
by the protocol family
2015-11-16 00:43:16 +01:00
angt
4944e76f97 Fix last commit 2015-11-15 18:38:43 +01:00
angt
5865e61fd2 Use select() in the main loop (macos is full of sh!t) 2015-11-15 18:23:29 +01:00
angt
8855ce75fc Code cleanup 2015-11-15 17:42:18 +01:00
angt
3e1809a608 Version 0.0.2 2015-11-15 16:27:03 +01:00
angt
04370f0aa0 Code cleanup 2015-11-15 10:51:28 +01:00
11 changed files with 696 additions and 319 deletions

View File

@@ -1,4 +1,13 @@
bin_PROGRAMS = glorytun bin_PROGRAMS = glorytun
glorytun_SOURCES = src/common.h src/common-static.h src/main.c src/option.c src/option.h
glorytun_CFLAGS = $(libsodium_CFLAGS) glorytun_CFLAGS = $(libsodium_CFLAGS)
glorytun_LDADD = $(libsodium_LIBS) glorytun_LDADD = $(libsodium_LIBS)
glorytun_SOURCES = \
src/common.h \
src/common-static.h \
src/common.c \
src/ip-static.h \
src/main.c \
src/option.c \
src/option.h \
src/tun.c \
src/tun.h

View File

@@ -16,5 +16,5 @@ To build and install the latest version:
To create and use a new secret key: To create and use a new secret key:
$ dd if=/dev/random iflag=fullblock of=glorytun.key bs=32 count=1 $ dd if=/dev/urandom of=glorytun.key bs=32 count=1
# glorytun keyfile glorytun.key [...] # glorytun keyfile glorytun.key [...]

View File

@@ -1,5 +1,5 @@
AC_PREREQ([2.65]) AC_PREREQ([2.65])
AC_INIT([glorytun], [0.0.1], [https://github.com/angt/glorytun/issues], AC_INIT([glorytun], [0.0.5], [https://github.com/angt/glorytun/issues],
[glorytun], [https://github.com/angt/glorytun]) [glorytun], [https://github.com/angt/glorytun])
AC_CONFIG_SRCDIR([src/common.h]) AC_CONFIG_SRCDIR([src/common.h])
AC_CONFIG_AUX_DIR([build-aux]) AC_CONFIG_AUX_DIR([build-aux])

40
src/common.c Normal file
View File

@@ -0,0 +1,40 @@
#include "common.h"
#include <stdio.h>
#include <stdarg.h>
int gt_print (const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
int ret = vfprintf(stdout, fmt, ap);
va_end(ap);
if (ret<0)
return 0;
return ret;
}
void gt_log (const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
}
void gt_fatal (const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
exit(EXIT_FAILURE);
}
void gt_na (const char *name)
{
gt_log("%s is not available on your platform!\n", name);
}

View File

@@ -14,6 +14,8 @@
#define PALIGN(x) ((void *)ALIGN((size_t)(x))) #define PALIGN(x) ((void *)ALIGN((size_t)(x)))
#define PALIGN_DOWN(x) ((void *)ALIGN_DOWN((size_t)(x))) #define PALIGN_DOWN(x) ((void *)ALIGN_DOWN((size_t)(x)))
#define _printf_(A,B) __attribute__((format(printf,A,B)))
#define _noreturn_ __attribute__((noreturn))
#define _unused_ __attribute__((unused)) #define _unused_ __attribute__((unused))
typedef struct buffer buffer_t; typedef struct buffer buffer_t;
@@ -24,3 +26,8 @@ struct buffer {
uint8_t *write; uint8_t *write;
uint8_t *end; uint8_t *end;
}; };
int gt_print (const char *, ...) _printf_(1,2);
void gt_log (const char *, ...) _printf_(1,2);
void gt_fatal (const char *, ...) _printf_(1,2) _noreturn_;
void gt_na (const char *);

30
src/ip-static.h Normal file
View File

@@ -0,0 +1,30 @@
#pragma once
#include <stdint.h>
static inline int ip_get_version (const uint8_t *data, size_t size)
{
if (size<20) // XXX
return -1; // XXX
return data[0]>>4;
}
static inline void ip_set_size (uint8_t *data, size_t size)
{
data[2] = 0xFF&(size>>8);
data[3] = 0xFF&(size);
}
static inline ssize_t ip_get_size (const uint8_t *data, size_t size)
{
switch (ip_get_version(data, size)) {
case 4:
return (data[2]<<8)|data[3];
case -1:
return -1;
}
return 0;
}

View File

@@ -1,27 +1,23 @@
#include "common-static.h"
#include "option.h"
#include <inttypes.h> #include <inttypes.h>
#include <limits.h>
#include <stdio.h> #include <stdio.h>
#include <stdint.h>
#include <signal.h> #include <signal.h>
#include <poll.h> #include <poll.h>
#include <sys/time.h> #include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/fcntl.h> #include <sys/fcntl.h>
#include <sys/socket.h> #include <sys/socket.h>
#include <netinet/tcp.h> #include <netinet/tcp.h>
#include <arpa/inet.h> #include <arpa/inet.h>
#include <netdb.h> #include <netdb.h>
#ifdef __linux__
# include <linux/if.h>
# include <linux/if_tun.h>
#endif
#include <sodium.h> #include <sodium.h>
#include "common-static.h"
#include "ip-static.h"
#include "option.h"
#include "tun.h"
#ifndef O_CLOEXEC #ifndef O_CLOEXEC
#define O_CLOEXEC 0 #define O_CLOEXEC 0
#endif #endif
@@ -29,28 +25,21 @@
#define GT_BUFFER_SIZE (4*1024*1024) #define GT_BUFFER_SIZE (4*1024*1024)
#define GT_TIMEOUT (1000) #define GT_TIMEOUT (1000)
struct netio { struct fdbuf {
int fd; int fd;
struct { buffer_t read;
buffer_t buf; buffer_t write;
ssize_t ret;
} write, read;
}; };
struct crypto_ctx { struct crypto_ctx {
crypto_aead_aes256gcm_state state_r; struct {
crypto_aead_aes256gcm_state state_w; crypto_aead_aes256gcm_state state;
uint8_t nonce_r[crypto_aead_aes256gcm_NPUBBYTES]; uint8_t nonce[crypto_aead_aes256gcm_NPUBBYTES];
uint8_t nonce_w[crypto_aead_aes256gcm_NPUBBYTES]; } write, read;
uint8_t skey[crypto_generichash_KEYBYTES]; uint8_t skey[crypto_generichash_KEYBYTES];
}; };
volatile sig_atomic_t running; volatile sig_atomic_t gt_close = 0;
static void gt_not_available (const char *name)
{
fprintf(stderr, "%s is not available on your platform!\n", name);
}
static int64_t dt_ms (struct timeval *ta, struct timeval *tb) static int64_t dt_ms (struct timeval *ta, struct timeval *tb)
{ {
@@ -77,43 +66,75 @@ static void fd_set_nonblock (int fd)
perror("fcntl O_NONBLOCK"); perror("fcntl O_NONBLOCK");
} }
static void sk_set_nodelay (int fd) enum sk_opt {
sk_nodelay,
sk_reuseaddr,
sk_keepalive,
sk_keepcnt,
sk_keepidle,
sk_keepintvl,
sk_congestion,
sk_defer_accept,
};
static void sk_set (int fd, enum sk_opt opt, const void *val, socklen_t len)
{ {
int val = 1; if (!val || len<=0)
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY , &val, sizeof(val))==-1)
perror("setsockopt TCP_NODELAY");
}
static void sk_set_reuseaddr (int fd)
{
int val = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))==-1)
perror("setsockopt SO_REUSEADDR");
}
#ifdef TCP_CONGESTION
static void sk_set_congestion (int fd, const char *name)
{
size_t len = str_len(name);
if (!len)
return; return;
if (setsockopt(fd, IPPROTO_TCP, TCP_CONGESTION, name, len+1)==-1) struct {
perror("setsockopt TCP_CONGESTION"); const char *name;
} const int present;
#else const int level;
static void sk_set_congestion (_unused_ int fd, _unused_ const char *name) const int option;
{ } opts[] = {
gt_not_available("TCP_CONGESTION"); [sk_nodelay] = { "TCP_NODELAY", 1, IPPROTO_TCP, TCP_NODELAY, },
} [sk_reuseaddr] = { "SO_REUSEADDR", 1, SOL_SOCKET, SO_REUSEADDR, },
[sk_keepalive] = { "SO_KEEPALIVE", 1, SOL_SOCKET, SO_KEEPALIVE, },
[sk_keepcnt] = { "TCP_KEEPCNT",
#ifdef TCP_KEEPCNT
1, IPPROTO_TCP, TCP_KEEPCNT,
#endif #endif
},
[sk_keepidle] = { "TCP_KEEPIDLE",
#ifdef TCP_KEEPIDLE
1, IPPROTO_TCP, TCP_KEEPIDLE,
#endif
},
[sk_keepintvl] = { "TCP_KEEPINTVL",
#ifdef TCP_KEEPINTVL
1, IPPROTO_TCP, TCP_KEEPINTVL,
#endif
},
[sk_congestion] = { "TCP_CONGESTION",
#ifdef TCP_CONGESTION
1, IPPROTO_TCP, TCP_CONGESTION,
#endif
},
[sk_defer_accept] = { "TCP_DEFER_ACCEPT",
#ifdef TCP_DEFER_ACCEPT
1, IPPROTO_TCP, TCP_DEFER_ACCEPT,
#endif
},
};
if (!opts[opt].present) {
gt_na(opts[opt].name);
return;
}
if (setsockopt(fd, opts[opt].level, opts[opt].option, val, len)==-1)
gt_log("couldn't set socket option `%s'\n", opts[opt].name);
}
static void sk_set_int (int fd, enum sk_opt opt, int val)
{
return sk_set(fd, opt, &val, sizeof(val));
}
static int sk_listen (int fd, struct addrinfo *ai) static int sk_listen (int fd, struct addrinfo *ai)
{ {
sk_set_reuseaddr(fd); sk_set_int(fd, sk_reuseaddr, 1);
int ret = bind(fd, ai->ai_addr, ai->ai_addrlen); int ret = bind(fd, ai->ai_addr, ai->ai_addrlen);
@@ -122,13 +143,15 @@ static int sk_listen (int fd, struct addrinfo *ai)
return -1; return -1;
} }
ret = listen(fd, 1); ret = listen(fd, 8);
if (ret==-1) { if (ret==-1) {
perror("listen"); perror("listen");
return -1; return -1;
} }
sk_set_int(fd, sk_defer_accept, GT_TIMEOUT/1000);
return 0; return 0;
} }
@@ -222,8 +245,7 @@ static socklen_t sk_get_info (int fd, struct tcp_info *ti)
static void print_tcp_info (const char *name, struct tcp_info *ti) static void print_tcp_info (const char *name, struct tcp_info *ti)
{ {
fprintf(stderr, gt_log("%s: tcpinfo"
"%s: tcpinfo"
" rto:%" PRIu32 " ato:%" PRIu32 " snd_mss:%" PRIu32 " rto:%" PRIu32 " ato:%" PRIu32 " snd_mss:%" PRIu32
" rcv_mss:%" PRIu32 " unacked:%" PRIu32 " sacked:%" PRIu32 " rcv_mss:%" PRIu32 " unacked:%" PRIu32 " sacked:%" PRIu32
" lost:%" PRIu32 " retrans:%" PRIu32 " fackets:%" PRIu32 " lost:%" PRIu32 " retrans:%" PRIu32 " fackets:%" PRIu32
@@ -243,7 +265,7 @@ static void print_tcp_info (const char *name, struct tcp_info *ti)
static struct addrinfo *ai_create (const char *host, const char *port, int listener) static struct addrinfo *ai_create (const char *host, const char *port, int listener)
{ {
if (!port || !port[0]) { if (!port || !port[0]) {
fprintf(stderr, "port is not valid\n"); gt_log("port is not valid\n");
return NULL; return NULL;
} }
@@ -270,74 +292,21 @@ static struct addrinfo *ai_create (const char *host, const char *port, int liste
break; break;
case EAI_FAIL: case EAI_FAIL:
case EAI_AGAIN: case EAI_AGAIN:
fprintf(stderr, "the name server returned a failure\n"); gt_log("the name server returned a failure\n");
break; break;
default: default:
fprintf(stderr, "%s.%s is not valid\n", host?:"", port); gt_log("%s.%s is not valid\n", host?:"", port);
} }
return NULL; return NULL;
} }
#ifdef __linux__
static int tun_create (char *name, int multiqueue)
{
int fd = open("/dev/net/tun", O_RDWR);
if (fd<0) {
perror("open /dev/net/tun");
return -1;
}
struct ifreq ifr = {
.ifr_flags = IFF_TUN|IFF_NO_PI,
};
if (multiqueue) {
#ifdef IFF_MULTI_QUEUE
ifr.ifr_flags |= IFF_MULTI_QUEUE;
#else
gt_not_available("IFF_MULTI_QUEUE");
#endif
}
str_cpy(ifr.ifr_name, name, IFNAMSIZ-1);
int ret = ioctl(fd, TUNSETIFF, &ifr);
if (ret<0) {
perror("ioctl TUNSETIFF");
return -1;
}
printf("tun name: %s\n", ifr.ifr_name);
return fd;
}
#else
static int tun_create (_unused_ char *name, _unused_ int mq)
{
for (unsigned dev_id = 0U; dev_id < 32U; dev_id++) {
char dev_path[11U];
snprintf(dev_path, sizeof(dev_path), "/dev/tun%u", dev_id);
int fd = open(dev_path, O_RDWR);
if (fd!=-1)
return fd;
}
return -1;
}
#endif
static void gt_sa_stop (int sig) static void gt_sa_stop (int sig)
{ {
switch (sig) { switch (sig) {
case SIGINT: case SIGINT:
case SIGTERM: case SIGTERM:
running = 0; gt_close = 1;
} }
} }
@@ -346,7 +315,6 @@ static void gt_set_signal (void)
struct sigaction sa; struct sigaction sa;
byte_set(&sa, 0, sizeof(sa)); byte_set(&sa, 0, sizeof(sa));
running = 1;
sa.sa_handler = gt_sa_stop; sa.sa_handler = gt_sa_stop;
sigaction(SIGINT, &sa, NULL); sigaction(SIGINT, &sa, NULL);
@@ -407,7 +375,7 @@ static ssize_t fd_read_all (int fd, void *data, size_t size)
}; };
while (done<size) { while (done<size) {
ssize_t ret = fd_read(fd, data+done, size-done); ssize_t ret = fd_read(fd, (uint8_t *)data+done, size-done);
if (!ret) if (!ret)
break; break;
@@ -434,7 +402,7 @@ static ssize_t fd_write_all (int fd, const void *data, size_t size)
}; };
while (done<size) { while (done<size) {
ssize_t ret = fd_write(fd, data+done, size-done); ssize_t ret = fd_write(fd, (const uint8_t *)data+done, size-done);
if (!ret) if (!ret)
break; break;
@@ -451,52 +419,69 @@ static ssize_t fd_write_all (int fd, const void *data, size_t size)
return done; return done;
} }
static int encrypt_packet (struct crypto_ctx *ctx, uint8_t *packet, size_t size, buffer_t *buffer) static int gt_encrypt (struct crypto_ctx *ctx, buffer_t *dst, buffer_t *src)
{ {
const size_t ws = size + crypto_aead_aes256gcm_ABYTES; size_t rs = buffer_read_size(src);
size_t ws = buffer_write_size(dst);
if (buffer_write_size(buffer) < ws) if (!rs || !ws)
return 1; return 0;
const int hs = 4; size_t size = rs+crypto_aead_aes256gcm_ABYTES;
byte_cpy(buffer->write, packet, size); if (size+2>ws)
return 0;
dst->write[0] = 0xFF&(size>>8);
dst->write[1] = 0xFF&(size);
crypto_aead_aes256gcm_encrypt_afternm( crypto_aead_aes256gcm_encrypt_afternm(
buffer->write + hs, NULL, dst->write+2, NULL,
packet + hs, size - hs, src->read, rs,
packet, hs, dst->write, 2,
NULL, ctx->nonce_w, NULL, ctx->write.nonce,
(const crypto_aead_aes256gcm_state *)&ctx->state_w); (const crypto_aead_aes256gcm_state *)&ctx->write.state);
sodium_increment(ctx->nonce_w, crypto_aead_aes256gcm_NPUBBYTES); sodium_increment(ctx->write.nonce, crypto_aead_aes256gcm_NPUBBYTES);
buffer->write += ws;
src->read += rs;
dst->write += size+2;
return 0; return 0;
} }
static int decrypt_packet (struct crypto_ctx *ctx, uint8_t *packet, size_t size, buffer_t *buffer) static int gt_decrypt (struct crypto_ctx *ctx, buffer_t *dst, buffer_t *src)
{ {
const size_t rs = size + crypto_aead_aes256gcm_ABYTES; size_t rs = buffer_read_size(src);
size_t ws = buffer_write_size(dst);
if (buffer_read_size(buffer) < rs) if (!rs || !ws)
return 1; return 0;
const int hs = 4; if (rs<=2+16)
return 0;
byte_cpy(packet, buffer->read, hs); size_t size = (src->read[0]<<8)|src->read[1];
if (size-crypto_aead_aes256gcm_ABYTES>ws)
return 0;
if (size+2>rs)
return 0;
if (crypto_aead_aes256gcm_decrypt_afternm( if (crypto_aead_aes256gcm_decrypt_afternm(
packet + hs, NULL, dst->write, NULL,
NULL, NULL,
buffer->read + hs, rs - hs, src->read+2, size,
packet, hs, src->read, 2,
ctx->nonce_r, ctx->read.nonce,
(const crypto_aead_aes256gcm_state *)&ctx->state_r)) (const crypto_aead_aes256gcm_state *)&ctx->read.state))
return -1; return -1;
sodium_increment(ctx->nonce_r, crypto_aead_aes256gcm_NPUBBYTES); sodium_increment(ctx->read.nonce, crypto_aead_aes256gcm_NPUBBYTES);
buffer->read += rs;
src->read += size+2;
dst->write += size-crypto_aead_aes256gcm_ABYTES;
return 0; return 0;
} }
@@ -516,24 +501,7 @@ static void dump_ip_header (uint8_t *data, size_t size)
hex[40] = 0; hex[40] = 0;
fprintf(stderr, "DUMP(%zu): %s\n", size, hex); gt_log("DUMP(%zu): %s\n", size, hex);
}
static void set_ip_size (uint8_t *data, size_t size)
{
data[2] = 0xFF&(size>>8);
data[3] = 0xFF&(size);
}
static ssize_t get_ip_size (const uint8_t *data, size_t size)
{
if (size<20)
return -1;
if ((data[0]>>4)==4)
return (data[2]<<8)|data[3];
return 0;
} }
static int gt_setup_secretkey (struct crypto_ctx *ctx, char *keyfile) static int gt_setup_secretkey (struct crypto_ctx *ctx, char *keyfile)
@@ -545,21 +513,23 @@ static int gt_setup_secretkey (struct crypto_ctx *ctx, char *keyfile)
if (!keyfile) if (!keyfile)
return 0; return 0;
int fd = open(keyfile, O_RDONLY|O_CLOEXEC); int fd;
if (fd<0) { do {
fd = open(keyfile, O_RDONLY|O_CLOEXEC);
} while (fd==-1 && errno==EINTR);
if (fd==-1) {
perror("open keyfile"); perror("open keyfile");
return -1; return -1;
} }
if (fd_read_all(fd, ctx->skey, size)!=size) { if (fd_read_all(fd, ctx->skey, size)!=size) {
fprintf(stderr, "unable to read secret key in `%s'\n", keyfile); gt_log("unable to read secret key in `%s'\n", keyfile);
close(fd); close(fd);
return -1; return -1;
} }
// TODO: check key
close(fd); close(fd);
return 0; return 0;
@@ -569,22 +539,25 @@ static int gt_setup_crypto (struct crypto_ctx *ctx, int fd, int listener)
{ {
const size_t nonce_size = crypto_aead_aes256gcm_NPUBBYTES; const size_t nonce_size = crypto_aead_aes256gcm_NPUBBYTES;
const size_t public_size = crypto_scalarmult_SCALARBYTES; const size_t public_size = crypto_scalarmult_SCALARBYTES;
const size_t hkey_size = crypto_generichash_BYTES; const size_t hash_size = crypto_generichash_BYTES;
const size_t size = nonce_size + public_size + hkey_size; const size_t size = nonce_size + public_size + hash_size;
uint8_t secret[crypto_scalarmult_SCALARBYTES]; uint8_t secret[crypto_scalarmult_SCALARBYTES];
uint8_t shared[crypto_scalarmult_BYTES]; uint8_t shared[crypto_scalarmult_BYTES];
uint8_t key[crypto_aead_aes256gcm_KEYBYTES]; uint8_t key[crypto_aead_aes256gcm_KEYBYTES];
uint8_t data_r[size], data_w[size]; uint8_t data_r[size], data_w[size];
uint8_t hkey_c[hkey_size]; uint8_t auth_r[hash_size], auth_w[hash_size];
uint8_t hash[hash_size];
crypto_generichash_state state;
randombytes_buf(data_w, nonce_size); randombytes_buf(data_w, nonce_size);
randombytes_buf(secret, sizeof(secret)); randombytes_buf(secret, sizeof(secret));
crypto_scalarmult_base(&data_w[nonce_size], secret); crypto_scalarmult_base(&data_w[nonce_size], secret);
crypto_generichash(&data_w[size-hkey_size], hkey_size, crypto_generichash(&data_w[size-hash_size], hash_size,
data_w, size-hkey_size, ctx->skey, sizeof(ctx->skey)); data_w, size-hash_size, ctx->skey, sizeof(ctx->skey));
if (!listener && fd_write_all(fd, data_w, size)!=size) if (!listener && fd_write_all(fd, data_w, size)!=size)
return -1; return -1;
@@ -592,38 +565,53 @@ static int gt_setup_crypto (struct crypto_ctx *ctx, int fd, int listener)
if (fd_read_all(fd, data_r, size)!=size) if (fd_read_all(fd, data_r, size)!=size)
return -1; return -1;
crypto_generichash(hkey_c, hkey_size, crypto_generichash(hash, hash_size,
data_r, size-hkey_size, ctx->skey, sizeof(ctx->skey)); data_r, size-hash_size, ctx->skey, sizeof(ctx->skey));
if (sodium_memcmp(&data_r[size-hkey_size], hkey_c, hkey_size)) if (sodium_memcmp(&data_r[size-hash_size], hash, hash_size))
return -2; return -2;
if (listener && fd_write_all(fd, data_w, size)!=size) if (listener && fd_write_all(fd, data_w, size)!=size)
return -1; return -1;
crypto_scalarmult(shared, secret, &data_r[nonce_size]); crypto_generichash(auth_w, hash_size,
data_r, size, ctx->skey, sizeof(ctx->skey));
if (fd_write_all(fd, auth_w, hash_size)!=hash_size)
return -1;
if (fd_read_all(fd, auth_r, hash_size)!=hash_size)
return -1;
crypto_generichash(hash, hash_size,
data_w, size, ctx->skey, sizeof(ctx->skey));
if (sodium_memcmp(auth_r, hash, hash_size))
return -2;
if (crypto_scalarmult(shared, secret, &data_r[nonce_size]))
return -2;
crypto_generichash_state state;
crypto_generichash_init(&state, ctx->skey, sizeof(ctx->skey), sizeof(key)); crypto_generichash_init(&state, ctx->skey, sizeof(ctx->skey), sizeof(key));
crypto_generichash_update(&state, shared, sizeof(shared)); crypto_generichash_update(&state, shared, sizeof(shared));
crypto_generichash_update(&state, data_r, size); crypto_generichash_update(&state, data_r, size);
crypto_generichash_update(&state, data_w, size); crypto_generichash_update(&state, data_w, size);
crypto_generichash_final(&state, key, sizeof(key)); crypto_generichash_final(&state, key, sizeof(key));
crypto_aead_aes256gcm_beforenm(&ctx->state_r, key); crypto_aead_aes256gcm_beforenm(&ctx->read.state, key);
crypto_generichash_init(&state, ctx->skey, sizeof(ctx->skey), sizeof(key)); crypto_generichash_init(&state, ctx->skey, sizeof(ctx->skey), sizeof(key));
crypto_generichash_update(&state, shared, sizeof(shared)); crypto_generichash_update(&state, shared, sizeof(shared));
crypto_generichash_update(&state, data_w, size); crypto_generichash_update(&state, data_w, size);
crypto_generichash_update(&state, data_r, size); crypto_generichash_update(&state, data_r, size);
crypto_generichash_final(&state, key, sizeof(key)); crypto_generichash_final(&state, key, sizeof(key));
crypto_aead_aes256gcm_beforenm(&ctx->state_w, key); crypto_aead_aes256gcm_beforenm(&ctx->write.state, key);
sodium_memzero(secret, sizeof(secret)); sodium_memzero(secret, sizeof(secret));
sodium_memzero(shared, sizeof(shared)); sodium_memzero(shared, sizeof(shared));
sodium_memzero(key, sizeof(key)); sodium_memzero(key, sizeof(key));
byte_cpy(ctx->nonce_r, data_r, nonce_size); byte_cpy(ctx->read.nonce, data_r, nonce_size);
byte_cpy(ctx->nonce_w, data_w, nonce_size); byte_cpy(ctx->write.nonce, data_w, nonce_size);
return 0; return 0;
} }
@@ -632,16 +620,15 @@ int main (int argc, char **argv)
{ {
gt_set_signal(); gt_set_signal();
int listener = 0;
char *host = NULL; char *host = NULL;
char *port = "5000"; char *port = "5000";
char *dev = PACKAGE_NAME; char *dev = PACKAGE_NAME;
char *keyfile = NULL; char *keyfile = NULL;
char *congestion = NULL; char *congestion = NULL;
int delay = 0; long buffer_size = GT_BUFFER_SIZE;
int multiqueue = 0; long ka_count = -1;
int version = 0; long ka_idle = -1;
int debug = 0; long ka_interval = -1;
#ifdef TCP_INFO #ifdef TCP_INFO
struct { struct {
@@ -650,35 +637,55 @@ int main (int argc, char **argv)
} tcpinfo = {0}; } tcpinfo = {0};
#endif #endif
struct option ka_opts[] = {
{ "count", &ka_count, option_long },
{ "idle", &ka_idle, option_long },
{ "interval", &ka_interval, option_long },
{ NULL },
};
struct option opts[] = { struct option opts[] = {
{ "listener", &listener, option_flag }, { "listener", NULL, option_option },
{ "host", &host, option_str }, { "host", &host, option_str },
{ "port", &port, option_str }, { "port", &port, option_str },
{ "dev", &dev, option_str }, { "dev", &dev, option_str },
{ "keyfile", &keyfile, option_str }, { "keyfile", &keyfile, option_str },
{ "congestion", &congestion, option_str }, { "congestion", &congestion, option_str },
{ "delay", &delay, option_flag }, { "delay", NULL, option_option },
{ "multiqueue", &multiqueue, option_flag }, { "multiqueue", NULL, option_option },
{ "debug", &debug, option_flag }, { "keepalive", ka_opts, option_option },
{ "version", &version, option_flag }, { "buffer-size", &buffer_size, option_long },
{ "daemon", NULL, option_option },
{ "debug", NULL, option_option },
{ "version", NULL, option_option },
{ NULL }, { NULL },
}; };
if (option(opts, argc, argv)) if (option(opts, argc, argv))
return 1; return 1;
if (version) { if (option_is_set(opts, "version")) {
printf(PACKAGE_STRING"\n"); gt_print(PACKAGE_STRING"\n");
return 0; return 0;
} }
int listener = option_is_set(opts, "listener");
int delay = option_is_set(opts, "delay");
int debug = option_is_set(opts, "debug");
int keepalive = option_is_set(opts, "keepalive");
if (buffer_size < 2048) {
buffer_size = 2048;
gt_log("buffer size must be greater than 2048!\n");
}
if (sodium_init()==-1) { if (sodium_init()==-1) {
fprintf(stderr, "libsodium initialization has failed!\n"); gt_log("libsodium initialization has failed!\n");
return 1; return 1;
} }
if (!crypto_aead_aes256gcm_is_available()) { if (!crypto_aead_aes256gcm_is_available()) {
gt_not_available("AES-256-GCM"); gt_na("AES-256-GCM");
return 1; return 1;
} }
@@ -692,18 +699,21 @@ int main (int argc, char **argv)
if (!ai) if (!ai)
return 1; return 1;
struct netio tun = { .fd = -1 }; struct fdbuf tun = { .fd = -1 };
struct netio sock = { .fd = -1 }; struct fdbuf sock = { .fd = -1 };
tun.fd = tun_create(dev, multiqueue); tun.fd = tun_create(dev, option_is_set(opts, "multiqueue"));
if (tun.fd==-1) if (tun.fd==-1)
return 1; return 1;
fd_set_nonblock(tun.fd); fd_set_nonblock(tun.fd);
buffer_setup(&sock.write.buf, NULL, GT_BUFFER_SIZE); buffer_setup(&tun.write, NULL, 32*1024);
buffer_setup(&sock.read.buf, NULL, GT_BUFFER_SIZE); buffer_setup(&tun.read, NULL, 32*1024);
buffer_setup(&sock.write, NULL, buffer_size);
buffer_setup(&sock.read, NULL, buffer_size);
int fd = -1; int fd = -1;
@@ -714,12 +724,26 @@ int main (int argc, char **argv)
return 1; return 1;
} }
while (running) { if (option_is_set(opts, "daemon")) {
switch (fork()) {
case -1:
perror("fork");
return 1;
case 0:
if (setsid()==-1)
perror("setsid");
break;
default:
_exit(0);
}
}
while (!gt_close) {
sock.fd = listener?sk_accept(fd):sk_create(ai, sk_connect); sock.fd = listener?sk_accept(fd):sk_create(ai, sk_connect);
if (sock.fd==-1) { if (sock.fd==-1) {
usleep(100000); usleep(100000);
continue; goto restart;
} }
char *sockname = sk_get_name(sock.fd); char *sockname = sk_get_name(sock.fd);
@@ -727,39 +751,72 @@ int main (int argc, char **argv)
if (!sockname) if (!sockname)
goto restart; goto restart;
fprintf(stderr, "%s: connected\n", sockname); gt_log("%s: connected\n", sockname);
if (!delay)
sk_set_nodelay(sock.fd);
fd_set_nonblock(sock.fd); fd_set_nonblock(sock.fd);
sk_set_congestion(sock.fd, congestion);
sk_set_int(sock.fd, sk_nodelay, !delay);
sk_set_int(sock.fd, sk_keepalive, keepalive);
if (keepalive) {
if (ka_count>=0 && ka_count<=INT_MAX)
sk_set_int(sock.fd, sk_keepcnt, ka_count);
if (ka_idle>=0 && ka_idle<=INT_MAX)
sk_set_int(sock.fd, sk_keepidle, ka_idle);
if (ka_interval>=0 && ka_interval<=INT_MAX)
sk_set_int(sock.fd, sk_keepintvl, ka_interval);
}
sk_set(sock.fd, sk_congestion, congestion, str_len(congestion));
switch (gt_setup_crypto(&ctx, sock.fd, listener)) { switch (gt_setup_crypto(&ctx, sock.fd, listener)) {
case -2: fprintf(stderr, "%s: key exchange could not be verified!\n", sockname); case -2: gt_log("%s: key exchange could not be verified!\n", sockname);
case -1: goto restart; case -1: goto restart;
default: break; default: break;
} }
struct pollfd fds[] = { fd_set rfds, wfds;
{ .fd = tun.fd, .events = POLLIN }, FD_ZERO(&rfds);
{ .fd = sock.fd, .events = POLLIN }, FD_ZERO(&wfds);
};
struct { int stop_loop = 0;
uint8_t buf[2048];
size_t size;
} tunr, tunw;
tunr.size = 0; buffer_format(&sock.write);
tunw.size = 0; buffer_format(&sock.read);
while (running) { while (1) {
if (poll(fds, COUNT(fds), -1)==-1 && errno!=EINTR) { if (gt_close)
perror("poll"); stop_loop |= 1;
if (stop_loop) {
if (((stop_loop&(1<<2)) || !buffer_read_size(&sock.write)) &&
((stop_loop&(1<<1)) || !buffer_read_size(&sock.read)))
goto restart;
FD_CLR(tun.fd, &rfds);
} else {
FD_SET(tun.fd, &rfds);
}
FD_SET(sock.fd, &rfds);
if (buffer_read_size(&tun.read))
FD_SET(sock.fd, &wfds);
if (buffer_read_size(&sock.read))
FD_SET(tun.fd, &wfds);
if (select(sock.fd+1, &rfds, &wfds, NULL, NULL)==-1) {
if (errno==EINTR)
continue;
perror("select");
return 1; return 1;
} }
FD_CLR(sock.fd, &wfds);
FD_CLR(tun.fd, &wfds);
#ifdef TCP_INFO #ifdef TCP_INFO
struct timeval now; struct timeval now;
gettimeofday(&now, NULL); gettimeofday(&now, NULL);
@@ -771,14 +828,16 @@ int main (int argc, char **argv)
} }
#endif #endif
buffer_shift(&sock.write.buf); buffer_shift(&tun.read);
if (fds[0].revents & POLLIN) { if (FD_ISSET(tun.fd, &rfds)) {
while (1) { while (1) {
if (buffer_write_size(&sock.write.buf)<sizeof(tunr.buf)+16) size_t size = buffer_write_size(&tun.read);
if (size<1500)
break; break;
ssize_t r = fd_read(fds[0].fd, tunr.buf, sizeof(tunr.buf)); ssize_t r = tun_read(tun.fd, tun.read.write, size);
if (!r) if (!r)
return 2; return 2;
@@ -786,89 +845,90 @@ int main (int argc, char **argv)
if (r<0) if (r<0)
break; break;
ssize_t ip_size = get_ip_size(tunr.buf, sizeof(tunr.buf)); ssize_t ip_size = ip_get_size(tun.read.write, size);
if (ip_size<=0) if (ip_size<=0)
continue; continue;
if (ip_size!=r) { if (ip_size!=r) {
dump_ip_header(tunr.buf, r); dump_ip_header(tun.read.write, r);
if (r<ip_size) { if (r<ip_size) {
set_ip_size(tunr.buf, r); ip_set_size(tun.read.write, r);
} else { } else {
continue; continue;
} }
} }
encrypt_packet(&ctx, tunr.buf, r, &sock.write.buf); tun.read.write += r;
} }
} }
if (fds[1].revents & POLLOUT) gt_encrypt(&ctx, &sock.write, &tun.read);
fds[1].events = POLLIN;
if (buffer_read_size(&sock.write.buf)) { if (buffer_read_size(&sock.write)) {
sock.write.ret = fd_write(fds[1].fd, sock.write.buf.read, buffer_read_size(&sock.write.buf)); ssize_t r = fd_write(sock.fd, sock.write.read,
buffer_read_size(&sock.write));
if (!sock.write.ret) if (r==-1)
goto restart; FD_SET(sock.fd, &wfds);
if (sock.write.ret==-1) if (!r)
fds[1].events = POLLIN|POLLOUT; stop_loop |= (1<<2);
if (sock.write.ret>0) if (r>0)
sock.write.buf.read += sock.write.ret; sock.write.read += r;
} else {
if (stop_loop) {
gt_log("%s: shutdown\n", sockname);
shutdown(sock.fd, SHUT_WR);
}
} }
buffer_shift(&sock.read.buf); buffer_shift(&sock.write);
buffer_shift(&sock.read);
if (fds[1].revents & POLLIN) { if (FD_ISSET(sock.fd, &rfds)) {
sock.read.ret = fd_read(fds[1].fd, sock.read.buf.write, buffer_write_size(&sock.read.buf)); ssize_t r = fd_read(sock.fd, sock.read.write,
buffer_write_size(&sock.read));
if (!sock.read.ret) if (!r)
goto restart; stop_loop |= (1<<1);
if (sock.read.ret>0) if (r>0)
sock.read.buf.write += sock.read.ret; sock.read.write += r;
} }
if (fds[0].revents & POLLOUT) if (gt_decrypt(&ctx, &tun.write, &sock.read)) {
fds[0].events = POLLIN; gt_log("%s: message could not be verified!\n", sockname);
goto restart;
}
while (1) { while (1) {
if (!tunw.size) { size_t size = buffer_read_size(&tun.write);
size_t size = buffer_read_size(&sock.read.buf); ssize_t ip_size = ip_get_size(tun.write.read, size);
ssize_t ip_size = get_ip_size(sock.read.buf.read, size);
if (!ip_size) if (!ip_size) {
goto restart; gt_log("%s: bad packet!\n", sockname);
goto restart;
if (ip_size<0 || (size_t)ip_size+16>size)
break;
if (decrypt_packet(&ctx, tunw.buf, ip_size, &sock.read.buf)) {
fprintf(stderr, "%s: message could not be verified!\n", sockname);
goto restart;
}
tunw.size = ip_size;
} }
if (tunw.size) {
ssize_t r = fd_write(fds[0].fd, tunw.buf, tunw.size);
if (!r) if (ip_size<0 || (size_t)ip_size>size)
return 2; break;
if (r==-1) ssize_t r = tun_write(tun.fd, tun.write.read, ip_size);
fds[0].events = POLLIN|POLLOUT;
if (r<0) if (!r)
break; return 2;
tunw.size = 0; if (r==-1)
} FD_SET(tun.fd, &wfds);
if (r>0)
tun.write.read += r;
} }
buffer_shift(&tun.write);
} }
restart: restart:
@@ -877,14 +937,16 @@ int main (int argc, char **argv)
sockname = NULL; sockname = NULL;
} }
close(sock.fd); if (sock.fd!=-1) {
sock.fd = -1; close(sock.fd);
sock.fd = -1;
}
} }
freeaddrinfo(ai); freeaddrinfo(ai);
free(sock.write.buf.data); free(sock.write.data);
free(sock.read.buf.data); free(sock.read.data);
return 0; return 0;
} }

View File

@@ -5,18 +5,10 @@
#include "option.h" #include "option.h"
int option_flag (void *data, _unused_ int argc, _unused_ char **argv)
{
const int one = 1;
byte_cpy(data, &one, sizeof(one));
return 0;
}
int option_str (void *data, int argc, char **argv) int option_str (void *data, int argc, char **argv)
{ {
if (argc<2 || !argv[1]) { if (argc<2 || !argv[1]) {
printf("option `%s' need a string argument\n", argv[0]); gt_print("option `%s' need a string argument\n", argv[0]);
return -1; return -1;
} }
@@ -28,7 +20,7 @@ int option_str (void *data, int argc, char **argv)
int option_long (void *data, int argc, char **argv) int option_long (void *data, int argc, char **argv)
{ {
if (argc<2 || !argv[1]) { if (argc<2 || !argv[1]) {
printf("option `%s' need an integer argument\n", argv[0]); gt_print("option `%s' need an integer argument\n", argv[0]);
return -1; return -1;
} }
@@ -37,7 +29,7 @@ int option_long (void *data, int argc, char **argv)
long val = strtol(argv[1], &end, 0); long val = strtol(argv[1], &end, 0);
if (errno || argv[1]==end) { if (errno || argv[1]==end) {
printf("argument `%s' is not a valid integer\n", argv[1]); gt_print("argument `%s' is not a valid integer\n", argv[1]);
return -1; return -1;
} }
@@ -46,8 +38,21 @@ int option_long (void *data, int argc, char **argv)
return 1; return 1;
} }
int option_is_set (struct option *opts, const char *name)
{
for (int k=0; opts[k].name; k++) {
if (!str_cmp(opts[k].name, name))
return opts[k].set;
}
return 0;
}
int option_option (void *data, int argc, char **argv) int option_option (void *data, int argc, char **argv)
{ {
if (!data)
return 0;
struct option *opts = (struct option *)data; struct option *opts = (struct option *)data;
for (int k=0; opts[k].name; k++) for (int k=0; opts[k].name; k++)
@@ -61,7 +66,7 @@ int option_option (void *data, int argc, char **argv)
continue; continue;
if (opts[k].set) { if (opts[k].set) {
printf("option `%s' is already set\n", opts[k].name); gt_print("option `%s' is already set\n", opts[k].name);
return -1; return -1;
} }
@@ -84,31 +89,31 @@ int option_option (void *data, int argc, char **argv)
return argc; return argc;
} }
static void option_usage (struct option *opts, char *name) static int option_usage (struct option *opts, int slen)
{ {
char *usage = "usage: "; if (!opts)
size_t slen = str_len(usage)+str_len(name); return 0;
size_t len = slen;
printf("%s%s", usage, name); int len = slen;
if (slen>40)
slen = 12;
for (int k=0; opts[k].name; k++) { for (int k=0; opts[k].name; k++) {
char *arg = (opts[k].call==option_flag)?"":" ARG"; if (len>60) {
size_t inc = str_len(opts[k].name)+str_len(arg)+3; gt_print("\n%*s", (int)slen, "");
if (len+inc>72) {
printf("\n%*s", (int)slen, "");
len = slen; len = slen;
} }
printf(" [%s%s]", opts[k].name, arg); len += gt_print(" [%s", opts[k].name);
len += inc;
if (opts[k].call==option_option) {
len += option_usage((struct option *)opts[k].data, len);
} else {
len += gt_print(" ARG");
}
len += gt_print("]");
} }
printf("\n"); return len;
} }
int option (struct option *opts, int argc, char **argv) int option (struct option *opts, int argc, char **argv)
@@ -121,8 +126,16 @@ int option (struct option *opts, int argc, char **argv)
if (ret<0 || ret+1>=argc) if (ret<0 || ret+1>=argc)
return 1; return 1;
printf("option `%s' is unknown\n", argv[ret+1]); gt_print("option `%s' is unknown\n", argv[ret+1]);
option_usage(opts, argv[0]);
int slen = gt_print("usage: %s", argv[0]);
if (slen>40)
slen = 12;
option_usage(opts, slen);
printf("\n");
return 1; return 1;
} }

View File

@@ -7,9 +7,9 @@ struct option {
int set; int set;
}; };
int option_flag (void *, int, char **); int option_option (void *, int, char **);
int option_str (void *, int, char **); int option_str (void *, int, char **);
int option_long (void *, int, char **); int option_long (void *, int, char **);
int option_option (void *, int, char **);
int option (struct option *, int, char **); int option_is_set (struct option *, const char *);
int option (struct option *, int, char **);

209
src/tun.c Normal file
View File

@@ -0,0 +1,209 @@
#include "common-static.h"
#include "ip-static.h"
#include "tun.h"
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/uio.h>
#ifdef __linux__
# include <linux/if.h>
# include <linux/if_tun.h>
#endif
#ifdef __APPLE__
# include <sys/sys_domain.h>
# include <sys/kern_control.h>
# include <net/if_utun.h>
#endif
#if defined(__APPLE__) || defined(__OpenBSD__)
# define GT_BSD_TUN 1
#endif
#ifdef __linux__
int tun_create (char *name, int multiqueue)
{
int fd = open("/dev/net/tun", O_RDWR);
if (fd<0) {
perror("open /dev/net/tun");
return -1;
}
struct ifreq ifr = {
.ifr_flags = IFF_TUN|IFF_NO_PI,
};
if (multiqueue) {
#ifdef IFF_MULTI_QUEUE
ifr.ifr_flags |= IFF_MULTI_QUEUE;
#else
gt_na("IFF_MULTI_QUEUE");
#endif
}
str_cpy(ifr.ifr_name, name, IFNAMSIZ-1);
int ret = ioctl(fd, TUNSETIFF, &ifr);
if (ret<0) {
perror("ioctl TUNSETIFF");
return -1;
}
gt_log("tun name: %s\n", ifr.ifr_name);
return fd;
}
#elif defined(__APPLE__)
int tun_create (_unused_ char *name, _unused_ int mq)
{
for (unsigned dev_id = 0; dev_id < 32; dev_id++) {
struct ctl_info ci;
byte_set(&ci, 0, sizeof(ci));
str_cpy(ci.ctl_name, UTUN_CONTROL_NAME, sizeof(ci.ctl_name)-1);
int fd = socket(PF_SYSTEM, SOCK_DGRAM, SYSPROTO_CONTROL);
if (fd==-1)
return -1;
if (ioctl(fd, CTLIOCGINFO, &ci)==-1) {
close(fd);
continue;
}
struct sockaddr_ctl sc = {
.sc_id = ci.ctl_id,
.sc_len = sizeof(sc),
.sc_family = AF_SYSTEM,
.ss_sysaddr = AF_SYS_CONTROL,
.sc_unit = dev_id+1,
};
if (connect(fd, (struct sockaddr *)&sc, sizeof(sc))==-1) {
close(fd);
continue;
}
gt_log("tun name: /dev/utun%u\n", dev_id);
return fd;
}
return -1;
}
#else
int tun_create (_unused_ char *name, _unused_ int mq)
{
for (unsigned dev_id = 0; dev_id < 32; dev_id++) {
char dev_path[11];
snprintf(dev_path, sizeof(dev_path), "/dev/tun%u", dev_id);
int fd = open(dev_path, O_RDWR);
if (fd==-1)
continue;
gt_log("tun name: %s\n", dev_path);
return fd;
}
return -1;
}
#endif
ssize_t tun_read (int fd, void *data, size_t size)
{
if (!size)
return -2;
#ifdef GT_BSD_TUN
uint32_t family;
struct iovec iov[2] = {
{ .iov_base = &family, .iov_len = sizeof(family) },
{ .iov_base = data, .iov_len = size }
};
ssize_t ret = readv(fd, iov, 2);
#else
ssize_t ret = read(fd, data, size);
#endif
if (ret==-1) {
if (errno==EAGAIN || errno==EINTR)
return -1;
if (errno)
perror("tun read");
return 0;
}
#ifdef GT_BSD_TUN
if (ret<(ssize_t) sizeof(family))
return 0;
return ret-sizeof(family);
#else
return ret;
#endif
}
ssize_t tun_write (int fd, const void *data, size_t size)
{
if (!size)
return -2;
#ifdef GT_BSD_TUN
uint32_t family;
switch (ip_get_version(data, size)) {
case 4:
family = htonl(AF_INET);
break;
case 6:
family = htonl(AF_INET6);
break;
default:
return -1;
}
struct iovec iov[2] = {
{ .iov_base = &family, .iov_len = sizeof(family) },
{ .iov_base = (void *) data, .iov_len = size },
};
ssize_t ret = writev(fd, iov, 2);
#else
ssize_t ret = write(fd, data, size);
#endif
if (ret==-1) {
if (errno==EAGAIN || errno==EINTR)
return -1;
if (errno)
perror("tun write");
return 0;
}
#ifdef GT_BSD_TUN
if (ret<(ssize_t) sizeof(family))
return 0;
return ret-sizeof(family);
#else
return ret;
#endif
}

7
src/tun.h Normal file
View File

@@ -0,0 +1,7 @@
#pragma once
#include <unistd.h>
int tun_create (char *, int);
ssize_t tun_read (int, void *, size_t);
ssize_t tun_write (int, const void *, size_t);