libtun/source/libtun/adapter.d

83 lines
1.6 KiB
D
Raw Normal View History

module libtun.adapter;
extern (C) int ioctl(int fd, ulong request, void* data);
extern (C) int open(char* path, int flags);
2021-07-18 18:45:17 +01:00
import core.stdc.stdio;
/**
* TUN maintenance routines in `tunctl.c`
*/
2021-07-18 18:23:16 +01:00
extern (C) int createTun(char* interfaceName, int iffFlags);
extern (C) int destroyTun(int fd);
2021-07-18 18:45:17 +01:00
extern (C) int tunWrite(int fd, char* data, int length);
extern (C) int tunRead(int fd, char* data);
public class TUNAdapter
{
2021-07-18 18:45:17 +01:00
/* Tunnel device descriptor */
private int tunFD;
private bool isClosed;
2021-07-18 18:45:17 +01:00
this(string interfaceName, AdapterType adapterType = AdapterType.TAP)
{
2021-07-18 18:45:17 +01:00
init(interfaceName);
}
2021-07-18 18:45:17 +01:00
private void init(string interfaceName)
{
2021-07-18 18:45:17 +01:00
tunFD = createTun(cast(char*)interfaceName, 1);
if(tunFD < 0)
{
throw new TUNException("Error creating tun device");
}
}
private void sanityCheck()
{
if(isClosed)
{
throw new TUNException("Cannot operate on closed tunnel device");
}
}
public void close()
{
sanityCheck();
isClosed = true;
destroyTun(tunFD);
}
public void receive(ref byte[] buffer)
{
sanityCheck();
/* TODO: Get amount read */
/* FIXME: For now set it length to 20 */
buffer.length = 400;
tunRead(tunFD, cast(char*)buffer.ptr);
}
public void send(byte[] buffer)
{
sanityCheck();
2021-07-18 18:45:17 +01:00
tunWrite(tunFD, cast(char*)buffer.ptr, cast(int)buffer.length);
}
}
public final class TUNException : Exception
{
this(string msg)
{
super(msg);
}
}
public enum AdapterType
{
TUN,
TAP
}