mirror of
https://github.com/rkonfj/peerguard.git
synced 2024-08-11 11:00:25 +08:00
vpn: add inbound/outbound packet handlers
This commit is contained in:
parent
568da58bae
commit
3a9c580c4a
11
vpn/packet.go
Normal file
11
vpn/packet.go
Normal file
@ -0,0 +1,11 @@
|
||||
package vpn
|
||||
|
||||
type InboundHandler interface {
|
||||
Name() string
|
||||
In([]byte) []byte
|
||||
}
|
||||
|
||||
type OutboundHandler interface {
|
||||
Name() string
|
||||
Out([]byte) []byte
|
||||
}
|
26
vpn/vpn.go
26
vpn/vpn.go
@ -45,6 +45,8 @@ type Config struct {
|
||||
PrivateKey string
|
||||
OnRoute func(route Route)
|
||||
ModifyDiscoConfig func(cfg *disco.DiscoConfig)
|
||||
InboundHandlers []InboundHandler
|
||||
OutboundHandlers []OutboundHandler
|
||||
}
|
||||
|
||||
type VPN struct {
|
||||
@ -265,11 +267,23 @@ func (vpn *VPN) runTunReadEventLoop(wg *sync.WaitGroup, device tun.Device) {
|
||||
|
||||
func (vpn *VPN) runTunWriteEventLoop(wg *sync.WaitGroup, device tun.Device) {
|
||||
defer wg.Done()
|
||||
handle := func(pkt []byte) []byte {
|
||||
for _, in := range vpn.cfg.InboundHandlers {
|
||||
if pkt = in.In(pkt); pkt == nil {
|
||||
slog.Debug("DropInbound", "handler", in.Name())
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return pkt
|
||||
}
|
||||
for {
|
||||
pkt, ok := <-vpn.inbound
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if pkt = handle(pkt); pkt == nil {
|
||||
continue
|
||||
}
|
||||
_, err := device.Write([][]byte{pkt}, IPPacketOffset)
|
||||
if err != nil {
|
||||
slog.Debug("WriteToTunError", "detail", err.Error())
|
||||
@ -310,11 +324,23 @@ func (vpn *VPN) runPacketConnWriteEventLoop(wg *sync.WaitGroup, packetConn net.P
|
||||
}
|
||||
slog.Log(context.Background(), -10, "DropPacketPeerNotFound", "ip", dstIP)
|
||||
}
|
||||
handle := func(pkt []byte) []byte {
|
||||
for _, out := range vpn.cfg.OutboundHandlers {
|
||||
if pkt = out.Out(pkt); pkt == nil {
|
||||
slog.Debug("DropOutbound", "handler", out.Name())
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return pkt
|
||||
}
|
||||
for {
|
||||
packet, ok := <-vpn.outbound
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if packet = handle(packet); packet == nil {
|
||||
continue
|
||||
}
|
||||
pkt := packet[IPPacketOffset:]
|
||||
if pkt[0]>>4 == 4 {
|
||||
header, err := ipv4.ParseHeader(pkt)
|
||||
|
Loading…
Reference in New Issue
Block a user