dissertation-2-code/tun/tun.go

97 lines
1.4 KiB
Go
Raw Normal View History

2020-10-23 20:07:15 +01:00
package tun
import (
"github.com/pkg/taptun"
"io"
"log"
"mpbl3p/proxy"
"net"
2020-11-01 18:18:37 +00:00
"os"
"strings"
"sync"
"time"
)
2020-10-23 20:07:15 +01:00
type SourceSink struct {
tun *taptun.Tun
bufferSize int
up bool
upMu sync.Mutex
}
2020-10-24 17:44:14 +01:00
func NewTun(namingScheme string, bufferSize int) (ss *SourceSink, err error) {
ss = &SourceSink{}
ss.tun, err = taptun.NewTun(namingScheme)
if err != nil {
return
}
ss.bufferSize = bufferSize
ss.upMu.Lock()
go func() {
defer ss.upMu.Unlock()
for {
iface, err := net.InterfaceByName(ss.tun.String())
if err != nil {
panic(err)
}
if strings.Contains(iface.Flags.String(), "up") {
log.Println("tun is up")
ss.up = true
return
}
time.Sleep(100 * time.Millisecond)
}
}()
return
}
2020-10-23 20:07:15 +01:00
func (t *SourceSink) Source() (proxy.Packet, error) {
if !t.up {
t.upMu.Lock()
t.upMu.Unlock()
}
buf := make([]byte, t.bufferSize)
read, err := t.tun.Read(buf)
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
}
2020-11-28 17:15:56 +00:00
return proxy.SimplePacket(buf[:read]), 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 {
if !t.up {
t.upMu.Lock()
t.upMu.Unlock()
}
2020-11-26 22:39:07 +00:00
_, err := t.tun.Write(packet.Contents())
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
}