nebula/udp/udp_generic.go

87 lines
1.9 KiB
Go
Raw Normal View History

2021-10-21 16:24:11 -05:00
//go:build (!linux || android) && !e2e_testing
// +build !linux android
2021-03-26 09:46:30 -05:00
// +build !e2e_testing
2019-11-19 17:00:20 +00:00
// udp_generic implements the nebula UDP interface in pure Go stdlib. This
// means it can be used on platforms like Darwin and Windows.
package udp
2019-11-19 17:00:20 +00:00
import (
"context"
"fmt"
"net"
"net/netip"
2021-03-26 09:46:30 -05:00
"github.com/sirupsen/logrus"
"github.com/slackhq/nebula/config"
2019-11-19 17:00:20 +00:00
)
2023-06-14 10:48:52 -05:00
type GenericConn struct {
2019-11-19 17:00:20 +00:00
*net.UDPConn
2021-03-26 09:46:30 -05:00
l *logrus.Logger
2019-11-19 17:00:20 +00:00
}
var _ Conn = &GenericConn{}
func NewGenericListener(l *logrus.Logger, ip netip.Addr, port int, multi bool, batch int) (Conn, error) {
2019-11-19 17:00:20 +00:00
lc := NewListenConfig(multi)
pc, err := lc.ListenPacket(context.TODO(), "udp", net.JoinHostPort(ip.String(), fmt.Sprintf("%v", port)))
2019-11-19 17:00:20 +00:00
if err != nil {
return nil, err
}
if uc, ok := pc.(*net.UDPConn); ok {
2023-06-14 10:48:52 -05:00
return &GenericConn{UDPConn: uc, l: l}, nil
2019-11-19 17:00:20 +00:00
}
return nil, fmt.Errorf("Unexpected PacketConn: %T %#v", pc, pc)
}
func (u *GenericConn) WriteTo(b []byte, addr netip.AddrPort) error {
_, err := u.UDPConn.WriteToUDPAddrPort(b, addr)
2019-11-19 17:00:20 +00:00
return err
}
func (u *GenericConn) LocalAddr() (netip.AddrPort, error) {
2023-06-14 10:48:52 -05:00
a := u.UDPConn.LocalAddr()
2019-11-19 17:00:20 +00:00
switch v := a.(type) {
case *net.UDPAddr:
addr, ok := netip.AddrFromSlice(v.IP)
if !ok {
return netip.AddrPort{}, fmt.Errorf("LocalAddr returned invalid IP address: %s", v.IP)
}
return netip.AddrPortFrom(addr, uint16(v.Port)), nil
2021-03-18 20:37:24 -05:00
2019-11-19 17:00:20 +00:00
default:
return netip.AddrPort{}, fmt.Errorf("LocalAddr returned: %#v", a)
2019-11-19 17:00:20 +00:00
}
}
2023-06-14 10:48:52 -05:00
func (u *GenericConn) ReloadConfig(c *config.C) {
2019-11-19 17:00:20 +00:00
}
2023-06-14 10:48:52 -05:00
func NewUDPStatsEmitter(udpConns []Conn) func() {
// No UDP stats for non-linux
return func() {}
}
2019-11-19 17:00:20 +00:00
type rawMessage struct {
Len uint32
}
func (u *GenericConn) ListenOut(r EncReader) {
buffer := make([]byte, MTU)
2019-11-19 17:00:20 +00:00
for {
// Just read one packet at a time
n, rua, err := u.ReadFromUDPAddrPort(buffer)
2019-11-19 17:00:20 +00:00
if err != nil {
u.l.WithError(err).Debug("udp socket is closed, exiting read loop")
return
2019-11-19 17:00:20 +00:00
}
r(netip.AddrPortFrom(rua.Addr().Unmap(), rua.Port()), buffer[:n])
2019-11-19 17:00:20 +00:00
}
}