xref: /aosp_15_r20/external/webrtc/p2p/base/ice_transport_internal.h (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright 2016 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef P2P_BASE_ICE_TRANSPORT_INTERNAL_H_
12 #define P2P_BASE_ICE_TRANSPORT_INTERNAL_H_
13 
14 #include <stdint.h>
15 
16 #include <string>
17 #include <vector>
18 
19 #include "absl/strings/string_view.h"
20 #include "absl/types/optional.h"
21 #include "api/candidate.h"
22 #include "api/rtc_error.h"
23 #include "api/transport/enums.h"
24 #include "p2p/base/connection.h"
25 #include "p2p/base/packet_transport_internal.h"
26 #include "p2p/base/port.h"
27 #include "p2p/base/transport_description.h"
28 #include "rtc_base/network_constants.h"
29 #include "rtc_base/system/rtc_export.h"
30 #include "rtc_base/third_party/sigslot/sigslot.h"
31 #include "rtc_base/time_utils.h"
32 
33 namespace cricket {
34 
35 struct IceTransportStats {
36   CandidateStatsList candidate_stats_list;
37   ConnectionInfos connection_infos;
38   // Number of times the selected candidate pair has changed
39   // Initially 0 and 1 once the first candidate pair has been selected.
40   // The counter is increase also when "unselecting" a connection.
41   uint32_t selected_candidate_pair_changes = 0;
42 
43   // Bytes/packets sent/received.
44   // note: Is not the same as sum(connection_infos.bytes_sent)
45   // as connections are created and destroyed while the ICE transport
46   // is alive.
47   uint64_t bytes_sent = 0;
48   uint64_t bytes_received = 0;
49   uint64_t packets_sent = 0;
50   uint64_t packets_received = 0;
51 
52   IceRole ice_role = ICEROLE_UNKNOWN;
53   std::string ice_local_username_fragment;
54   webrtc::IceTransportState ice_state = webrtc::IceTransportState::kNew;
55 };
56 
57 typedef std::vector<Candidate> Candidates;
58 
59 enum IceConnectionState {
60   kIceConnectionConnecting = 0,
61   kIceConnectionFailed,
62   kIceConnectionConnected,  // Writable, but still checking one or more
63                             // connections
64   kIceConnectionCompleted,
65 };
66 
67 // TODO(deadbeef): Unify with PeerConnectionInterface::IceConnectionState
68 // once /talk/ and /webrtc/ are combined, and also switch to ENUM_NAME naming
69 // style.
70 enum IceGatheringState {
71   kIceGatheringNew = 0,
72   kIceGatheringGathering,
73   kIceGatheringComplete,
74 };
75 
76 enum ContinualGatheringPolicy {
77   // All port allocator sessions will stop after a writable connection is found.
78   GATHER_ONCE = 0,
79   // The most recent port allocator session will keep on running.
80   GATHER_CONTINUALLY,
81 };
82 
83 // ICE Nomination mode.
84 enum class NominationMode {
85   REGULAR,         // Nominate once per ICE restart (Not implemented yet).
86   AGGRESSIVE,      // Nominate every connection except that it will behave as if
87                    // REGULAR when the remote is an ICE-LITE endpoint.
88   SEMI_AGGRESSIVE  // Our current implementation of the nomination algorithm.
89                    // The details are described in P2PTransportChannel.
90 };
91 
92 // Utility method that checks if various required Candidate fields are filled in
93 // and contain valid values. If conditions are not met, an RTCError with the
94 // appropriated error number and description is returned. If the configuration
95 // is valid RTCError::OK() is returned.
96 webrtc::RTCError VerifyCandidate(const Candidate& cand);
97 
98 // Runs through a list of cricket::Candidate instances and calls VerifyCandidate
99 // for each one, stopping on the first error encounted and returning that error
100 // value if so. On success returns RTCError::OK().
101 webrtc::RTCError VerifyCandidates(const Candidates& candidates);
102 
103 // Information about ICE configuration.
104 // TODO(deadbeef): Use absl::optional to represent unset values, instead of
105 // -1.
106 struct IceConfig {
107   // The ICE connection receiving timeout value in milliseconds.
108   absl::optional<int> receiving_timeout;
109   // Time interval in milliseconds to ping a backup connection when the ICE
110   // channel is strongly connected.
111   absl::optional<int> backup_connection_ping_interval;
112 
113   ContinualGatheringPolicy continual_gathering_policy = GATHER_ONCE;
114 
gather_continuallyIceConfig115   bool gather_continually() const {
116     return continual_gathering_policy == GATHER_CONTINUALLY;
117   }
118 
119   // Whether we should prioritize Relay/Relay candidate when nothing
120   // is writable yet.
121   bool prioritize_most_likely_candidate_pairs = false;
122 
123   // Writable connections are pinged at a slower rate once stablized.
124   absl::optional<int> stable_writable_connection_ping_interval;
125 
126   // If set to true, this means the ICE transport should presume TURN-to-TURN
127   // candidate pairs will succeed, even before a binding response is received.
128   bool presume_writable_when_fully_relayed = false;
129 
130   // If true, after the ICE transport type (as the candidate filter used by the
131   // port allocator) is changed such that new types of ICE candidates are
132   // allowed by the new filter, e.g. from CF_RELAY to CF_ALL, candidates that
133   // have been gathered by the ICE transport but filtered out and not signaled
134   // to the upper layers, will be surfaced.
135   bool surface_ice_candidates_on_ice_transport_type_changed = false;
136 
137   // Interval to check on all networks and to perform ICE regathering on any
138   // active network having no connection on it.
139   absl::optional<int> regather_on_failed_networks_interval;
140 
141   // The time period in which we will not switch the selected connection
142   // when a new connection becomes receiving but the selected connection is not
143   // in case that the selected connection may become receiving soon.
144   absl::optional<int> receiving_switching_delay;
145 
146   // TODO(honghaiz): Change the default to regular nomination.
147   // Default nomination mode if the remote does not support renomination.
148   NominationMode default_nomination_mode = NominationMode::SEMI_AGGRESSIVE;
149 
150   // The interval in milliseconds at which ICE checks (STUN pings) will be sent
151   // for a candidate pair when it is both writable and receiving (strong
152   // connectivity). This parameter overrides the default value given by
153   // `STRONG_PING_INTERVAL` in p2ptransport.h if set.
154   absl::optional<int> ice_check_interval_strong_connectivity;
155   // The interval in milliseconds at which ICE checks (STUN pings) will be sent
156   // for a candidate pair when it is either not writable or not receiving (weak
157   // connectivity). This parameter overrides the default value given by
158   // `WEAK_PING_INTERVAL` in p2ptransport.h if set.
159   absl::optional<int> ice_check_interval_weak_connectivity;
160   // ICE checks (STUN pings) will not be sent at higher rate (lower interval)
161   // than this, no matter what other settings there are.
162   // Measure in milliseconds.
163   //
164   // Note that this parameter overrides both the above check intervals for
165   // candidate pairs with strong or weak connectivity, if either of the above
166   // interval is shorter than the min interval.
167   absl::optional<int> ice_check_min_interval;
168   // The min time period for which a candidate pair must wait for response to
169   // connectivity checks before it becomes unwritable. This parameter
170   // overrides the default value given by `CONNECTION_WRITE_CONNECT_TIMEOUT`
171   // in port.h if set, when determining the writability of a candidate pair.
172   absl::optional<int> ice_unwritable_timeout;
173 
174   // The min number of connectivity checks that a candidate pair must sent
175   // without receiving response before it becomes unwritable. This parameter
176   // overrides the default value given by `CONNECTION_WRITE_CONNECT_FAILURES` in
177   // port.h if set, when determining the writability of a candidate pair.
178   absl::optional<int> ice_unwritable_min_checks;
179 
180   // The min time period for which a candidate pair must wait for response to
181   // connectivity checks it becomes inactive. This parameter overrides the
182   // default value given by `CONNECTION_WRITE_TIMEOUT` in port.h if set, when
183   // determining the writability of a candidate pair.
184   absl::optional<int> ice_inactive_timeout;
185 
186   // The interval in milliseconds at which STUN candidates will resend STUN
187   // binding requests to keep NAT bindings open.
188   absl::optional<int> stun_keepalive_interval;
189 
190   absl::optional<rtc::AdapterType> network_preference;
191 
192   webrtc::VpnPreference vpn_preference = webrtc::VpnPreference::kDefault;
193 
194   IceConfig();
195   IceConfig(int receiving_timeout_ms,
196             int backup_connection_ping_interval,
197             ContinualGatheringPolicy gathering_policy,
198             bool prioritize_most_likely_candidate_pairs,
199             int stable_writable_connection_ping_interval_ms,
200             bool presume_writable_when_fully_relayed,
201             int regather_on_failed_networks_interval_ms,
202             int receiving_switching_delay_ms);
203   ~IceConfig();
204 
205   // Helper getters for parameters with implementation-specific default value.
206   // By convention, parameters with default value are represented by
207   // absl::optional and setting a parameter to null restores its default value.
208   int receiving_timeout_or_default() const;
209   int backup_connection_ping_interval_or_default() const;
210   int stable_writable_connection_ping_interval_or_default() const;
211   int regather_on_failed_networks_interval_or_default() const;
212   int receiving_switching_delay_or_default() const;
213   int ice_check_interval_strong_connectivity_or_default() const;
214   int ice_check_interval_weak_connectivity_or_default() const;
215   int ice_check_min_interval_or_default() const;
216   int ice_unwritable_timeout_or_default() const;
217   int ice_unwritable_min_checks_or_default() const;
218   int ice_inactive_timeout_or_default() const;
219   int stun_keepalive_interval_or_default() const;
220 };
221 
222 // TODO(zhihuang): Replace this with
223 // PeerConnectionInterface::IceConnectionState.
224 enum class IceTransportState {
225   STATE_INIT,
226   STATE_CONNECTING,  // Will enter this state once a connection is created
227   STATE_COMPLETED,
228   STATE_FAILED
229 };
230 
231 // TODO(zhihuang): Remove this once it's no longer used in
232 // remoting/protocol/libjingle_transport_factory.cc
233 enum IceProtocolType {
234   ICEPROTO_RFC5245  // Standard RFC 5245 version of ICE.
235 };
236 
237 // IceTransportInternal is an internal abstract class that does ICE.
238 // Once the public interface is supported,
239 // (https://www.w3.org/TR/webrtc/#rtcicetransport)
240 // the IceTransportInterface will be split from this class.
241 class RTC_EXPORT IceTransportInternal : public rtc::PacketTransportInternal {
242  public:
243   IceTransportInternal();
244   ~IceTransportInternal() override;
245 
246   // TODO(bugs.webrtc.org/9308): Remove GetState once all uses have been
247   // migrated to GetIceTransportState.
248   virtual IceTransportState GetState() const = 0;
249   virtual webrtc::IceTransportState GetIceTransportState() const = 0;
250 
251   virtual int component() const = 0;
252 
253   virtual IceRole GetIceRole() const = 0;
254 
255   virtual void SetIceRole(IceRole role) = 0;
256 
257   virtual void SetIceTiebreaker(uint64_t tiebreaker) = 0;
258 
259   // TODO(zhihuang): Remove this once it's no longer called in
260   // remoting/protocol/libjingle_transport_factory.cc
SetIceProtocolType(IceProtocolType type)261   virtual void SetIceProtocolType(IceProtocolType type) {}
262 
263   virtual void SetIceCredentials(absl::string_view ice_ufrag,
264                                  absl::string_view ice_pwd);
265 
266   virtual void SetRemoteIceCredentials(absl::string_view ice_ufrag,
267                                        absl::string_view ice_pwd);
268 
269   // The ufrag and pwd in `ice_params` must be set
270   // before candidate gathering can start.
271   virtual void SetIceParameters(const IceParameters& ice_params) = 0;
272 
273   virtual void SetRemoteIceParameters(const IceParameters& ice_params) = 0;
274 
275   virtual void SetRemoteIceMode(IceMode mode) = 0;
276 
277   virtual void SetIceConfig(const IceConfig& config) = 0;
278 
279   // Start gathering candidates if not already started, or if an ICE restart
280   // occurred.
281   virtual void MaybeStartGathering() = 0;
282 
283   virtual void AddRemoteCandidate(const Candidate& candidate) = 0;
284 
285   virtual void RemoveRemoteCandidate(const Candidate& candidate) = 0;
286 
287   virtual void RemoveAllRemoteCandidates() = 0;
288 
289   virtual IceGatheringState gathering_state() const = 0;
290 
291   // Returns the current stats for this connection.
292   virtual bool GetStats(IceTransportStats* ice_transport_stats) = 0;
293 
294   // Returns RTT estimate over the currently active connection, or an empty
295   // absl::optional if there is none.
296   virtual absl::optional<int> GetRttEstimate() = 0;
297 
298   // TODO(qingsi): Remove this method once Chrome does not depend on it anymore.
299   virtual const Connection* selected_connection() const = 0;
300 
301   // Returns the selected candidate pair, or an empty absl::optional if there is
302   // none.
303   virtual absl::optional<const CandidatePair> GetSelectedCandidatePair()
304       const = 0;
305 
306   sigslot::signal1<IceTransportInternal*> SignalGatheringState;
307 
308   // Handles sending and receiving of candidates.
309   sigslot::signal2<IceTransportInternal*, const Candidate&>
310       SignalCandidateGathered;
311 
312   sigslot::signal2<IceTransportInternal*, const IceCandidateErrorEvent&>
313       SignalCandidateError;
314 
315   sigslot::signal2<IceTransportInternal*, const Candidates&>
316       SignalCandidatesRemoved;
317 
318   // Deprecated by PacketTransportInternal::SignalNetworkRouteChanged.
319   // This signal occurs when there is a change in the way that packets are
320   // being routed, i.e. to a different remote location. The candidate
321   // indicates where and how we are currently sending media.
322   // TODO(zhihuang): Update the Chrome remoting to use the new
323   // SignalNetworkRouteChanged.
324   sigslot::signal2<IceTransportInternal*, const Candidate&> SignalRouteChange;
325 
326   sigslot::signal1<const cricket::CandidatePairChangeEvent&>
327       SignalCandidatePairChanged;
328 
329   // Invoked when there is conflict in the ICE role between local and remote
330   // agents.
331   sigslot::signal1<IceTransportInternal*> SignalRoleConflict;
332 
333   // Emitted whenever the transport state changed.
334   // TODO(bugs.webrtc.org/9308): Remove once all uses have migrated to the new
335   // IceTransportState.
336   sigslot::signal1<IceTransportInternal*> SignalStateChanged;
337 
338   // Emitted whenever the new standards-compliant transport state changed.
339   sigslot::signal1<IceTransportInternal*> SignalIceTransportStateChanged;
340 
341   // Invoked when the transport is being destroyed.
342   sigslot::signal1<IceTransportInternal*> SignalDestroyed;
343 };
344 
345 }  // namespace cricket
346 
347 #endif  // P2P_BASE_ICE_TRANSPORT_INTERNAL_H_
348