From 1eb37178c117b393823f97266800ced66729c9df Mon Sep 17 00:00:00 2001 From: "Tristan B. Kildaire" Date: Sun, 18 Jul 2021 23:10:11 +0200 Subject: [PATCH] Added method to close tun device Throw error when trying to operate on closed tun device --- source/app.d | 3 +++ source/libtun/adapter.d | 37 ++++++++++++++++++++++++++++++++++--- source/libtun/tunctl.c | 11 +++++++++++ 3 files changed, 48 insertions(+), 3 deletions(-) diff --git a/source/app.d b/source/app.d index aed9cd6..d2d7a6e 100644 --- a/source/app.d +++ b/source/app.d @@ -11,6 +11,9 @@ void main() while(true) { adapter.send([1,1,2,2,2,2]); + byte[] buffer; + adapter.receive(buffer); + writeln(buffer); Thread.sleep(dur!("msecs")(500)); } diff --git a/source/libtun/adapter.d b/source/libtun/adapter.d index 7347294..e1a2107 100644 --- a/source/libtun/adapter.d +++ b/source/libtun/adapter.d @@ -7,18 +7,20 @@ import core.stdc.stdio; /** -* TUN maintenance routines in `test.c` +* TUN maintenance routines in `tunctl.c` */ extern (C) int createTun(char* interfaceName, int iffFlags); extern (C) int destroyTun(int fd); extern (C) int tunWrite(int fd, char* data, int length); +extern (C) int tunRead(int fd, char* data); public class TUNAdapter { /* Tunnel device descriptor */ private int tunFD; + private bool isClosed; - this(string interfaceName) + this(string interfaceName, AdapterType adapterType = AdapterType.TAP) { init(interfaceName); } @@ -32,13 +34,36 @@ public class TUNAdapter } } - public void receive(byte[] buffer) + 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(); + tunWrite(tunFD, cast(char*)buffer.ptr, cast(int)buffer.length); } } @@ -49,4 +74,10 @@ public final class TUNException : Exception { super(msg); } +} + +public enum AdapterType +{ + TUN, + TAP } \ No newline at end of file diff --git a/source/libtun/tunctl.c b/source/libtun/tunctl.c index 68fad00..06863c1 100644 --- a/source/libtun/tunctl.c +++ b/source/libtun/tunctl.c @@ -54,3 +54,14 @@ int tunWrite(int fd, char* data, int length) { write(fd, data, length); } + +/** +* TODO: Depending on mode we need to read a certain amount +* to get the length and then from there move onwards +* +* (FIXME: For now we just read 20 bytes) +*/ +int tunRead(int fd, char* data) +{ + read(fd, data, 400); +}