Skip to content

Commit

Permalink
begin generic tun impl
Browse files Browse the repository at this point in the history
  • Loading branch information
radkesvat committed Aug 2, 2024
1 parent 2e9e94f commit df86a06
Show file tree
Hide file tree
Showing 5 changed files with 441 additions and 0 deletions.
Empty file added ww/managers/tundevice_manager.c
Empty file.
Empty file added ww/managers/tundevice_manager.h
Empty file.
19 changes: 19 additions & 0 deletions ww/tundevice/tun.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#pragma once
#include "hloop.h"
#include "hplatform.h"
#include <stdint.h>

typedef union {
int fd; // Unix file descriptor
void *handle; // Windows handle (void* can hold HANDLE)
} tun_handle_t;

typedef struct tun_device_s
{
char *name;
hio_t *io;
tun_handle_t handle;

} tun_device_t;

tun_device_t *createTunDevice(hloop_t *loop, const char *name, bool offload);
48 changes: 48 additions & 0 deletions ww/tundevice/tun_unix.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#include "tun.h"
#include "ww.h"
#include <arpa/inet.h>
#include <fcntl.h>
#include <linux/if.h>
#include <linux/if_tun.h>
#include <netinet/ip.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>

tun_device_t *createTunDevice(hloop_t *loop, const char *name, bool offload)
{
(void) offload; // todo (send/receive offloading)

struct ifreq ifr;

int fd = open("/dev/net/tun", O_RDWR);
if (fd < 0)
{
perror("Opening /dev/net/tun");
return NULL;
}

memset(&ifr, 0, sizeof(ifr));

ifr.ifr_flags = IFF_TUN | IFF_NO_PI; // TUN device, no packet information
if (*name)
{
strncpy(ifr.ifr_name, name, IFNAMSIZ);
}

int err = ioctl(fd, TUNSETIFF, (void *) &ifr);
if (err < 0)
{
perror("ioctl(TUNSETIFF)");
close(fd);
return NULL;
}

tun_device_t *tdev = globalMalloc(sizeof(tun_device_t));
*tdev = (tun_device_t) {.name = strdup(ifr.ifr_name), .handle = (tun_handle_t) {.fd = fd}, .io = hio_get(loop, fd)};

return tdev;
}

Loading

0 comments on commit df86a06

Please sign in to comment.