package relay import ( "context" "github.com/pion/stun/v3" "net" "time" ) // ServeSTUN handles binding only; no TURN allocations or arbitrary destinations. // A fixed global budget bounds work and reflection traffic without a per-IP map. func ServeSTUN(ctx context.Context, conn *net.UDPConn) error { go func() { <-ctx.Done(); conn.Close() }() buffer := make([]byte, 1500) budget, reset := 100, time.Now() for { size, address, err := conn.ReadFromUDP(buffer) if err != nil { if ctx.Err() != nil { return nil } return err } if time.Since(reset) >= time.Second { budget = 100 reset = time.Now() } if budget == 0 || size < 20 || size > 1200 { continue } budget-- message := &stun.Message{Raw: buffer[:size]} if message.Decode() != nil || message.Type != stun.BindingRequest { continue } response, err := stun.Build(stun.NewTransactionIDSetter(message.TransactionID), stun.BindingSuccess, &stun.XORMappedAddress{IP: address.IP, Port: address.Port}) if err == nil { conn.WriteToUDP(response.Raw, address) } } }