Skip to main content

rtci_ice/agent/
agent_proto.rs

1use super::*;
2use mdns::MDNS_PORT;
3
4/// The line logged for a datagram whose local address is no local candidate's (RFC 8445
5/// Section 7.3.1.4: the local candidate has "the transport address (as seen by the agent) on
6/// which the STUN request was received"). An unspecified local address (`0.0.0.0:port`,
7/// `[::]:port`) is never a candidate's transport address: it is what a socket bound to the
8/// unspecified address reports as its own, and the line says so. The datagram is discarded
9/// either way; only the wording differs.
10pub(crate) fn unmatched_local_address_log(name: &str, transport: &TransportContext) -> String {
11    if transport.local_addr.ip().is_unspecified() {
12        format!(
13            "[{name}]: Discarded message from {}: its local address {} is unspecified. The local \
14             address of a datagram is the address of the local candidate it arrived on: a socket \
15             bound to the unspecified address must report the concrete address each datagram \
16             was received on (its destination address, IP_PKTINFO / IPV6_RECVPKTINFO), and a \
17             datagram relayed by a TURN allocation the application runs carries the relayed \
18             address",
19            transport.peer_addr, transport.local_addr,
20        )
21    } else {
22        format!(
23            "[{name}]: Discarded message, not a valid local candidate from {:?}:{}",
24            transport.transport_protocol, transport.local_addr,
25        )
26    }
27}
28
29impl sansio::Protocol<TaggedBytesMut, (), ()> for Agent {
30    type Rout = TaggedBytesMut;
31    type Wout = TaggedBytesMut;
32    type Eout = TaggedEvent;
33    type Error = Error;
34    type Time = Instant;
35
36    /// Reads one datagram. `msg.transport.local_addr` is the transport address of the local
37    /// candidate the datagram arrived on, matched exactly (RFC 8445 Section 7.3.1.4): the
38    /// address of a host candidate, or, for a datagram a TURN allocation relayed (taken out of
39    /// its Data indication or ChannelData), the relayed address of the relayed candidate. A
40    /// socket bound to the unspecified address reports the concrete address the datagram was
41    /// received on, not `0.0.0.0:port` / `[::]:port`. A datagram on an address that is no
42    /// local candidate's is discarded with [`Error::ErrUnhandledStunpacket`].
43    fn handle_read(&mut self, msg: TaggedBytesMut) -> Result<()> {
44        self.clock = self.clock.max(msg.now);
45        // The embedder's address policy: a datagram from a source it refuses is dropped before
46        // anything reads it, as a firewall would drop it: no response, no peer-reflexive
47        // candidate, no consent, no pair (`AgentConfig::address_policy`).
48        if !self.remote_policy.allows_source(msg.transport.peer_addr) {
49            debug!(
50                "[{}]: dropped a datagram from {}: the address policy refuses the source",
51                self.get_name(),
52                msg.transport.peer_addr
53            );
54            return Ok(());
55        }
56        // mDNS arrives on the host's mDNS socket, the one bound to MDNS_PORT that this
57        // agent's queries leave from. A source port says nothing: anyone can send from 5353 to
58        // an ICE socket, and an answer taken from there could point a `.local` candidate at an
59        // address of the sender's choosing. Datagrams on ICE sockets are ICE traffic, whatever
60        // their source port.
61        // (Whatever arrives on the mDNS socket goes to the mDNS connection, from any source
62        // port: a query from another port is a legacy unicast query, which RFC 6762 Section
63        // 6.7 has answered by unicast; a response from another port is refused there. With
64        // `multicast_dns_destination_reported` the local address is the datagram's
65        // destination, the mDNS group's or the host's own.)
66        if msg.transport.local_addr.port() == MDNS_PORT
67            && self
68                .find_local_candidate(msg.transport.local_addr, msg.transport.transport_protocol)
69                .is_none()
70        {
71            let now = msg.now;
72            if let Some(mdns_conn) = &mut self.mdns {
73                mdns_conn.handle_read(msg)?;
74            }
75            let remote_candidates = self.drain_mdns_events(now);
76            self.trigger_request_connectivity_check(remote_candidates);
77
78            Ok(())
79        } else if self.handle_previous_generation(&msg) {
80            // Consent traffic of the generation an ICE restart replaced, on the path that is
81            // still in use.
82            Ok(())
83        } else if let Some(local_index) =
84            self.find_local_candidate(msg.transport.local_addr, msg.transport.transport_protocol)
85        {
86            self.handle_inbound_candidate_msg(local_index, msg)
87        } else {
88            warn!(
89                "{}",
90                unmatched_local_address_log(self.get_name(), &msg.transport)
91            );
92            Err(Error::ErrUnhandledStunpacket)
93        }
94    }
95
96    fn poll_read(&mut self) -> Option<Self::Rout> {
97        None
98    }
99
100    fn handle_write(&mut self, _msg: ()) -> std::result::Result<(), Self::Error> {
101        Ok(())
102    }
103
104    /// The next datagram to send. `transport.local_addr` is the base of the local candidate
105    /// it leaves from (RFC 8445 Section 6.1.2): a host candidate's address (send it from that
106    /// socket), or a relayed candidate's relayed address, in which case it goes through that
107    /// candidate's TURN allocation (a Send indication or ChannelData to `peer_addr`), not
108    /// directly from a socket. (mDNS datagrams leave from port 5353, the host's mDNS socket.)
109    fn poll_write(&mut self) -> Option<Self::Wout> {
110        if let Some(mdns_conn) = &mut self.mdns {
111            while let Some(msg) = mdns_conn.poll_write() {
112                self.write_outs.push_back(msg);
113            }
114        }
115
116        self.write_outs.pop_front()
117    }
118
119    fn handle_event(&mut self, _evt: ()) -> std::result::Result<(), Self::Error> {
120        Ok(())
121    }
122
123    fn poll_event(&mut self) -> Option<Self::Eout> {
124        self.event_outs.pop_front()
125    }
126
127    fn handle_timeout(&mut self, now: Self::Time) -> std::result::Result<(), Self::Error> {
128        self.clock = self.clock.max(now);
129        if let Some(mdns_conn) = &mut self.mdns {
130            let _ = mdns_conn.handle_timeout(now);
131        }
132        let remote_candidates = self.drain_mdns_events(now);
133        self.trigger_request_connectivity_check(remote_candidates);
134
135        // Requests that were answered before the peer's credentials arrived (RFC 8445
136        // Section 7.3) are processed now that there are some.
137        if !self.early_requests.is_empty() {
138            self.process_early_requests(now);
139        }
140
141        // The path an ICE restart left in use keeps its consent checks, with or without the
142        // peer's new credentials.
143        self.maintain_previous_generation(now);
144
145        if self.ice_deadline().is_some_and(|deadline| deadline <= now) {
146            self.contact(now);
147        }
148        Ok(())
149    }
150
151    fn poll_timeout(&mut self) -> Option<Self::Time> {
152        let mdns_timeout = if let Some(mdns_conn) = &mut self.mdns {
153            mdns_conn.poll_timeout()
154        } else {
155            None
156        };
157
158        let ice_timeout = self.ice_deadline();
159
160        // This treats the options as a collection and picks the minimum
161        [
162            mdns_timeout,
163            ice_timeout,
164            self.previous_generation_deadline(),
165        ]
166        .into_iter()
167        .flatten()
168        .min()
169    }
170
171    fn close(&mut self) -> std::result::Result<(), Self::Error> {
172        self.set_selected_pair(None, None);
173        self.delete_all_candidates(false);
174        self.update_connection_state(None, ConnectionState::Closed);
175        if let Some(mdns_conn) = &mut self.mdns {
176            mdns_conn.close()?;
177        }
178        Ok(())
179    }
180}