Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC6062: Implement client side for TCP allocations #311

Merged
merged 17 commits into from
May 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Aaron France <[email protected]>
Aleksandr Razumov <[email protected]>
anastasia <[email protected]>
andrefsp <[email protected]>
Andy Yan <[email protected]>
Antonio Sorrentino <[email protected]>
Artem Yarovenko <[email protected]>
Atsushi Watanabe <[email protected]>
Expand Down
188 changes: 154 additions & 34 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (

"github.com/pion/logging"
"github.com/pion/stun"
"github.com/pion/transport/v2"
"github.com/pion/transport/v2/stdnet"
"github.com/pion/turn/v2/internal/client"
"github.com/pion/turn/v2/internal/proto"
)
Expand Down Expand Up @@ -43,12 +45,14 @@ type ClientConfig struct {
Software string
RTO time.Duration
Conn net.PacketConn // Listening socket (net.PacketConn)
Net transport.Net
LoggerFactory logging.LoggerFactory
}

// Client is a STUN server client
type Client struct {
conn net.PacketConn // Read-only
net transport.Net // Read-only
stunServerAddr net.Addr // Read-only
turnServerAddr net.Addr // Read-only

Expand All @@ -60,11 +64,12 @@ type Client struct {
trMap *client.TransactionMap // Thread-safe
rto time.Duration // Read-only
relayedConn *client.UDPConn // Protected by mutex ***
tcpAllocation *client.TCPAllocation // Protected by mutex ***
allocTryLock client.TryLock // Thread-safe
listenTryLock client.TryLock // Thread-safe
mutex sync.RWMutex // Thread-safe
mutexTrMap sync.Mutex // Thread-safe
log logging.LeveledLogger // Tead-only
log logging.LeveledLogger // Read-only
}

// NewClient returns a new Client instance. listeningAddress is the address and port to listen on, default "0.0.0.0:0"
Expand All @@ -85,6 +90,14 @@ func NewClient(config *ClientConfig) (*Client, error) {
rto = config.RTO
}

if config.Net == nil {
n, err := stdnet.NewNet()
if err != nil {
return nil, err
}
config.Net = n
}

c := &Client{
conn: config.Conn,
stunServerAddr: config.STUNServerAddr,
Expand All @@ -94,6 +107,7 @@ func NewClient(config *ClientConfig) (*Client, error) {
realm: stun.NewRealm(config.Realm),
software: stun.NewSoftware(config.Software),
trMap: client.NewTransactionMap(),
net: config.Net,
rto: rto,
log: log,
}
Expand Down Expand Up @@ -201,42 +215,34 @@ func (c *Client) SendBindingRequest() (net.Addr, error) {
return c.SendBindingRequestTo(c.stunServerAddr)
}

// Allocate sends a TURN allocation request to the given transport address
func (c *Client) Allocate() (net.PacketConn, error) {
if err := c.allocTryLock.Lock(); err != nil {
return nil, fmt.Errorf("%w: %s", errOneAllocateOnly, err.Error())
}
defer c.allocTryLock.Unlock()

relayedConn := c.relayedUDPConn()
if relayedConn != nil {
return nil, fmt.Errorf("%w: %s", errAlreadyAllocated, relayedConn.LocalAddr().String())
}
func (c *Client) sendAllocateRequest(protocol proto.Protocol) (proto.RelayedAddress, proto.Lifetime, stun.Nonce, error) {
var relayed proto.RelayedAddress
var lifetime proto.Lifetime
var nonce stun.Nonce

msg, err := stun.Build(
stun.TransactionID,
stun.NewType(stun.MethodAllocate, stun.ClassRequest),
proto.RequestedTransport{Protocol: proto.ProtoUDP},
proto.RequestedTransport{Protocol: protocol},
stun.Fingerprint,
)
if err != nil {
return nil, err
return relayed, lifetime, nonce, err
}

trRes, err := c.PerformTransaction(msg, c.turnServerAddr, false)
if err != nil {
return nil, err
return relayed, lifetime, nonce, err
}

res := trRes.Msg

// Anonymous allocate failed, trying to authenticate.
var nonce stun.Nonce
if err = nonce.GetFrom(res); err != nil {
return nil, err
return relayed, lifetime, nonce, err
}
if err = c.realm.GetFrom(res); err != nil {
return nil, err
return relayed, lifetime, nonce, err
}
c.realm = append([]byte(nil), c.realm...)
c.integrity = stun.NewLongTermIntegrity(
Expand All @@ -246,65 +252,137 @@ func (c *Client) Allocate() (net.PacketConn, error) {
msg, err = stun.Build(
stun.TransactionID,
stun.NewType(stun.MethodAllocate, stun.ClassRequest),
proto.RequestedTransport{Protocol: proto.ProtoUDP},
proto.RequestedTransport{Protocol: protocol},
&c.username,
&c.realm,
&nonce,
&c.integrity,
stun.Fingerprint,
)
if err != nil {
return nil, err
return relayed, lifetime, nonce, err
}

trRes, err = c.PerformTransaction(msg, c.turnServerAddr, false)
if err != nil {
return nil, err
return relayed, lifetime, nonce, err
}
res = trRes.Msg

if res.Type.Class == stun.ClassErrorResponse {
var code stun.ErrorCodeAttribute
if err = code.GetFrom(res); err == nil {
return nil, fmt.Errorf("%s (error %s)", res.Type, code) //nolint:goerr113
return relayed, lifetime, nonce, fmt.Errorf("%s (error %s)", res.Type, code) //nolint:goerr113
}
return nil, fmt.Errorf("%s", res.Type) //nolint:goerr113
return relayed, lifetime, nonce, fmt.Errorf("%s", res.Type) //nolint:goerr113
}

// Getting relayed addresses from response.
var relayed proto.RelayedAddress
if err := relayed.GetFrom(res); err != nil {
return relayed, lifetime, nonce, err
}

// Getting lifetime from response
if err := lifetime.GetFrom(res); err != nil {
return relayed, lifetime, nonce, err
}
return relayed, lifetime, nonce, nil
}

// Allocate sends a TURN allocation request to the given transport address
func (c *Client) Allocate() (net.PacketConn, error) {
if err := c.allocTryLock.Lock(); err != nil {
return nil, fmt.Errorf("%w: %s", errOneAllocateOnly, err.Error())
}
defer c.allocTryLock.Unlock()

relayedConn := c.relayedUDPConn()
if relayedConn != nil {
return nil, fmt.Errorf("%w: %s", errAlreadyAllocated, relayedConn.LocalAddr().String())
}

relayed, lifetime, nonce, err := c.sendAllocateRequest(proto.ProtoUDP)
if err != nil {
return nil, err
}

relayedAddr := &net.UDPAddr{
IP: relayed.IP,
Port: relayed.Port,
}

// Getting lifetime from response
var lifetime proto.Lifetime
if err := lifetime.GetFrom(res); err != nil {
relayedConn = client.NewUDPConn(&client.AllocationConfig{
Client: c,
RelayedAddr: relayedAddr,
ServerAddr: c.turnServerAddr,
Realm: c.realm,
Username: c.username,
Integrity: c.integrity,
Nonce: nonce,
Lifetime: lifetime.Duration,
Net: c.net,
Log: c.log,
})
c.setRelayedUDPConn(relayedConn)

return relayedConn, nil
}

// AllocateTCP creates a new TCP allocation at the TURN server.
func (c *Client) AllocateTCP() (*client.TCPAllocation, error) {
if err := c.allocTryLock.Lock(); err != nil {
return nil, fmt.Errorf("%w: %s", errOneAllocateOnly, err.Error())
}
defer c.allocTryLock.Unlock()

allocation := c.getTCPAllocation()
if allocation != nil {
return nil, fmt.Errorf("%w: %s", errAlreadyAllocated, allocation.Addr())
}

relayed, lifetime, nonce, err := c.sendAllocateRequest(proto.ProtoTCP)
if err != nil {
return nil, err
}

relayedConn = client.NewUDPConn(&client.UDPConnConfig{
Observer: c,
relayedAddr := &net.TCPAddr{
IP: relayed.IP,
Port: relayed.Port,
}

allocation = client.NewTCPAllocation(&client.AllocationConfig{
Client: c,
RelayedAddr: relayedAddr,
ServerAddr: c.turnServerAddr,
Realm: c.realm,
Username: c.username,
Integrity: c.integrity,
Nonce: nonce,
Lifetime: lifetime.Duration,
Net: c.net,
Log: c.log,
})

c.setRelayedUDPConn(relayedConn)
c.setTCPAllocation(allocation)

return relayedConn, nil
return allocation, nil
}

// CreatePermission Issues a CreatePermission request for the supplied addresses
// as described in https://datatracker.ietf.org/doc/html/rfc5766#section-9
func (c *Client) CreatePermission(addrs ...net.Addr) error {
return c.relayedUDPConn().CreatePermissions(addrs...)
if conn := c.relayedUDPConn(); conn != nil {
if err := conn.CreatePermissions(addrs...); err != nil {
return err
}
}

if allocation := c.getTCPAllocation(); allocation != nil {
if err := allocation.CreatePermissions(addrs...); err != nil {
return err
}
}
return nil
}

// PerformTransaction performs STUN transaction
Expand Down Expand Up @@ -350,6 +428,7 @@ func (c *Client) PerformTransaction(msg *stun.Message, to net.Addr, ignoreResult
// (Called by UDPConn)
func (c *Client) OnDeallocated(net.Addr) {
c.setRelayedUDPConn(nil)
c.setTCPAllocation(nil)
}

// HandleInbound handles data received.
Expand Down Expand Up @@ -408,7 +487,8 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
}

if msg.Type.Class == stun.ClassIndication {
if msg.Type.Method == stun.MethodData {
switch msg.Type.Method {
case stun.MethodData:
var peerAddr proto.PeerAddress
if err := peerAddr.GetFrom(msg); err != nil {
return err
Expand All @@ -430,8 +510,34 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
c.log.Debug("no relayed conn allocated")
return nil // Silently discard
}

relayedConn.HandleInbound(data, from)
case stun.MethodConnectionAttempt:
var peerAddr proto.PeerAddress
if err := peerAddr.GetFrom(msg); err != nil {
return err
}

addr := &net.TCPAddr{
IP: peerAddr.IP,
Port: peerAddr.Port,
}

var cid proto.ConnectionID
if err := cid.GetFrom(msg); err != nil {
return err
}

c.log.Debugf("connection attempt from %s", addr.String())

allocation := c.getTCPAllocation()
if allocation == nil {
c.log.Debug("no TCP allocation exists")
return nil // Silently discard
}

allocation.HandleConnectionAttempt(addr, cid)
default:
c.log.Debug("received unsupported STUN method")
}
return nil
}
Expand Down Expand Up @@ -542,3 +648,17 @@ func (c *Client) relayedUDPConn() *client.UDPConn {

return c.relayedConn
}

func (c *Client) setTCPAllocation(alloc *client.TCPAllocation) {
c.mutex.Lock()
defer c.mutex.Unlock()

c.tcpAllocation = alloc
}

func (c *Client) getTCPAllocation() *client.TCPAllocation {
c.mutex.RLock()
defer c.mutex.RUnlock()

return c.tcpAllocation
}
Loading