dissertation-2-code/tun/tun.go
Jake Hillion 6f72047caf
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
improved sinking
2021-03-31 18:12:20 +01:00

74 lines
1.2 KiB
Go

package tun
import (
wgtun "golang.zx2c4.com/wireguard/tun"
"io"
"log"
"mpbl3p/proxy"
"os"
)
type SourceSink struct {
tun wgtun.Device
mtu int
}
func NewTun(name string, mtu int) (t wgtun.Device, err error) {
return wgtun.CreateTUN(name, mtu)
}
func NewFromFile(fd uintptr, mtu int) (ss *SourceSink, err error) {
ss = new(SourceSink)
file := os.NewFile(fd, "")
ss.tun, err = wgtun.CreateTUNFromFile(file, mtu)
if err != nil {
return
}
ss.mtu = mtu
return
}
func (t *SourceSink) Close() error {
return t.tun.Close()
}
func (t *SourceSink) Source() (proxy.Packet, error) {
buf := make([]byte, t.mtu)
read, err := t.tun.Read(buf, 4)
if err != nil {
return nil, err
}
if read == 0 {
return nil, io.EOF
}
return proxy.SimplePacket(buf[4:read]), nil
}
var good, bad float64
func (t *SourceSink) Sink(packet proxy.Packet) error {
// make space for tun header
content := make([]byte, len(packet.Contents())+4)
copy(content[4:], packet.Contents())
_, err := t.tun.Write(content, 4)
if err != nil {
switch err.(type) {
case *os.PathError:
bad += 1
log.Printf("packet loss: %f%%\n", bad*100/(good+bad))
return nil
default:
return err
}
}
good += 1
return nil
}