webrtc_ice_agent (webrtc v0.1.0)

View Source

Sans-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. Socket may be a stream connection {stream, N} to a TURN server (below): write Bin on it.
  • {connect, {stream, N}, #{server, transport, local, hostname, tls_options}}: open a TCP (transporttcp) or TLS (tls) connection to a TURN server from address local, then call stream_up/3, or stream_down/4 when it fails. Messages read from it (webrtc_turn_stream:split/1) go to handle_packet/5 with {stream, N} as the socket and the server as the source; stream_down/4 when it closes.
  • {open_udp, {udp, N}, #{local := IP}}: open a UDP socket on IP (any port) and report it with udp_socket_up/4, or udp_socket_down/4.
  • {connect, {tcp, N}, #{transport := ice_tcp, local, remote}}: open a TCP connection from address local to remote for an ICE-TCP pair (RFC 6544), then stream_up/3 or stream_down/4. Packets on it, both ways, are framed with a 16-bit length (RFC 4571): received ones go to handle_packet/5 with {tcp, N} as the socket and the remote address as the source.
  • {close_stream, Ref}: close the connection Ref.
  • {event, Event}.

Events

  • {local_candidate, #ice_cand{}}: a new local candidate to trickle (webrtc_ice_candidate:to_sdp/1 gives 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 from Peer.
  • {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

action/0

-type action() :: {send, term(), webrtc_ice_candidate:address(), binary()} | {event, event()}.

agent/0

-opaque agent()

event/0

-type event() :: {atom(), term()} | {atom(), term(), term()} | {data, via(), term(), binary()}.

opts/0

-type opts() :: #{atom() => term()}.

via/0

-type via() :: term() | {relay, term(), webrtc_ice_candidate:address()}.

Functions

add_host(Sock, Addr, Now, S)

-spec add_host(term(), webrtc_ice_candidate:address(), integer(), agent()) -> {agent(), [action()]}.

Add one host candidate later (new interface).

add_remote_candidate(Bin, Now, S)

-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(Now, Ice)

-spec close(integer(), agent()) -> {agent(), [action()]}.

Close the agent: TURN allocations are deleted, nothing is sent afterwards.

connection_state(Ice)

-spec connection_state(agent()) -> atom().

end_of_candidates(Now, S)

-spec end_of_candidates(integer(), agent()) -> {agent(), [action()]}.

gather(Hosts, Now, S)

-spec gather([tuple()], integer(), agent()) -> {agent(), [action()]}.

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.

gathering_state(Ice)

-spec gathering_state(agent()) -> new | gathering | complete.

handle_packet(Sock, From, Bin, Now, Ice)

-spec handle_packet(term(), webrtc_ice_candidate:address(), binary(), integer(), agent()) ->
                       {agent(), [action()]}.

A datagram received on Sock from From.

handle_timeout(Now, Ice)

-spec handle_timeout(integer(), agent()) -> {agent(), [action()]}.

is_valid_remote(Via, From, S)

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

local_candidates(Ice)

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

local_credentials(Ice)

-spec local_credentials(agent()) -> {binary(), binary()}.

new(Opts)

-spec new(opts()) -> agent().

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

next_timeout(Ice)

-spec next_timeout(agent()) -> integer() | infinity.

remote_candidates(Ice)

-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}].

remote_credentials(Ice)

-spec remote_credentials(agent()) -> {binary(), binary()} | undefined.

remove_host(Sock, Now, S)

-spec remove_host(term(), integer(), agent()) -> {agent(), [action()]}.

A socket went away (network change): remove its candidates.

restart(Now, S)

-spec restart(integer(), agent()) -> {agent(), [action()]}.

ICE restart (RFC 8445 §9) with new random credentials.

restart(Opts, Now, S)

-spec restart(map(), integer(), agent()) -> {agent(), [action()]}.

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.

role(Ice)

-spec role(agent()) -> controlling | controlled.

selected_pair(S)

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

selected_pair(Comp, S)

-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(Data, Now, S)

-spec send(binary(), integer(), agent()) -> {ok, agent(), [action()]} | {error, term()}.

send(Comp, Data, Now, Ice)

-spec send(1..256, binary(), integer(), agent()) -> {ok, agent(), [action()]} | {error, term()}.

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.

set_marks(Marks, S)

-spec set_marks([1..63], agent()) -> agent().

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

set_remote_credentials(U, P, Now, Ice)

-spec set_remote_credentials(binary(), binary(), integer(), agent()) -> {agent(), [action()]}.

Remote ufrag and password (RFC 8839 §5.4). Starts the checks and the RFC 8863 PAC timer. Changing them requires restart/2,3.

set_remote_pacing(Ta, Ice)

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

stats(S)

-spec stats(agent()) -> map().

Counters and the candidate pairs with their state, validity, nomination, RTT and request/response counts.

stream_down(Ref, Reason, Now, S)

-spec stream_down({stream, pos_integer()}, term(), integer(), agent()) -> {agent(), [action()]}.

A stream connection to a TURN server failed or closed.

stream_server(Ref, Ice)

-spec stream_server({stream, pos_integer()}, agent()) -> webrtc_ice_candidate:address() | undefined.

The TURN server a stream connection leads to.

stream_up(Ref, Now, S)

-spec stream_up({stream, pos_integer()}, integer(), agent()) -> {agent(), [action()]}.

A stream connection to a TURN server asked with {connect, ...} is up.

tcp_accepted(Ref, Listen, Peer, Now, S)

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

tcp_listeners(Specs, Now, S)

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

udp_socket_down(Ref, Reason, Now, S)

-spec udp_socket_down({udp, pos_integer()}, term(), integer(), agent()) -> {agent(), [action()]}.

udp_socket_up(Ref, Sock, Now, S)

-spec udp_socket_up({udp, pos_integer()}, term(), integer(), agent()) -> {agent(), [action()]}.

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.