netmaker/stun-server/stun-server.go

164 lines
3.6 KiB
Go
Raw Normal View History

2022-10-26 13:20:09 +08:00
package stunserver
import (
2022-11-07 23:55:58 +08:00
"context"
2022-10-26 13:20:09 +08:00
"fmt"
"log"
"net"
2022-11-07 23:55:58 +08:00
"os"
"os/signal"
2022-10-26 13:20:09 +08:00
"strings"
2022-11-07 23:55:58 +08:00
"sync"
"syscall"
2022-10-26 13:20:09 +08:00
"github.com/gravitl/netmaker/logger"
"github.com/gravitl/netmaker/servercfg"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"gortc.io/stun"
)
// Server is RFC 5389 basic server implementation.
//
// Current implementation is UDP only and not utilizes FINGERPRINT mechanism,
// nor ALTERNATE-SERVER, nor credentials mechanisms. It does not support
// backwards compatibility with RFC 3489.
type Server struct {
2022-11-07 23:55:58 +08:00
Addr string
Ctx context.Context
2022-10-26 13:20:09 +08:00
}
// Logger is used for logging formatted messages.
type Logger interface {
// Printf must have the same semantics as log.Printf.
Printf(format string, args ...interface{})
}
var (
defaultLogger = logrus.New()
software = stun.NewSoftware("netmaker-stun")
errNotSTUNMessage = errors.New("not stun message")
)
func basicProcess(addr net.Addr, b []byte, req, res *stun.Message) error {
if !stun.IsMessage(b) {
return errNotSTUNMessage
}
if _, err := req.Write(b); err != nil {
return errors.Wrap(err, "failed to read message")
}
var (
ip net.IP
port int
)
switch a := addr.(type) {
case *net.UDPAddr:
ip = a.IP
port = a.Port
default:
panic(fmt.Sprintf("unknown addr: %v", addr))
}
return res.Build(req,
stun.BindingSuccess,
software,
&stun.XORMappedAddress{
IP: ip,
Port: port,
},
stun.Fingerprint,
)
}
func (s *Server) serveConn(c net.PacketConn, res, req *stun.Message) error {
if c == nil {
return nil
}
buf := make([]byte, 1024)
n, addr, err := c.ReadFrom(buf)
if err != nil {
2022-11-07 23:55:58 +08:00
logger.Log(1, "ReadFrom: %v", err.Error())
2022-10-26 13:20:09 +08:00
return nil
}
log.Printf("read %d bytes from %s\n", n, addr)
if _, err = req.Write(buf[:n]); err != nil {
2022-11-07 23:55:58 +08:00
logger.Log(1, "Write: %v", err.Error())
2022-10-26 13:20:09 +08:00
return err
}
if err = basicProcess(addr, buf[:n], req, res); err != nil {
if err == errNotSTUNMessage {
return nil
}
2022-11-07 23:55:58 +08:00
logger.Log(1, "basicProcess: %v", err.Error())
2022-10-26 13:20:09 +08:00
return nil
}
_, err = c.WriteTo(res.Raw, addr)
if err != nil {
2022-11-07 23:55:58 +08:00
logger.Log(1, "WriteTo: %v", err.Error())
2022-10-26 13:20:09 +08:00
}
return err
}
// Serve reads packets from connections and responds to BINDING requests.
2022-11-07 23:55:58 +08:00
func (s *Server) serve(c net.PacketConn) error {
2022-10-26 13:20:09 +08:00
var (
res = new(stun.Message)
req = new(stun.Message)
)
for {
2022-11-07 23:55:58 +08:00
select {
case <-s.Ctx.Done():
logger.Log(0, "Shutting down stun server...")
c.Close()
return nil
default:
if err := s.serveConn(c, res, req); err != nil {
logger.Log(1, "serve: %v", err.Error())
continue
}
res.Reset()
req.Reset()
2022-10-26 13:20:09 +08:00
}
}
}
2022-11-07 23:55:58 +08:00
// listenUDPAndServe listens on laddr and process incoming packets.
func listenUDPAndServe(ctx context.Context, serverNet, laddr string) error {
2022-10-26 13:20:09 +08:00
c, err := net.ListenPacket(serverNet, laddr)
if err != nil {
return err
}
s := &Server{
2022-11-07 23:55:58 +08:00
Addr: laddr,
Ctx: ctx,
2022-10-26 13:20:09 +08:00
}
2022-11-07 23:55:58 +08:00
return s.serve(c)
2022-10-26 13:20:09 +08:00
}
func normalize(address string) string {
if len(address) == 0 {
address = "0.0.0.0"
}
if !strings.Contains(address, ":") {
address = fmt.Sprintf("%s:%d", address, stun.DefaultPort)
}
return address
}
// Start - starts the stun server
2022-11-07 23:55:58 +08:00
func Start(wg *sync.WaitGroup) {
ctx, cancel := context.WithCancel(context.Background())
go func(wg *sync.WaitGroup) {
defer wg.Done()
2022-11-07 23:55:58 +08:00
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGTERM, os.Interrupt)
<-quit
cancel()
}(wg)
normalized := normalize(fmt.Sprintf("0.0.0.0:%d", servercfg.GetStunPort()))
2022-10-26 13:20:09 +08:00
logger.Log(0, "netmaker-stun listening on", normalized, "via udp")
2022-11-07 23:55:58 +08:00
err := listenUDPAndServe(ctx, "udp", normalized)
2022-10-26 13:20:09 +08:00
if err != nil {
logger.Log(0, "failed to start stun server: ", err.Error())
}
}