slimming/device.go

287 lines
5.7 KiB
Go
Raw Normal View History

2022-08-26 02:23:06 +00:00
package main
import (
"bytes"
"context"
"encoding/binary"
"encoding/gob"
"fmt"
"log"
2022-08-29 01:37:00 +00:00
"net"
2022-08-26 02:23:06 +00:00
"os/exec"
gen "slimming/proto/gen"
"strings"
2022-08-29 02:10:45 +00:00
"sync"
2022-08-26 02:23:06 +00:00
"sync/atomic"
"time"
"github.com/songgao/packets/ethernet"
"github.com/songgao/water"
"github.com/songgao/water/waterutil"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type ExchangeBuffer struct {
BytesArray [][]byte
}
type NetCard struct {
FrameChan chan []byte
ifce *water.Interface
server *RPCServer
clientMap map[string]*RPCClient
2022-08-29 02:10:45 +00:00
lock sync.Mutex
}
func (nc *NetCard) Lock(do func()) {
nc.lock.Lock()
defer nc.lock.Unlock()
do()
2022-08-26 02:23:06 +00:00
}
type RPCClient struct {
FrameChan chan *ExchangeBuffer
conn *grpc.ClientConn
}
func (cli *RPCClient) connect(realAddr string) {
log.Println("rpcclient connect", realAddr)
// defer log.Println("rpcclient exit")
conn, err := grpc.Dial(realAddr,
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
if err != nil {
log.Printf("did not connect: %v", err)
return
}
cli.conn = conn
go cli.run()
time.Sleep(time.Millisecond)
}
func (cli *RPCClient) run() {
defer log.Println("rpcclient exit")
defer func() {
if err := recover(); err != nil {
log.Println("recover")
cli.conn = nil
}
}()
c := gen.NewFrameServiceClient(cli.conn)
stream, err := c.SendFrames(context.Background())
if err != nil {
log.Panic(err)
}
buf := bytes.NewBuffer(nil)
for {
// Contact the server and print out its response.
buf.Reset()
2022-08-26 02:29:37 +00:00
// encode gob
enc := gob.NewEncoder(buf)
cliBuffer := <-cli.FrameChan
2022-08-29 02:50:05 +00:00
2022-08-29 02:55:44 +00:00
log.Printf("send to target %s source bytes: %d", waterutil.IPv4Destination(cliBuffer.BytesArray[0]), len(cliBuffer.BytesArray[0]))
2022-08-26 02:53:35 +00:00
err := enc.Encode(cliBuffer.BytesArray)
if err != nil {
log.Panic(err)
}
2022-08-26 02:29:37 +00:00
// zstd compress
2022-08-26 02:54:43 +00:00
// zenc, err := zstd.NewWriter(buf)
// if err != nil {
// log.Panic(err)
// }
// err = zenc.Flush()
// if err != nil {
// log.Println(err)
// }
2022-08-26 02:23:06 +00:00
// 发到对面的网卡
err = stream.Send(&gen.Request{
Frames: buf.Bytes(),
})
if err != nil {
log.Panic(err)
}
}
}
func (nc *NetCard) Run() {
go nc.runRead()
go nc.runWrite()
// go nc.cli.run()
time.Sleep(time.Second)
cmdstr := fmt.Sprintf("ip addr add %s dev stun", config.Network.Self.Virt)
log.Println(cmdstr)
cmd := strings.Split(cmdstr, " ")
err := exec.Command(cmd[0], cmd[1:]...).Run()
if err != nil {
log.Panic(err)
}
cmdstr = "ip link set dev stun up"
cmd = strings.Split(cmdstr, " ")
err = exec.Command(cmd[0], cmd[1:]...).Run()
if err != nil {
log.Panic(err)
}
nc.server.run()
}
func NewNetCard() *NetCard {
config := water.Config{
2022-08-29 01:37:00 +00:00
DeviceType: water.TUN,
2022-08-29 01:11:46 +00:00
PlatformSpecificParams: water.PlatformSpecificParams{
Name: "stun",
},
2022-08-26 02:23:06 +00:00
}
ifce, err := water.New(config)
if err != nil {
log.Panic(err)
}
nc := &NetCard{
FrameChan: make(chan []byte, 3000),
ifce: ifce,
clientMap: map[string]*RPCClient{},
}
nc.server = newRPCServer(nc)
return nc
}
func (nc *NetCard) runRead() {
log.Println("start netcard read")
var ifce *water.Interface = nc.ifce
for {
var bytesMap map[string]*ExchangeBuffer = make(map[string]*ExchangeBuffer)
var ok bool
var isLoop int32 = 1
// 20 微秒后停止收集数据
go func() {
var after = time.NewTimer(time.Millisecond * 20)
<-after.C
atomic.StoreInt32(&isLoop, 0)
}()
for atomic.LoadInt32(&isLoop) > 0 {
var rframe ethernet.Frame
rframe.Resize(1500)
2022-08-29 02:45:38 +00:00
n, err := ifce.Read([]byte(rframe))
if err != nil {
log.Fatal(err)
}
rframe = rframe[:n]
2022-08-29 02:10:45 +00:00
2022-08-29 02:32:55 +00:00
if !waterutil.IsIPv4(rframe) || waterutil.IPv4Source(rframe).Equal(net.IPv4(0, 0, 0, 0)) {
2022-08-26 02:23:06 +00:00
continue
}
var realAddr string = ""
config.Lock(func() {
if realAddr, ok = config.IPv4Nodes[binary.LittleEndian.Uint32([]byte(waterutil.IPv4Destination(rframe)))]; !ok {
return
}
})
2022-08-29 03:00:37 +00:00
2022-08-26 02:23:06 +00:00
if realAddr == "" {
2022-08-29 02:45:38 +00:00
log.Printf("%s is not exists", waterutil.IPv4Destination(rframe))
2022-08-26 02:23:06 +00:00
continue
}
// log.Printf("Payload: % x\n", rframe.Payload())
2022-08-29 03:00:37 +00:00
log.Printf("Ethertype: % x %v realAddr %s\n", rframe.Ethertype(), waterutil.IsIPv4(rframe), realAddr)
2022-08-29 01:37:00 +00:00
log.Printf("Dst: %s Src %s\n", waterutil.IPv4Destination(rframe), waterutil.IPv4Source(rframe))
2022-08-26 02:23:06 +00:00
var buffer *ExchangeBuffer
if buffer, ok = bytesMap[realAddr]; !ok {
buffer = &ExchangeBuffer{BytesArray: make([][]byte, 0, 1000)}
bytesMap[realAddr] = buffer
}
buffer.BytesArray = append(buffer.BytesArray, []byte(rframe))
}
2022-08-29 03:13:48 +00:00
continue
2022-08-26 02:23:06 +00:00
for dst, buffer := range bytesMap {
var cli *RPCClient
if cli, ok = nc.clientMap[dst]; !ok {
cli = &RPCClient{FrameChan: make(chan *ExchangeBuffer)}
nc.clientMap[dst] = cli
}
if cli.conn == nil {
cli.connect(dst)
} else {
cli.FrameChan <- buffer // 网卡数据 发到对方
}
}
// 写到grpc服务
// log.Printf("Dst: %s\n", rframe.Destination()[0:4])
// log.Printf("Src: %s\n", rframe.Source()[0:4])
// log.Printf("Ethertype: % x\n", rframe.Ethertype())
// log.Printf("Payload: % x\n", rframe.Payload())
}
}
func (nc *NetCard) runWrite() {
var ifce *water.Interface = nc.ifce
2022-08-26 02:54:43 +00:00
var err error
2022-08-26 03:00:18 +00:00
2022-08-26 02:23:06 +00:00
for wframe := range nc.FrameChan {
log.Printf("get wframes bytes len: %d", len(wframe))
2022-08-26 03:00:18 +00:00
var buf = bytes.NewBuffer(wframe)
2022-08-26 02:23:06 +00:00
2022-08-26 02:54:43 +00:00
// zdec, err := zstd.NewReader(buf)
// if err != nil {
// log.Panic(err)
// }
// zdec.Close()
2022-08-26 02:23:06 +00:00
2022-08-26 02:29:37 +00:00
dec := gob.NewDecoder(buf)
2022-08-26 02:23:06 +00:00
var bufs [][]byte
err = dec.Decode(&bufs)
if err != nil {
log.Panic(err)
}
2022-08-29 02:45:38 +00:00
for _, buf := range bufs {
2022-08-29 02:55:44 +00:00
log.Printf("get wframes decode len: %d", len(buf))
log.Printf("get decode frames decode source: %s dst: %s", waterutil.IPv4Source(buf), waterutil.IPv4Destination(buf))
2022-08-29 02:45:38 +00:00
_, err := ifce.Write(buf)
if err != nil {
log.Panic(err)
2022-08-26 02:23:06 +00:00
}
2022-08-29 02:45:38 +00:00
}
2022-08-29 02:10:45 +00:00
2022-08-26 02:23:06 +00:00
}
}