TURN module (rfc5766)

Client

TURN client that manages relay allocations, permissions, and data relay via RFC 5766.

Client

#include <icy/turn/client/client.h>

Inherits: Stateful< ClientState >, IAllocation Subclassed by: TCPClient, UDPClient

TURN client that manages relay allocations, permissions, and data relay via RFC 5766.

Public Methods

ReturnNameDescription
Client#### Parameters
voidstart virtualConnects the socket to the TURN server and starts the allocation sequence. Permissions must be added via addPermission() before calling this.
voidstop virtualStops the timer, cancels pending transactions, and closes the socket.
voidsendAllocate virtualSends an Allocate request to the server with the configured transport and lifetime. On first call the server will typically respond with a 401 challenge; the client re-sends with credentials automatically.
voidaddPermission virtualAdds multiple peer IP addresses to the permission list.
voidaddPermission virtualAdds a single peer IP to the permission list, or refreshes it if already present. Permissions should be added before start(); they may also be added later, in which case a new CreatePermission request is required.
voidsendCreatePermission virtualSends a CreatePermission request for all IPs currently in the permission list. Called automatically after allocation succeeds and periodically by the timer to refresh expiring permissions.
voidsendChannelBind virtualChannel bindings (RFC 5766 Section 11) are intentionally not implemented. They are a bandwidth optimization that replaces STUN-framed Send/Data indications with a compact 4-byte ChannelData header. This only benefits high-throughput media relay scenarios; in practice, media flows directly via ICE/DTLS rather than through this TURN client's data path, so the optimization is not worth the complexity (channel number allocation, 10-minute binding refresh timers, ChannelData wire framing). Data relay uses sendData() with Send Indications instead.
voidsendRefresh virtualSends a Refresh request to extend the allocation lifetime. Called automatically by the timer when roughly one-third of the lifetime remains.
voidsendData virtualSends a Send Indication to relay data to peerAddress through the TURN server. If permissions are still being negotiated the indication is queued and flushed once CreatePermission succeeds.
boolhandleResponse virtualDispatches an incoming STUN/TURN response to the appropriate handler.
voidhandleAllocateResponse virtualProcesses a successful Allocate response; extracts mapped/relayed addresses and advances the state to Authorizing, then sends CreatePermission.
voidhandleAllocateErrorResponse virtualHandles an Allocate error response; manages the 401 challenge/re-send flow and sets the client to Failed for unrecoverable errors.
voidhandleCreatePermissionResponse virtualHandles a successful CreatePermission response; flushes queued Send Indications and advances state to Success.
voidhandleCreatePermissionErrorResponse virtualHandles a failed CreatePermission response; clears all permissions and sets the client to Failed.
voidhandleRefreshResponse virtualHandles a Refresh response; updates the stored lifetime.
voidhandleDataIndication virtualHandles an incoming Data Indication; extracts peer address and data and forwards to ClientObserver::onRelayDataReceived().
inttransportProtocol virtual#### Returns
stun::Transaction::PtrcreateTransaction virtualCreates a new STUN transaction, registers the progress callback, and adds it to the active transaction list.
voidauthenticateRequest virtualAdds STUN long-term credential attributes (Username, Realm, Nonce, MessageIntegrity) to request if the realm has been received from the server.
boolsendAuthenticatedTransaction virtualCalls authenticateRequest() then sends the transaction.
stun::Transaction::PtrremoveTransaction virtualRemoves a transaction from the active list. The IntrusivePtr keeps the object alive until the caller's copy is released.
net::AddressmappedAddress const#### Returns
net::AddressrelayedAddress virtual const#### Returns
boolclosed const#### Returns
ClientObserver &observer#### Returns
const Options &options const#### Returns
voidaddPermission virtualAdds a permission for ip, or refreshes the existing one.
voidaddPermission virtualAdds a permission for address, or refreshes the existing one. The port is ignored; TURN permissions are IP-only.
boolhasPermission virtualChecks whether a permission exists for peerIP. Local addresses (192.168.x.x and 127.x.x.x) are always permitted.
boolhasPermission virtualChecks whether a permission exists for peerAddress. The port is ignored; TURN permissions are IP-only.
voidremovePermission virtualRemoves the permission for ip if present.
voidremovePermission virtualRemoves the permission for address if present. The port is ignored; TURN permissions are IP-only.

Client

Client(ClientObserver & observer, const Options & options, const net::Socket::Ptr & socket)

Parameters

  • observer Observer to receive lifecycle and data callbacks.

  • options Configuration for this client instance.

  • socket Underlying transport socket (TCP or UDP).


start

virtual

virtual void start()

Connects the socket to the TURN server and starts the allocation sequence. Permissions must be added via addPermission() before calling this.


stop

virtual

virtual void stop()

Stops the timer, cancels pending transactions, and closes the socket.


sendAllocate

virtual

virtual void sendAllocate()

Sends an Allocate request to the server with the configured transport and lifetime. On first call the server will typically respond with a 401 challenge; the client re-sends with credentials automatically.


addPermission

virtual

virtual void addPermission(const IPList & peerIPs)

Adds multiple peer IP addresses to the permission list.

Parameters

  • peerIPs List of IPv4 address strings to permit.

addPermission

virtual

virtual void addPermission(const std::string & ip)

Adds a single peer IP to the permission list, or refreshes it if already present. Permissions should be added before start(); they may also be added later, in which case a new CreatePermission request is required.

Parameters

  • ip IPv4 address string of the permitted peer.

sendCreatePermission

virtual

virtual void sendCreatePermission()

Sends a CreatePermission request for all IPs currently in the permission list. Called automatically after allocation succeeds and periodically by the timer to refresh expiring permissions.


sendChannelBind

virtual

virtual void sendChannelBind(const std::string & peerIP)

Channel bindings (RFC 5766 Section 11) are intentionally not implemented. They are a bandwidth optimization that replaces STUN-framed Send/Data indications with a compact 4-byte ChannelData header. This only benefits high-throughput media relay scenarios; in practice, media flows directly via ICE/DTLS rather than through this TURN client's data path, so the optimization is not worth the complexity (channel number allocation, 10-minute binding refresh timers, ChannelData wire framing). Data relay uses sendData() with Send Indications instead.

Parameters

  • peerIP Unused; always throws std::logic_error.

sendRefresh

virtual

virtual void sendRefresh()

Sends a Refresh request to extend the allocation lifetime. Called automatically by the timer when roughly one-third of the lifetime remains.


sendData

virtual

virtual void sendData(const char * data, size_t size, const net::Address & peerAddress)

Sends a Send Indication to relay data to peerAddress through the TURN server. If permissions are still being negotiated the indication is queued and flushed once CreatePermission succeeds.

Parameters

  • data Pointer to the payload to relay.

  • size Number of bytes to relay.

  • peerAddress Destination peer address (must have an active permission).


handleResponse

virtual

virtual bool handleResponse(const stun::Message & response)

Dispatches an incoming STUN/TURN response to the appropriate handler.

Parameters

  • response Received STUN message.

Returns

true if the message was handled, false if it was unrecognised.


handleAllocateResponse

virtual

virtual void handleAllocateResponse(const stun::Message & response)

Processes a successful Allocate response; extracts mapped/relayed addresses and advances the state to Authorizing, then sends CreatePermission.

Parameters

  • response Allocate success response from the server.

handleAllocateErrorResponse

virtual

virtual void handleAllocateErrorResponse(const stun::Message & response)

Handles an Allocate error response; manages the 401 challenge/re-send flow and sets the client to Failed for unrecoverable errors.

Parameters

  • response Allocate error response from the server.

handleCreatePermissionResponse

virtual

virtual void handleCreatePermissionResponse(const stun::Message & response)

Handles a successful CreatePermission response; flushes queued Send Indications and advances state to Success.

Parameters

  • response CreatePermission success response from the server.

handleCreatePermissionErrorResponse

virtual

virtual void handleCreatePermissionErrorResponse(const stun::Message & response)

Handles a failed CreatePermission response; clears all permissions and sets the client to Failed.

Parameters

  • response CreatePermission error response from the server.

handleRefreshResponse

virtual

virtual void handleRefreshResponse(const stun::Message & response)

Handles a Refresh response; updates the stored lifetime.

Parameters

  • response Refresh response from the server.

handleDataIndication

virtual

virtual void handleDataIndication(const stun::Message & response)

Handles an incoming Data Indication; extracts peer address and data and forwards to ClientObserver::onRelayDataReceived().

Parameters

  • response Data Indication message from the server.

transportProtocol

virtual

virtual int transportProtocol()

Returns

The IANA protocol number for the underlying transport (kProtocolUDP or kProtocolTCP).


createTransaction

virtual

virtual stun::Transaction::Ptr createTransaction(const net::Socket::Ptr & socket)

Creates a new STUN transaction, registers the progress callback, and adds it to the active transaction list.

Parameters

  • socket Optional override socket; uses the control socket if nullptr.

Returns

IntrusivePtr to the new transaction.


authenticateRequest

virtual

virtual void authenticateRequest(stun::Message & request)

Adds STUN long-term credential attributes (Username, Realm, Nonce, MessageIntegrity) to request if the realm has been received from the server.

Parameters

  • request Message to decorate with authentication attributes.

sendAuthenticatedTransaction

virtual

virtual bool sendAuthenticatedTransaction(stun::Transaction * transaction)

Calls authenticateRequest() then sends the transaction.

Parameters

  • transaction Transaction whose request to authenticate and send.

Returns

true if the send succeeded.


removeTransaction

virtual

virtual stun::Transaction::Ptr removeTransaction(stun::Transaction * transaction)

Removes a transaction from the active list. The IntrusivePtr keeps the object alive until the caller's copy is released.

Parameters

  • transaction Transaction to remove.

Returns

The removed Ptr, or nullptr if not found.


mappedAddress

const

net::Address mappedAddress() const

Returns

The server-reflexive (mapped) address assigned by the TURN server.


relayedAddress

virtual const

virtual net::Address relayedAddress() const

Returns

The relayed transport address assigned by the TURN server.


closed

const

bool closed() const

Returns

true when the client is in the None or Failed state.


observer

ClientObserver & observer()

Returns

Reference to the observer provided at construction.


options

const

const Options & options() const

Returns

Reference to the immutable options struct.


addPermission

virtual

virtual void addPermission(const std::string & ip)

Adds a permission for ip, or refreshes the existing one.

Parameters

  • ip IPv4 address string to permit.

addPermission

virtual

virtual void addPermission(const net::Address & address)

Adds a permission for address, or refreshes the existing one. The port is ignored; TURN permissions are IP-only.


hasPermission

virtual

virtual bool hasPermission(const std::string & peerIP)

Checks whether a permission exists for peerIP. Local addresses (192.168.x.x and 127.x.x.x) are always permitted.

Parameters

  • peerIP IPv4 address string to check.

Returns

true if a valid (non-expired) permission exists.


hasPermission

virtual

virtual bool hasPermission(const net::Address & peerAddress)

Checks whether a permission exists for peerAddress. The port is ignored; TURN permissions are IP-only.


removePermission

virtual

virtual void removePermission(const std::string & ip)

Removes the permission for ip if present.

Parameters

  • ip IPv4 address string to remove.

removePermission

virtual

virtual void removePermission(const net::Address & address)

Removes the permission for address if present. The port is ignored; TURN permissions are IP-only.

Protected Attributes

ReturnNameDescription
ClientObserver &_observer
Options_options
net::SocketEmitter_socket
Timer_timer
icy::Error_error
net::Address_mappedAddress
net::Address_relayedAddress
std::string_realm
std::string_nonce
std::deque< stun::Message >_pendingIndicationsA list of queued Send indication packets awaiting server permissions.
std::vector< stun::Transaction::Ptr >_transactionsA list containing currently active transactions.

_observer

ClientObserver & _observer

_options

Options _options

_socket

net::SocketEmitter _socket

_timer

Timer _timer

_error

icy::Error _error

_mappedAddress

net::Address _mappedAddress

_relayedAddress

net::Address _relayedAddress

_realm

std::string _realm

_nonce

std::string _nonce

_pendingIndications

std::deque< stun::Message > _pendingIndications

A list of queued Send indication packets awaiting server permissions.


_transactions

std::vector< stun::Transaction::Ptr > _transactions

A list containing currently active transactions.

Protected Methods

ReturnNameDescription
voidsetError virtualSets the error field and transitions the client to the Failed state.
boolonSocketConnect virtualSocket connect callback; starts the timer and sends the first Allocate request.
boolonSocketRecv virtualSocket receive callback; parses STUN messages from the buffer and dispatches them.
boolonSocketClose virtualSocket close callback; shuts down the client and records the socket error.
voidonTransactionProgress virtualSTUN transaction state-change callback; handles Success and Failed outcomes.
voidonStateChangeForwards state-change events to the observer.
voidonTimer virtualPeriodic timer callback; re-allocates on expiry or refreshes when lifetime is below one-third remaining. Also calls ClientObserver::onTimer().

setError

virtual

virtual void setError(const icy::Error & error)

Sets the error field and transitions the client to the Failed state.

Parameters

  • error Error descriptor.

onSocketConnect

virtual

virtual bool onSocketConnect(net::Socket & socket)

Socket connect callback; starts the timer and sends the first Allocate request.

Parameters

  • socket The connected socket.

onSocketRecv

virtual

virtual bool onSocketRecv(net::Socket & socket, const MutableBuffer & buffer, const net::Address & peerAddress)

Socket receive callback; parses STUN messages from the buffer and dispatches them.

Parameters

  • socket The receiving socket.

  • buffer Received data.

  • peerAddress Source address of the received data.


onSocketClose

virtual

virtual bool onSocketClose(net::Socket & socket)

Socket close callback; shuts down the client and records the socket error.

Parameters

  • socket The closed socket.

onTransactionProgress

virtual

virtual void onTransactionProgress(void * sender, TransactionState & state, const TransactionState &)

STUN transaction state-change callback; handles Success and Failed outcomes.

Parameters

  • sender Pointer to the stun::Transaction that changed state.

  • state The new transaction state.


onStateChange

void onStateChange(ClientState & state, const ClientState & oldState)

Forwards state-change events to the observer.


onTimer

virtual

virtual void onTimer()

Periodic timer callback; re-allocates on expiry or refreshes when lifetime is below one-third remaining. Also calls ClientObserver::onTimer().