q3rcon-proxy/pkg/udpproxy/udpproxy.go

94 lines
1.8 KiB
Go
Raw Normal View History

2023-01-08 09:26:04 +00:00
package udpproxy
import (
"net"
"sync"
"time"
2024-03-08 02:29:40 +00:00
log "github.com/sirupsen/logrus"
2023-01-08 09:26:04 +00:00
)
type Client struct {
laddr *net.UDPAddr
raddr *net.UDPAddr
proxyConn *net.UDPConn
mutex sync.RWMutex
sessions map[string]*Session
}
func New(port, target string) (*Client, error) {
laddr, err := net.ResolveUDPAddr("udp", port)
if err != nil {
return nil, err
}
raddr, err := net.ResolveUDPAddr("udp", target)
if err != nil {
return nil, err
}
return &Client{
laddr: laddr,
raddr: raddr,
mutex: sync.RWMutex{},
sessions: map[string]*Session{},
}, nil
}
func (c *Client) isValidPacket(header []byte) bool {
return string(header[:8]) == "\xff\xff\xff\xffrcon" || string(header[:13]) == "\xff\xff\xff\xffgetstatus" || string(header[:11]) == "\xff\xff\xff\xffgetinfo"
}
2023-01-08 09:26:04 +00:00
func (c *Client) ListenAndServe() error {
var err error
c.proxyConn, err = net.ListenUDP("udp", c.laddr)
if err != nil {
return err
}
go c.pruneSessions()
for {
buf := make([]byte, 2048)
2023-01-08 10:59:43 +00:00
n, caddr, err := c.proxyConn.ReadFromUDP(buf)
2023-01-08 09:26:04 +00:00
if err != nil {
log.Println(err)
}
if !c.isValidPacket(buf[:16]) {
continue
}
2023-01-08 09:26:04 +00:00
session, found := c.sessions[caddr.String()]
if !found {
session, err = createSession(caddr, c.raddr, c.proxyConn)
if err != nil {
log.Println(err)
continue
}
c.sessions[caddr.String()] = session
}
2023-01-08 11:04:44 +00:00
go session.proxyTo(buf[:n])
2023-01-08 09:26:04 +00:00
}
}
func (c *Client) pruneSessions() {
ticker := time.NewTicker(1 * time.Minute)
// the locks here could be abusive and i dont even know if this is a real
// problem but we definitely need to clean up stale sessions
for range ticker.C {
for _, session := range c.sessions {
c.mutex.RLock()
if time.Since(session.updateTime) > time.Minute*5 {
delete(c.sessions, session.caddr.String())
}
c.mutex.RUnlock()
}
}
}