webrtc_ice_agent (webrtc v0.1.0)
View SourceSans-IO ICE agent (RFC 8445), full or lite, with trickle ICE (RFC 8838), the RFC 8863 failure rule, consent freshness (RFC 7675) and relayed candidates through TURN (RFC 8656).
The agent handles one data stream. With BUNDLE and rtcp-mux (the WebRTC case) that is a single component, 1; other components can be configured with the components option and given to host candidates.
Driving the agent
The owner (a transport process) holds the agent state, the UDP sockets and a single timer:
A0 = webrtc_ice_agent:new(#{role => controlling,
stun_servers => [{{192,0,2,1}, 3478}]}),
{U, P} = webrtc_ice_agent:local_credentials(A0), % signal them
{A1, Acts1} = webrtc_ice_agent:gather([{Sock, {IP, Port}}], Now, A0),
{A2, Acts2} = webrtc_ice_agent:set_remote_credentials(RU, RP, Now, A1),
{A3, Acts3} = webrtc_ice_agent:add_remote_candidate(<<"candidate:...">>, Now, A2),
{A4, Acts4} = webrtc_ice_agent:end_of_candidates(Now, A3),
%% every datagram whose first byte is 0..3 (STUN) or 64..79 (TURN
%% ChannelData):
{A5, Acts5} = webrtc_ice_agent:handle_packet(Sock, {SrcIP, SrcPort}, Bin, Now, A4),
%% when the timer fires:
{A6, Acts6} = webrtc_ice_agent:handle_timeout(Now, A5),
Deadline = webrtc_ice_agent:next_timeout(A6),
%% application data (DTLS, SRTP) on the selected pair:
{ok, A7, Acts7} = webrtc_ice_agent:send(Data, Now, A6).After every call the owner executes the actions in order and re-arms its timer from next_timeout/1 (an absolute time in the unit of Now, monotonic milliseconds, or infinity).
Datagrams that are neither STUN nor ChannelData (DTLS, SRTP) are not given to the agent. The owner must drop them unless is_valid_remote(Socket, Source, Agent) is true (RFC 8445 §12.2, RFC 8826 §4.2).
Actions
{send, Socket, {IP, Port}, Bin}: send a datagram on the owner's socket.Socketmay be a stream connection{stream, N}to a TURN server (below): writeBinon it.{connect, {stream, N}, #{server, transport, local, hostname, tls_options}}: open a TCP (transporttcp) or TLS (tls) connection to a TURN server from addresslocal, then callstream_up/3, orstream_down/4when it fails. Messages read from it (webrtc_turn_stream:split/1) go tohandle_packet/5with{stream, N}as the socket and the server as the source;stream_down/4when it closes.{open_udp, {udp, N}, #{local := IP}}: open a UDP socket onIP(any port) and report it withudp_socket_up/4, orudp_socket_down/4.{connect, {tcp, N}, #{transport := ice_tcp, local, remote}}: open a TCP connection from addresslocaltoremotefor an ICE-TCP pair (RFC 6544), thenstream_up/3orstream_down/4. Packets on it, both ways, are framed with a 16-bit length (RFC 4571): received ones go tohandle_packet/5with{tcp, N}as the socket and the remote address as the source.{close_stream, Ref}: close the connectionRef.{event, Event}.
Events
{local_candidate, #ice_cand{}}: a new local candidate to trickle (webrtc_ice_candidate:to_sdp/1gives the attribute value).{local_candidate_removed, #ice_cand{}}.{gathering_state, new | gathering | complete}.{connection_state, new | checking | connected | completed | failed | disconnected | closed}.{selected_pair, Local, Remote}.{consent_lost, Local, Remote}: consent expired or was revoked; the agent no longer sends data on that pair.{role_change, controlling | controlled}.{data, {relay, Socket, Server}, Peer, Data}: a non-STUN datagram relayed by a TURN server; the owner demultiplexes it like a datagram received fromPeer.{turn_error, Server, Reason}.
Paths (via()) name where a packet entered or leaves: the owner's socket for host candidates, {relay, Socket, Server} for relayed candidates.
Summary
Functions
Add one host candidate later (new interface).
Add a remote candidate (record or a=candidate value). Ignored after end-of-candidates (RFC 8838 §14), for an unknown component, or when its ufrag extension names another session.
Close the agent: TURN allocations are deleted, nothing is sent afterwards.
Add the host candidates ({Socket, {IP, Port}} or {Socket, {IP, Port}, Component}, one socket per host candidate) and start gathering server-reflexive and relayed candidates.
A datagram received on Sock from From.
True when packets from From on Via belong to a validated pair (or a pair the peer authenticated with a check) that still has consent. Non-ICE traffic from other sources must be dropped.
Local candidates to signal (peer-reflexive ones excluded).
Create an agent. Options (all optional): role (controlling default), lite, remote_lite, ufrag, pwd, tiebreaker, seed (term for rand:seed_s/2, for reproducible tie-breakers and jitter), stun_servers ([Addr]), turn_servers ([#{address, username, password}]), components, ta (50 ms, at least 5, RFC 8445 §14.2), rc (7), rm (16), min_rto (500), max_check_rto (2500), max_rto, max_pairs (100), max_remote (remote candidates kept, signaled or peer-reflexive, 100), pac_timeout (39500), eoc_timeout (39500), nomination (best | first), nomination_timeout (1000), consent (true), consent_interval (5000), consent_expiry (30000), disconnect_timeout (10000), keepalive_interval (15000), stun_keepalive (15000), hidden_hosts (false: host candidates are signaled as they are).
A socket went away (network change): remove its candidates.
ICE restart (RFC 8445 §9) with new random credentials.
ICE restart. Opts may give ufrag and pwd. The selected pairs stay usable (with consent checks on the old credentials) until the new session selects its own. Local candidates are kept; signal them again with local_candidates/1.
Send application data on the selected pair of Comp (or the best valid pair before nomination, RFC 8445 §12.1, or the pair kept across an ICE restart). Fails when no pair has consent.
The DSCPs the flows on the selected pair use: each consent request is also sent with each of them, and a mark the path drops is reported as {dscp_blocked, Dscp} (RFC 8835 §4.2).
Remote ufrag and password (RFC 8839 §5.4). Starts the checks and the RFC 8863 PAC timer. Changing them requires restart/2,3.
The peer's Ta (a=ice-pacing, RFC 8839 §5.5; 50 ms when it sent none). Both agents use the higher of the two values (RFC 8445 §14.2).
Counters and the candidate pairs with their state, validity, nomination, RTT and request/response counts.
A stream connection to a TURN server failed or closed.
The TURN server a stream connection leads to.
A stream connection to a TURN server asked with {connect, ...} is up.
A connection {tcp, N} (named by the owner) was accepted on listener ListenRef from Peer. Refused ({close_stream, Ref}) when too many are open.
ICE-TCP (RFC 6544): the owner listens on these TCP addresses, [{ListenRef, {IP, Port}}]. Each gives a passive and an active host candidate. Call it before gather/3: gathering may complete there, and candidates after end-of-candidates are ignored by the peer.
The UDP socket asked with {open_udp, {udp, N}, #{local := IP}} is open (a TURN allocation retried from a new local port after 437, RFC 8656 §7.4). Datagrams it receives go to handle_packet/5 as for the other sockets.
Types
-type action() :: {send, term(), webrtc_ice_candidate:address(), binary()} | {event, event()}.
-opaque agent()
-type via() :: term() | {relay, term(), webrtc_ice_candidate:address()}.
Functions
-spec add_host(term(), webrtc_ice_candidate:address(), integer(), agent()) -> {agent(), [action()]}.
Add one host candidate later (new interface).
-spec add_remote_candidate(#ice_cand{foundation :: binary(), component :: 1..256, transport :: udp | tcp, priority :: 1..2147483647, address :: inet:ip_address(), port :: inet:port_number(), type :: host | srflx | prflx | relay, related_address :: inet:ip_address() | undefined, related_port :: inet:port_number() | undefined, tcptype :: active | passive | so | undefined, extensions :: [{binary(), binary()}], base :: {inet:ip_address(), inet:port_number()} | undefined, socket :: term(), server :: {inet:ip_address(), inet:port_number()} | undefined} | binary(), integer(), agent()) -> {agent(), [action()]} | {error, term()}.
Add a remote candidate (record or a=candidate value). Ignored after end-of-candidates (RFC 8838 §14), for an unknown component, or when its ufrag extension names another session.
Close the agent: TURN allocations are deleted, nothing is sent afterwards.
Add the host candidates ({Socket, {IP, Port}} or {Socket, {IP, Port}, Component}, one socket per host candidate) and start gathering server-reflexive and relayed candidates.
-spec gathering_state(agent()) -> new | gathering | complete.
-spec handle_packet(term(), webrtc_ice_candidate:address(), binary(), integer(), agent()) -> {agent(), [action()]}.
A datagram received on Sock from From.
-spec is_valid_remote(via(), webrtc_ice_candidate:address(), agent()) -> boolean().
True when packets from From on Via belong to a validated pair (or a pair the peer authenticated with a check) that still has consent. Non-ICE traffic from other sources must be dropped.
-spec local_candidates(agent()) -> [#ice_cand{foundation :: binary(), component :: 1..256, transport :: udp | tcp, priority :: 1..2147483647, address :: inet:ip_address(), port :: inet:port_number(), type :: host | srflx | prflx | relay, related_address :: inet:ip_address() | undefined, related_port :: inet:port_number() | undefined, tcptype :: active | passive | so | undefined, extensions :: [{binary(), binary()}], base :: {inet:ip_address(), inet:port_number()} | undefined, socket :: term(), server :: {inet:ip_address(), inet:port_number()} | undefined}].
Local candidates to signal (peer-reflexive ones excluded).
Create an agent. Options (all optional): role (controlling default), lite, remote_lite, ufrag, pwd, tiebreaker, seed (term for rand:seed_s/2, for reproducible tie-breakers and jitter), stun_servers ([Addr]), turn_servers ([#{address, username, password}]), components, ta (50 ms, at least 5, RFC 8445 §14.2), rc (7), rm (16), min_rto (500), max_check_rto (2500), max_rto, max_pairs (100), max_remote (remote candidates kept, signaled or peer-reflexive, 100), pac_timeout (39500), eoc_timeout (39500), nomination (best | first), nomination_timeout (1000), consent (true), consent_interval (5000), consent_expiry (30000), disconnect_timeout (10000), keepalive_interval (15000), stun_keepalive (15000), hidden_hosts (false: host candidates are signaled as they are).
-spec remote_candidates(agent()) -> [#ice_cand{foundation :: binary(), component :: 1..256, transport :: udp | tcp, priority :: 1..2147483647, address :: inet:ip_address(), port :: inet:port_number(), type :: host | srflx | prflx | relay, related_address :: inet:ip_address() | undefined, related_port :: inet:port_number() | undefined, tcptype :: active | passive | so | undefined, extensions :: [{binary(), binary()}], base :: {inet:ip_address(), inet:port_number()} | undefined, socket :: term(), server :: {inet:ip_address(), inet:port_number()} | undefined}].
A socket went away (network change): remove its candidates.
ICE restart (RFC 8445 §9) with new random credentials.
ICE restart. Opts may give ufrag and pwd. The selected pairs stay usable (with consent checks on the old credentials) until the new session selects its own. Local candidates are kept; signal them again with local_candidates/1.
-spec role(agent()) -> controlling | controlled.
-spec selected_pair(agent()) -> {#ice_cand{foundation :: binary(), component :: 1..256, transport :: udp | tcp, priority :: 1..2147483647, address :: inet:ip_address(), port :: inet:port_number(), type :: host | srflx | prflx | relay, related_address :: inet:ip_address() | undefined, related_port :: inet:port_number() | undefined, tcptype :: active | passive | so | undefined, extensions :: [{binary(), binary()}], base :: {inet:ip_address(), inet:port_number()} | undefined, socket :: term(), server :: {inet:ip_address(), inet:port_number()} | undefined}, #ice_cand{foundation :: binary(), component :: 1..256, transport :: udp | tcp, priority :: 1..2147483647, address :: inet:ip_address(), port :: inet:port_number(), type :: host | srflx | prflx | relay, related_address :: inet:ip_address() | undefined, related_port :: inet:port_number() | undefined, tcptype :: active | passive | so | undefined, extensions :: [{binary(), binary()}], base :: {inet:ip_address(), inet:port_number()} | undefined, socket :: term(), server :: {inet:ip_address(), inet:port_number()} | undefined}} | undefined.
-spec selected_pair(1..256, agent()) -> {#ice_cand{foundation :: binary(), component :: 1..256, transport :: udp | tcp, priority :: 1..2147483647, address :: inet:ip_address(), port :: inet:port_number(), type :: host | srflx | prflx | relay, related_address :: inet:ip_address() | undefined, related_port :: inet:port_number() | undefined, tcptype :: active | passive | so | undefined, extensions :: [{binary(), binary()}], base :: {inet:ip_address(), inet:port_number()} | undefined, socket :: term(), server :: {inet:ip_address(), inet:port_number()} | undefined}, #ice_cand{foundation :: binary(), component :: 1..256, transport :: udp | tcp, priority :: 1..2147483647, address :: inet:ip_address(), port :: inet:port_number(), type :: host | srflx | prflx | relay, related_address :: inet:ip_address() | undefined, related_port :: inet:port_number() | undefined, tcptype :: active | passive | so | undefined, extensions :: [{binary(), binary()}], base :: {inet:ip_address(), inet:port_number()} | undefined, socket :: term(), server :: {inet:ip_address(), inet:port_number()} | undefined}} | undefined.
Send application data on the selected pair of Comp (or the best valid pair before nomination, RFC 8445 §12.1, or the pair kept across an ICE restart). Fails when no pair has consent.
The DSCPs the flows on the selected pair use: each consent request is also sent with each of them, and a mark the path drops is reported as {dscp_blocked, Dscp} (RFC 8835 §4.2).
Remote ufrag and password (RFC 8839 §5.4). Starts the checks and the RFC 8863 PAC timer. Changing them requires restart/2,3.
-spec set_remote_pacing(non_neg_integer(), agent()) -> agent().
The peer's Ta (a=ice-pacing, RFC 8839 §5.5; 50 ms when it sent none). Both agents use the higher of the two values (RFC 8445 §14.2).
Counters and the candidate pairs with their state, validity, nomination, RTT and request/response counts.
A stream connection to a TURN server failed or closed.
-spec stream_server({stream, pos_integer()}, agent()) -> webrtc_ice_candidate:address() | undefined.
The TURN server a stream connection leads to.
-spec stream_up({stream, pos_integer()}, integer(), agent()) -> {agent(), [action()]}.
A stream connection to a TURN server asked with {connect, ...} is up.
-spec tcp_accepted({tcp, term()}, term(), webrtc_ice_candidate:address(), integer(), agent()) -> {agent(), [action()]}.
A connection {tcp, N} (named by the owner) was accepted on listener ListenRef from Peer. Refused ({close_stream, Ref}) when too many are open.
-spec tcp_listeners([{term(), webrtc_ice_candidate:address()}], integer(), agent()) -> {agent(), [action()]}.
ICE-TCP (RFC 6544): the owner listens on these TCP addresses, [{ListenRef, {IP, Port}}]. Each gives a passive and an active host candidate. Call it before gather/3: gathering may complete there, and candidates after end-of-candidates are ignored by the peer.
The UDP socket asked with {open_udp, {udp, N}, #{local := IP}} is open (a TURN allocation retried from a new local port after 437, RFC 8656 §7.4). Datagrams it receives go to handle_packet/5 as for the other sockets.