Home
TURN module (rfc5766)

Client

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

Client

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

Defined in src/turn/include/icy/turn/client/client.h:124

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

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

List of all members

NameKindOwner
ClientfunctionDeclared here
~ClientfunctionDeclared here
startfunctionDeclared here
stopfunctionDeclared here
sendAllocatefunctionDeclared here
addPermissionfunctionDeclared here
addPermissionfunctionDeclared here
sendCreatePermissionfunctionDeclared here
sendChannelBindfunctionDeclared here
sendRefreshfunctionDeclared here
sendDatafunctionDeclared here
handleResponsefunctionDeclared here
handleAllocateResponsefunctionDeclared here
handleAllocateErrorResponsefunctionDeclared here
handleCreatePermissionResponsefunctionDeclared here
handleCreatePermissionErrorResponsefunctionDeclared here
handleRefreshResponsefunctionDeclared here
handleDataIndicationfunctionDeclared here
transportProtocolfunctionDeclared here
createTransactionfunctionDeclared here
authenticateRequestfunctionDeclared here
sendAuthenticatedTransactionfunctionDeclared here
removeTransactionfunctionDeclared here
mappedAddressfunctionDeclared here
relayedAddressfunctionDeclared here
closedfunctionDeclared here
observerfunctionDeclared here
optionsfunctionDeclared here
addPermissionfunctionDeclared here
addPermissionfunctionDeclared here
hasPermissionfunctionDeclared here
hasPermissionfunctionDeclared here
removePermissionfunctionDeclared here
removePermissionfunctionDeclared here
_observervariableDeclared here
_optionsvariableDeclared here
_socketvariableDeclared here
_timervariableDeclared here
_errorvariableDeclared here
_mappedAddressvariableDeclared here
_relayedAddressvariableDeclared here
_realmvariableDeclared here
_noncevariableDeclared here
_pendingIndicationsvariableDeclared here
_transactionsvariableDeclared here
setErrorfunctionDeclared here
onSocketConnectfunctionDeclared here
onSocketRecvfunctionDeclared here
onSocketClosefunctionDeclared here
onTransactionProgressfunctionDeclared here
onStateChangefunctionDeclared here
onTimerfunctionDeclared here
StateChangevariableInherited from Stateful
StatefulfunctionInherited from Stateful
~StatefulfunctionInherited from Stateful
stateEqualsfunctionInherited from Stateful
stateBetweenfunctionInherited from Stateful
statefunctionInherited from Stateful
statefunctionInherited from Stateful
_statevariableInherited from Stateful
beforeStateChangefunctionInherited from Stateful
onStateChangefunctionInherited from Stateful
setStatefunctionInherited from Stateful
setStatefunctionInherited from Stateful
operator<<friendInherited from IAllocation
IAllocationfunctionInherited from IAllocation
~IAllocationfunctionInherited from IAllocation
IAllocationfunctionInherited from IAllocation
operator=functionInherited from IAllocation
IAllocationfunctionInherited from IAllocation
operator=functionInherited from IAllocation
updateUsagefunctionInherited from IAllocation
setLifetimefunctionInherited from IAllocation
setBandwidthLimitfunctionInherited from IAllocation
expiredfunctionInherited from IAllocation
deletedfunctionInherited from IAllocation
bandwidthLimitfunctionInherited from IAllocation
bandwidthUsedfunctionInherited from IAllocation
bandwidthRemainingfunctionInherited from IAllocation
timeRemainingfunctionInherited from IAllocation
tuplefunctionInherited from IAllocation
usernamefunctionInherited from IAllocation
lifetimefunctionInherited from IAllocation
permissionsfunctionInherited from IAllocation
relayedAddressfunctionInherited from IAllocation
addPermissionfunctionInherited from IAllocation
addPermissionfunctionInherited from IAllocation
addPermissionsfunctionInherited from IAllocation
removePermissionfunctionInherited from IAllocation
removePermissionfunctionInherited from IAllocation
removeAllPermissionsfunctionInherited from IAllocation
removeExpiredPermissionsfunctionInherited from IAllocation
hasPermissionfunctionInherited from IAllocation
hasPermissionfunctionInherited from IAllocation
printfunctionInherited from IAllocation
_tuplevariableInherited from IAllocation
_usernamevariableInherited from IAllocation
_permissionsvariableInherited from IAllocation
_lifetimevariableInherited from IAllocation
_bandwidthLimitvariableInherited from IAllocation
_bandwidthUsedvariableInherited from IAllocation
_createdAtvariableInherited from IAllocation
_updatedAtvariableInherited from IAllocation
_deletedvariableInherited from IAllocation

Inherited from Stateful

KindNameDescription
variableStateChangeSignals when the state changes.
functionStateful inline
function~Stateful virtual inline
functionstateEquals virtual const inlineReturns true if the current state ID equals the given ID.
functionstateBetween virtual const inlineReturns true if the current state ID is in the inclusive range [lid, rid].
functionstate virtual inlineReturns a mutable reference to the current state.
functionstate virtual const inlineReturns a copy of the current state.
variable_state
functionbeforeStateChange virtual inlineOverride to handle pre state change logic. Return false to prevent state change.
functiononStateChange virtual inlineOverride to handle post state change logic.
functionsetState virtual inlineSets the state and sends the state signal if the state change was successful.
functionsetState virtual inlineSets the state and sends the state signal if the state change was successful.

Inherited from IAllocation

KindNameDescription
friendoperator<< inline
functionIAllocation
function~IAllocation virtual
functionIAllocationDeleted constructor.
functionoperator=Deleted assignment operator.
functionIAllocationDeleted constructor.
functionoperator=Deleted assignment operator.
functionupdateUsage virtualUpdates the last-activity timestamp and accumulates bandwidth usage. Call this whenever data is relayed through the allocation.
functionsetLifetime virtualSets the allocation lifetime in seconds and resets the activity timestamp, effectively extending the expiry from the current moment.
functionsetBandwidthLimit virtualSets the maximum number of bytes this allocation may relay in its lifetime. Pass 0 to disable bandwidth limiting.
functionexpired virtual const
functiondeleted virtual constReturns true if the allocation's deleted flag is set and or if the allocation has expired.
functionbandwidthLimit virtual const
functionbandwidthUsed virtual const
functionbandwidthRemaining virtual const
functiontimeRemaining virtual const
functiontuple virtual
functionusername virtual const
functionlifetime virtual const
functionpermissions virtual const
functionrelayedAddress virtual const
functionaddPermission virtualAdds a permission for ip, or refreshes the existing one.
functionaddPermission virtualAdds a permission for address, or refreshes the existing one. The port is ignored; TURN permissions are IP-only.
functionaddPermissions virtualAdds (or refreshes) permissions for multiple IPs.
functionremovePermission virtualRemoves the permission for ip if present.
functionremovePermission virtualRemoves the permission for address if present. The port is ignored; TURN permissions are IP-only.
functionremoveAllPermissions virtualRemoves all permissions from the list.
functionremoveExpiredPermissions virtualRemoves any permissions whose 5-minute lifetime has elapsed.
functionhasPermission virtualChecks whether a permission exists for peerIP. Local addresses (192.168.x.x and 127.x.x.x) are always permitted.
functionhasPermission virtualChecks whether a permission exists for peerAddress. The port is ignored; TURN permissions are IP-only.
functionprint virtual const inline
variable_tuple
variable_username
variable_permissions
variable_lifetime
variable_bandwidthLimit
variable_bandwidthUsed
variable_createdAt
variable_updatedAt
variable_deleted

Public Methods

ReturnNameDescription
Client
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 virtual overrideAdds 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
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
net::AddressrelayedAddress virtual const override
boolclosed const
ClientObserver &observer
const Options &options const
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)

Defined in src/turn/include/icy/turn/client/client.h:161

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()

Defined in src/turn/include/icy/turn/client/client.h:166

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

Reimplemented by

stop

virtual

virtual void stop()

Defined in src/turn/include/icy/turn/client/client.h:169

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

Reimplemented by

sendAllocate

virtual

virtual void sendAllocate()

Defined in src/turn/include/icy/turn/client/client.h:175

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)

Defined in src/turn/include/icy/turn/client/client.h:179

Adds multiple peer IP addresses to the permission list.

Parameters

  • peerIPs List of IPv4 address strings to permit.

addPermission

virtual override

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

Defined in src/turn/include/icy/turn/client/client.h:186

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.
Reimplements

sendCreatePermission

virtual

virtual void sendCreatePermission()

Defined in src/turn/include/icy/turn/client/client.h:191

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)

Defined in src/turn/include/icy/turn/client/client.h:202

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()

Defined in src/turn/include/icy/turn/client/client.h:207

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)

Defined in src/turn/include/icy/turn/client/client.h:215

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).

Reimplemented by

handleResponse

virtual

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

Defined in src/turn/include/icy/turn/client/client.h:220

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.

Reimplemented by

handleAllocateResponse

virtual

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

Defined in src/turn/include/icy/turn/client/client.h:225

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)

Defined in src/turn/include/icy/turn/client/client.h:230

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)

Defined in src/turn/include/icy/turn/client/client.h:235

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)

Defined in src/turn/include/icy/turn/client/client.h:240

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)

Defined in src/turn/include/icy/turn/client/client.h:244

Handles a Refresh response; updates the stored lifetime.

Parameters

  • response Refresh response from the server.

handleDataIndication

virtual

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

Defined in src/turn/include/icy/turn/client/client.h:249

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()

Defined in src/turn/include/icy/turn/client/client.h:253

Returns

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

Reimplemented by

createTransaction

virtual

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

Defined in src/turn/include/icy/turn/client/client.h:259

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)

Defined in src/turn/include/icy/turn/client/client.h:264

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)

Defined in src/turn/include/icy/turn/client/client.h:269

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)

Defined in src/turn/include/icy/turn/client/client.h:275

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

Defined in src/turn/include/icy/turn/client/client.h:278

Returns

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


relayedAddress

virtual const override

virtual net::Address relayedAddress() const override

Defined in src/turn/include/icy/turn/client/client.h:281

Returns

The relayed transport address assigned by the TURN server.

Reimplements

closed

const

bool closed() const

Defined in src/turn/include/icy/turn/client/client.h:284

Returns

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


observer

ClientObserver & observer()

Defined in src/turn/include/icy/turn/client/client.h:287

Returns

Reference to the observer provided at construction.


options

const

const Options & options() const

Defined in src/turn/include/icy/turn/client/client.h:290

Returns

Reference to the immutable options struct.


addPermission

virtual

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

Defined in src/turn/include/icy/turn/client/client.h:154

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

Parameters

  • ip IPv4 address string to permit.
Reimplements

addPermission

virtual

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

Defined in src/turn/include/icy/turn/client/client.h:154

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

Reimplements

hasPermission

virtual

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

Defined in src/turn/include/icy/turn/client/client.h:155

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.

Reimplements

hasPermission

virtual

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

Defined in src/turn/include/icy/turn/client/client.h:155

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

Reimplements

removePermission

virtual

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

Defined in src/turn/include/icy/turn/client/client.h:156

Removes the permission for ip if present.

Parameters

  • ip IPv4 address string to remove.
Reimplements

removePermission

virtual

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

Defined in src/turn/include/icy/turn/client/client.h:156

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

Reimplements

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

Defined in src/turn/include/icy/turn/client/client.h:324


_options

Options _options

Defined in src/turn/include/icy/turn/client/client.h:325


_socket

net::SocketEmitter _socket

Defined in src/turn/include/icy/turn/client/client.h:326


_timer

Timer _timer

Defined in src/turn/include/icy/turn/client/client.h:327


_error

icy::Error _error

Defined in src/turn/include/icy/turn/client/client.h:328


_mappedAddress

net::Address _mappedAddress

Defined in src/turn/include/icy/turn/client/client.h:329


_relayedAddress

net::Address _relayedAddress

Defined in src/turn/include/icy/turn/client/client.h:330


_realm

std::string _realm

Defined in src/turn/include/icy/turn/client/client.h:332


_nonce

std::string _nonce

Defined in src/turn/include/icy/turn/client/client.h:333


_pendingIndications

std::deque< stun::Message > _pendingIndications

Defined in src/turn/include/icy/turn/client/client.h:336

A list of queued Send indication packets awaiting server permissions.


_transactions

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

Defined in src/turn/include/icy/turn/client/client.h:339

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.
voidonStateChange overrideForwards 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)

Defined in src/turn/include/icy/turn/client/client.h:295

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

Parameters

  • error Error descriptor.

onSocketConnect

virtual

virtual bool onSocketConnect(net::Socket & socket)

Defined in src/turn/include/icy/turn/client/client.h:299

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)

Defined in src/turn/include/icy/turn/client/client.h:305

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)

Defined in src/turn/include/icy/turn/client/client.h:309

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 &)

Defined in src/turn/include/icy/turn/client/client.h:314

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

override

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

Defined in src/turn/include/icy/turn/client/client.h:317

Forwards state-change events to the observer.


onTimer

virtual

virtual void onTimer()

Defined in src/turn/include/icy/turn/client/client.h:321

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