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.read_datagram(msg, None)
45 }
46
47 fn poll_read(&mut self) -> Option<Self::Rout> {
48 None
49 }
50
51 fn handle_write(&mut self, _msg: ()) -> std::result::Result<(), Self::Error> {
52 Ok(())
53 }
54
55 /// The next datagram to send. `transport.local_addr` is the base of the local candidate
56 /// it leaves from (RFC 8445 Section 6.1.2): a host candidate's address (send it from that
57 /// socket), or a relayed candidate's relayed address, in which case it goes through that
58 /// candidate's TURN allocation (a Send indication or ChannelData to `peer_addr`), not
59 /// directly from a socket. (mDNS datagrams leave from port 5353, the host's mDNS socket.)
60 fn poll_write(&mut self) -> Option<Self::Wout> {
61 if let Some(mdns_conn) = &mut self.mdns {
62 while let Some(msg) = mdns_conn.poll_write() {
63 self.write_outs.push_back(msg);
64 }
65 }
66
67 self.write_outs.pop_front()
68 }
69
70 fn handle_event(&mut self, _evt: ()) -> std::result::Result<(), Self::Error> {
71 Ok(())
72 }
73
74 fn poll_event(&mut self) -> Option<Self::Eout> {
75 self.event_outs.pop_front()
76 }
77
78 fn handle_timeout(&mut self, now: Self::Time) -> std::result::Result<(), Self::Error> {
79 self.clock = self.clock.max(now);
80 if let Some(mdns_conn) = &mut self.mdns {
81 let _ = mdns_conn.handle_timeout(now);
82 }
83 let remote_candidates = self.drain_mdns_events(now);
84 self.trigger_request_connectivity_check(remote_candidates);
85
86 // Requests that were answered before the peer's credentials arrived (RFC 8445
87 // Section 7.3) are processed now that there are some.
88 if !self.early_requests.is_empty() {
89 self.process_early_requests(now);
90 }
91
92 // The path an ICE restart left in use keeps its consent checks, with or without the
93 // peer's new credentials.
94 self.maintain_previous_generation(now);
95
96 if self.ice_deadline().is_some_and(|deadline| deadline <= now) {
97 self.contact(now);
98 }
99 Ok(())
100 }
101
102 fn poll_timeout(&mut self) -> Option<Self::Time> {
103 let mdns_timeout = if let Some(mdns_conn) = &mut self.mdns {
104 mdns_conn.poll_timeout()
105 } else {
106 None
107 };
108
109 let ice_timeout = self.ice_deadline();
110
111 // This treats the options as a collection and picks the minimum
112 [
113 mdns_timeout,
114 ice_timeout,
115 self.previous_generation_deadline(),
116 ]
117 .into_iter()
118 .flatten()
119 .min()
120 }
121
122 fn close(&mut self) -> std::result::Result<(), Self::Error> {
123 self.set_selected_pair(None, None);
124 self.delete_all_candidates(false);
125 self.update_connection_state(None, ConnectionState::Closed);
126 if let Some(mdns_conn) = &mut self.mdns {
127 mdns_conn.close()?;
128 }
129 Ok(())
130 }
131}
132
133impl Agent {
134 /// `handle_read`, and, for a datagram of the mDNS socket, `destination`: the destination
135 /// address of its IP header, where the driver read it (`Agent::handle_mdns_datagram`).
136 pub(crate) fn read_datagram(
137 &mut self,
138 msg: TaggedBytesMut,
139 destination: Option<IpAddr>,
140 ) -> Result<()> {
141 self.clock = self.clock.max(msg.now);
142 // The embedder's address policy: a datagram from a source it refuses is dropped before
143 // anything reads it, as a firewall would drop it: no response, no peer-reflexive
144 // candidate, no consent, no pair (`AgentConfig::address_policy`).
145 if !self.remote_policy.allows_source(msg.transport.peer_addr) {
146 debug!(
147 "[{}]: dropped a datagram from {}: the address policy refuses the source",
148 self.get_name(),
149 msg.transport.peer_addr
150 );
151 return Ok(());
152 }
153 // mDNS arrives on the host's mDNS socket, the one bound to MDNS_PORT that this
154 // agent's queries leave from. A source port says nothing: anyone can send from 5353 to
155 // an ICE socket, and an answer taken from there could point a `.local` candidate at an
156 // address of the sender's choosing. Datagrams on ICE sockets are ICE traffic, whatever
157 // their source port.
158 // (Whatever arrives on the mDNS socket goes to the mDNS connection, from any source
159 // port: a query from another port is a legacy unicast query, which RFC 6762 Section
160 // 6.7 has answered by unicast; a response from another port is refused there. With
161 // `multicast_dns_destination_reported` the local address is the datagram's
162 // destination, the mDNS group's or the host's own.)
163 if msg.transport.local_addr.port() == MDNS_PORT
164 && self
165 .find_local_candidate(msg.transport.local_addr, msg.transport.transport_protocol)
166 .is_none()
167 {
168 let now = msg.now;
169 if let Some(mdns_conn) = &mut self.mdns {
170 match destination {
171 Some(destination) => mdns_conn.handle_datagram(msg, destination)?,
172 None => mdns_conn.handle_read(msg)?,
173 }
174 }
175 let remote_candidates = self.drain_mdns_events(now);
176 self.trigger_request_connectivity_check(remote_candidates);
177
178 Ok(())
179 } else if self.handle_previous_generation(&msg) {
180 // Consent traffic of the generation an ICE restart replaced, on the path that is
181 // still in use.
182 Ok(())
183 } else if let Some(local_index) =
184 self.find_local_candidate(msg.transport.local_addr, msg.transport.transport_protocol)
185 {
186 self.handle_inbound_candidate_msg(local_index, msg)
187 } else {
188 warn!(
189 "{}",
190 unmatched_local_address_log(self.get_name(), &msg.transport)
191 );
192 Err(Error::ErrUnhandledStunpacket)
193 }
194 }
195}