dissertation-2-code/tun/tun.go

77 lines
1.2 KiB
Go
Raw Normal View History

2020-10-23 20:07:15 +01:00
package tun
import (
2021-03-26 11:58:03 +00:00
wgtun "golang.zx2c4.com/wireguard/tun"
"io"
"log"
"mpbl3p/proxy"
2020-11-01 18:18:37 +00:00
"os"
)
2020-10-23 20:07:15 +01:00
type SourceSink struct {
2021-03-26 11:58:03 +00:00
tun wgtun.Device
}
2021-03-26 11:58:03 +00:00
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)
2020-10-24 17:44:14 +01:00
2021-03-26 11:58:03 +00:00
file := os.NewFile(fd, "")
ss.tun, err = wgtun.CreateTUNFromFile(file, mtu)
if err != nil {
return
}
return
}
2021-03-26 11:58:03 +00:00
func (t *SourceSink) Close() error {
return t.tun.Close()
}
2020-10-23 20:07:15 +01:00
func (t *SourceSink) Source() (proxy.Packet, error) {
2021-05-11 22:37:39 +01:00
mtu, err := t.tun.MTU()
if err != nil {
return nil, err
}
buf := make([]byte, mtu+4)
2021-03-26 18:13:39 +00:00
read, err := t.tun.Read(buf, 4)
if err != nil {
2020-11-25 19:35:31 +00:00
return nil, err
}
if read == 0 {
2020-11-25 19:35:31 +00:00
return nil, io.EOF
}
2021-05-11 23:26:54 +01:00
return proxy.SimplePacket(buf[4 : read+4]), nil
}
2020-11-01 18:18:37 +00:00
var good, bad float64
2020-10-23 20:07:15 +01:00
func (t *SourceSink) Sink(packet proxy.Packet) error {
2021-03-31 18:12:20 +01:00
// make space for tun header
content := make([]byte, len(packet.Contents())+4)
copy(content[4:], packet.Contents())
_, err := t.tun.Write(content, 4)
2020-11-01 18:18:37 +00:00
if err != nil {
switch err.(type) {
case *os.PathError:
bad += 1
2020-11-03 20:56:51 +00:00
log.Printf("packet loss: %f%%\n", bad*100/(good+bad))
2020-11-01 18:18:37 +00:00
return nil
default:
return err
}
}
good += 1
return nil
}