p2p_transport_channel.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. /*
  2. * Copyright 2004 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. // P2PTransportChannel wraps up the state management of the connection between
  11. // two P2P clients. Clients have candidate ports for connecting, and
  12. // connections which are combinations of candidates from each end (Alice and
  13. // Bob each have candidates, one candidate from Alice and one candidate from
  14. // Bob are used to make a connection, repeat to make many connections).
  15. //
  16. // When all of the available connections become invalid (non-writable), we
  17. // kick off a process of determining more candidates and more connections.
  18. //
  19. #ifndef P2P_BASE_P2P_TRANSPORT_CHANNEL_H_
  20. #define P2P_BASE_P2P_TRANSPORT_CHANNEL_H_
  21. #include <algorithm>
  22. #include <map>
  23. #include <memory>
  24. #include <set>
  25. #include <string>
  26. #include <vector>
  27. #include "api/async_resolver_factory.h"
  28. #include "api/candidate.h"
  29. #include "api/rtc_error.h"
  30. #include "logging/rtc_event_log/events/rtc_event_ice_candidate_pair_config.h"
  31. #include "logging/rtc_event_log/ice_logger.h"
  32. #include "p2p/base/candidate_pair_interface.h"
  33. #include "p2p/base/ice_controller_factory_interface.h"
  34. #include "p2p/base/ice_controller_interface.h"
  35. #include "p2p/base/ice_transport_internal.h"
  36. #include "p2p/base/p2p_constants.h"
  37. #include "p2p/base/p2p_transport_channel_ice_field_trials.h"
  38. #include "p2p/base/port_allocator.h"
  39. #include "p2p/base/port_interface.h"
  40. #include "p2p/base/regathering_controller.h"
  41. #include "rtc_base/async_invoker.h"
  42. #include "rtc_base/async_packet_socket.h"
  43. #include "rtc_base/constructor_magic.h"
  44. #include "rtc_base/strings/string_builder.h"
  45. #include "rtc_base/system/rtc_export.h"
  46. #include "rtc_base/third_party/sigslot/sigslot.h"
  47. #include "rtc_base/thread_annotations.h"
  48. namespace webrtc {
  49. class RtcEventLog;
  50. } // namespace webrtc
  51. namespace cricket {
  52. // Enum for UMA metrics, used to record whether the channel is
  53. // connected/connecting/disconnected when ICE restart happens.
  54. enum class IceRestartState { CONNECTING, CONNECTED, DISCONNECTED, MAX_VALUE };
  55. static const int MIN_PINGS_AT_WEAK_PING_INTERVAL = 3;
  56. bool IceCredentialsChanged(const std::string& old_ufrag,
  57. const std::string& old_pwd,
  58. const std::string& new_ufrag,
  59. const std::string& new_pwd);
  60. // Adds the port on which the candidate originated.
  61. class RemoteCandidate : public Candidate {
  62. public:
  63. RemoteCandidate(const Candidate& c, PortInterface* origin_port)
  64. : Candidate(c), origin_port_(origin_port) {}
  65. PortInterface* origin_port() { return origin_port_; }
  66. private:
  67. PortInterface* origin_port_;
  68. };
  69. // P2PTransportChannel manages the candidates and connection process to keep
  70. // two P2P clients connected to each other.
  71. class RTC_EXPORT P2PTransportChannel : public IceTransportInternal {
  72. public:
  73. // For testing only.
  74. // TODO(zstein): Remove once AsyncResolverFactory is required.
  75. P2PTransportChannel(const std::string& transport_name,
  76. int component,
  77. PortAllocator* allocator);
  78. P2PTransportChannel(
  79. const std::string& transport_name,
  80. int component,
  81. PortAllocator* allocator,
  82. webrtc::AsyncResolverFactory* async_resolver_factory,
  83. webrtc::RtcEventLog* event_log = nullptr,
  84. IceControllerFactoryInterface* ice_controller_factory = nullptr);
  85. ~P2PTransportChannel() override;
  86. // From TransportChannelImpl:
  87. IceTransportState GetState() const override;
  88. webrtc::IceTransportState GetIceTransportState() const override;
  89. const std::string& transport_name() const override;
  90. int component() const override;
  91. bool writable() const override;
  92. bool receiving() const override;
  93. void SetIceRole(IceRole role) override;
  94. IceRole GetIceRole() const override;
  95. void SetIceTiebreaker(uint64_t tiebreaker) override;
  96. void SetIceParameters(const IceParameters& ice_params) override;
  97. void SetRemoteIceParameters(const IceParameters& ice_params) override;
  98. void SetRemoteIceMode(IceMode mode) override;
  99. // TODO(deadbeef): Deprecated. Remove when Chromium's
  100. // IceTransportChannel does not depend on this.
  101. void Connect() {}
  102. void MaybeStartGathering() override;
  103. IceGatheringState gathering_state() const override;
  104. void ResolveHostnameCandidate(const Candidate& candidate);
  105. void AddRemoteCandidate(const Candidate& candidate) override;
  106. void RemoveRemoteCandidate(const Candidate& candidate) override;
  107. void RemoveAllRemoteCandidates() override;
  108. // Sets the parameters in IceConfig. We do not set them blindly. Instead, we
  109. // only update the parameter if it is considered set in |config|. For example,
  110. // a negative value of receiving_timeout will be considered "not set" and we
  111. // will not use it to update the respective parameter in |config_|.
  112. // TODO(deadbeef): Use absl::optional instead of negative values.
  113. void SetIceConfig(const IceConfig& config) override;
  114. const IceConfig& config() const;
  115. static webrtc::RTCError ValidateIceConfig(const IceConfig& config);
  116. // From TransportChannel:
  117. int SendPacket(const char* data,
  118. size_t len,
  119. const rtc::PacketOptions& options,
  120. int flags) override;
  121. int SetOption(rtc::Socket::Option opt, int value) override;
  122. bool GetOption(rtc::Socket::Option opt, int* value) override;
  123. int GetError() override;
  124. bool GetStats(IceTransportStats* ice_transport_stats) override;
  125. absl::optional<int> GetRttEstimate() override;
  126. const Connection* selected_connection() const override;
  127. absl::optional<const CandidatePair> GetSelectedCandidatePair() const override;
  128. // TODO(honghaiz): Remove this method once the reference of it in
  129. // Chromoting is removed.
  130. const Connection* best_connection() const {
  131. RTC_DCHECK_RUN_ON(network_thread_);
  132. return selected_connection_;
  133. }
  134. void set_incoming_only(bool value) {
  135. RTC_DCHECK_RUN_ON(network_thread_);
  136. incoming_only_ = value;
  137. }
  138. // Note: These are only for testing purpose.
  139. // |ports_| and |pruned_ports| should not be changed from outside.
  140. const std::vector<PortInterface*>& ports() {
  141. RTC_DCHECK_RUN_ON(network_thread_);
  142. return ports_;
  143. }
  144. const std::vector<PortInterface*>& pruned_ports() {
  145. RTC_DCHECK_RUN_ON(network_thread_);
  146. return pruned_ports_;
  147. }
  148. IceMode remote_ice_mode() const {
  149. RTC_DCHECK_RUN_ON(network_thread_);
  150. return remote_ice_mode_;
  151. }
  152. void PruneAllPorts();
  153. int check_receiving_interval() const;
  154. absl::optional<rtc::NetworkRoute> network_route() const override;
  155. // Helper method used only in unittest.
  156. rtc::DiffServCodePoint DefaultDscpValue() const;
  157. // Public for unit tests.
  158. Connection* FindNextPingableConnection();
  159. void MarkConnectionPinged(Connection* conn);
  160. // Public for unit tests.
  161. rtc::ArrayView<Connection*> connections() const;
  162. // Public for unit tests.
  163. PortAllocatorSession* allocator_session() const {
  164. RTC_DCHECK_RUN_ON(network_thread_);
  165. if (allocator_sessions_.empty()) {
  166. return nullptr;
  167. }
  168. return allocator_sessions_.back().get();
  169. }
  170. // Public for unit tests.
  171. const std::vector<RemoteCandidate>& remote_candidates() const {
  172. RTC_DCHECK_RUN_ON(network_thread_);
  173. return remote_candidates_;
  174. }
  175. std::string ToString() const {
  176. RTC_DCHECK_RUN_ON(network_thread_);
  177. const std::string RECEIVING_ABBREV[2] = {"_", "R"};
  178. const std::string WRITABLE_ABBREV[2] = {"_", "W"};
  179. rtc::StringBuilder ss;
  180. ss << "Channel[" << transport_name_ << "|" << component_ << "|"
  181. << RECEIVING_ABBREV[receiving_] << WRITABLE_ABBREV[writable_] << "]";
  182. return ss.Release();
  183. }
  184. private:
  185. rtc::Thread* thread() const { return network_thread_; }
  186. bool IsGettingPorts() {
  187. RTC_DCHECK_RUN_ON(network_thread_);
  188. return allocator_session()->IsGettingPorts();
  189. }
  190. // Returns true if it's possible to send packets on |connection|.
  191. bool ReadyToSend(Connection* connection) const;
  192. bool PresumedWritable(const Connection* conn) const;
  193. void UpdateConnectionStates();
  194. void RequestSortAndStateUpdate(IceControllerEvent reason_to_sort);
  195. // Start pinging if we haven't already started, and we now have a connection
  196. // that's pingable.
  197. void MaybeStartPinging();
  198. void SortConnectionsAndUpdateState(IceControllerEvent reason_to_sort);
  199. void SortConnections();
  200. void SortConnectionsIfNeeded();
  201. void SwitchSelectedConnection(Connection* conn, IceControllerEvent reason);
  202. void UpdateState();
  203. void HandleAllTimedOut();
  204. void MaybeStopPortAllocatorSessions();
  205. // ComputeIceTransportState computes the RTCIceTransportState as described in
  206. // https://w3c.github.io/webrtc-pc/#dom-rtcicetransportstate. ComputeState
  207. // computes the value we currently export as RTCIceTransportState.
  208. // TODO(bugs.webrtc.org/9308): Remove ComputeState once it's no longer used.
  209. IceTransportState ComputeState() const;
  210. webrtc::IceTransportState ComputeIceTransportState() const;
  211. bool CreateConnections(const Candidate& remote_candidate,
  212. PortInterface* origin_port);
  213. bool CreateConnection(PortInterface* port,
  214. const Candidate& remote_candidate,
  215. PortInterface* origin_port);
  216. bool FindConnection(const Connection* connection) const;
  217. uint32_t GetRemoteCandidateGeneration(const Candidate& candidate);
  218. bool IsDuplicateRemoteCandidate(const Candidate& candidate);
  219. void RememberRemoteCandidate(const Candidate& remote_candidate,
  220. PortInterface* origin_port);
  221. void PingConnection(Connection* conn);
  222. void AddAllocatorSession(std::unique_ptr<PortAllocatorSession> session);
  223. void AddConnection(Connection* connection);
  224. void OnPortReady(PortAllocatorSession* session, PortInterface* port);
  225. void OnPortsPruned(PortAllocatorSession* session,
  226. const std::vector<PortInterface*>& ports);
  227. void OnCandidatesReady(PortAllocatorSession* session,
  228. const std::vector<Candidate>& candidates);
  229. void OnCandidateError(PortAllocatorSession* session,
  230. const IceCandidateErrorEvent& event);
  231. void OnCandidatesRemoved(PortAllocatorSession* session,
  232. const std::vector<Candidate>& candidates);
  233. void OnCandidatesAllocationDone(PortAllocatorSession* session);
  234. void OnUnknownAddress(PortInterface* port,
  235. const rtc::SocketAddress& addr,
  236. ProtocolType proto,
  237. IceMessage* stun_msg,
  238. const std::string& remote_username,
  239. bool port_muxed);
  240. void OnCandidateFilterChanged(uint32_t prev_filter, uint32_t cur_filter);
  241. // When a port is destroyed, remove it from both lists |ports_|
  242. // and |pruned_ports_|.
  243. void OnPortDestroyed(PortInterface* port);
  244. // When pruning a port, move it from |ports_| to |pruned_ports_|.
  245. // Returns true if the port is found and removed from |ports_|.
  246. bool PrunePort(PortInterface* port);
  247. void OnRoleConflict(PortInterface* port);
  248. void OnConnectionStateChange(Connection* connection);
  249. void OnReadPacket(Connection* connection,
  250. const char* data,
  251. size_t len,
  252. int64_t packet_time_us);
  253. void OnSentPacket(const rtc::SentPacket& sent_packet);
  254. void OnReadyToSend(Connection* connection);
  255. void OnConnectionDestroyed(Connection* connection);
  256. void OnNominated(Connection* conn);
  257. void CheckAndPing();
  258. void LogCandidatePairConfig(Connection* conn,
  259. webrtc::IceCandidatePairConfigType type);
  260. uint32_t GetNominationAttr(Connection* conn) const;
  261. bool GetUseCandidateAttr(Connection* conn) const;
  262. // Returns true if the new_connection is selected for transmission.
  263. bool MaybeSwitchSelectedConnection(Connection* new_connection,
  264. IceControllerEvent reason);
  265. bool MaybeSwitchSelectedConnection(
  266. IceControllerEvent reason,
  267. IceControllerInterface::SwitchResult result);
  268. void PruneConnections();
  269. // Returns the latest remote ICE parameters or nullptr if there are no remote
  270. // ICE parameters yet.
  271. IceParameters* remote_ice() {
  272. RTC_DCHECK_RUN_ON(network_thread_);
  273. return remote_ice_parameters_.empty() ? nullptr
  274. : &remote_ice_parameters_.back();
  275. }
  276. // Returns the remote IceParameters and generation that match |ufrag|
  277. // if found, and returns nullptr otherwise.
  278. const IceParameters* FindRemoteIceFromUfrag(const std::string& ufrag,
  279. uint32_t* generation);
  280. // Returns the index of the latest remote ICE parameters, or 0 if no remote
  281. // ICE parameters have been received.
  282. uint32_t remote_ice_generation() {
  283. RTC_DCHECK_RUN_ON(network_thread_);
  284. return remote_ice_parameters_.empty()
  285. ? 0
  286. : static_cast<uint32_t>(remote_ice_parameters_.size() - 1);
  287. }
  288. // Indicates if the given local port has been pruned.
  289. bool IsPortPruned(const Port* port) const;
  290. // Indicates if the given remote candidate has been pruned.
  291. bool IsRemoteCandidatePruned(const Candidate& cand) const;
  292. // Sets the writable state, signaling if necessary.
  293. void SetWritable(bool writable);
  294. // Sets the receiving state, signaling if necessary.
  295. void SetReceiving(bool receiving);
  296. // Clears the address and the related address fields of a local candidate to
  297. // avoid IP leakage. This is applicable in several scenarios as commented in
  298. // |PortAllocator::SanitizeCandidate|.
  299. Candidate SanitizeLocalCandidate(const Candidate& c) const;
  300. // Clears the address field of a remote candidate to avoid IP leakage. This is
  301. // applicable in the following scenarios:
  302. // 1. mDNS candidates are received.
  303. // 2. Peer-reflexive remote candidates.
  304. Candidate SanitizeRemoteCandidate(const Candidate& c) const;
  305. // Cast a Connection returned from IceController and verify that it exists.
  306. // (P2P owns all Connections, and only gives const pointers to IceController,
  307. // see IceControllerInterface).
  308. Connection* FromIceController(const Connection* conn) {
  309. // Verify that IceController does not return a connection
  310. // that we have destroyed.
  311. RTC_DCHECK(FindConnection(conn));
  312. return const_cast<Connection*>(conn);
  313. }
  314. int64_t ComputeEstimatedDisconnectedTimeMs(int64_t now,
  315. Connection* old_connection);
  316. std::string transport_name_ RTC_GUARDED_BY(network_thread_);
  317. int component_ RTC_GUARDED_BY(network_thread_);
  318. PortAllocator* allocator_ RTC_GUARDED_BY(network_thread_);
  319. webrtc::AsyncResolverFactory* async_resolver_factory_
  320. RTC_GUARDED_BY(network_thread_);
  321. rtc::Thread* network_thread_;
  322. bool incoming_only_ RTC_GUARDED_BY(network_thread_);
  323. int error_ RTC_GUARDED_BY(network_thread_);
  324. std::vector<std::unique_ptr<PortAllocatorSession>> allocator_sessions_
  325. RTC_GUARDED_BY(network_thread_);
  326. // |ports_| contains ports that are used to form new connections when
  327. // new remote candidates are added.
  328. std::vector<PortInterface*> ports_ RTC_GUARDED_BY(network_thread_);
  329. // |pruned_ports_| contains ports that have been removed from |ports_| and
  330. // are not being used to form new connections, but that aren't yet destroyed.
  331. // They may have existing connections, and they still fire signals such as
  332. // SignalUnknownAddress.
  333. std::vector<PortInterface*> pruned_ports_ RTC_GUARDED_BY(network_thread_);
  334. Connection* selected_connection_ RTC_GUARDED_BY(network_thread_) = nullptr;
  335. std::vector<RemoteCandidate> remote_candidates_
  336. RTC_GUARDED_BY(network_thread_);
  337. bool sort_dirty_ RTC_GUARDED_BY(
  338. network_thread_); // indicates whether another sort is needed right now
  339. bool had_connection_ RTC_GUARDED_BY(network_thread_) =
  340. false; // if connections_ has ever been nonempty
  341. typedef std::map<rtc::Socket::Option, int> OptionMap;
  342. OptionMap options_ RTC_GUARDED_BY(network_thread_);
  343. IceParameters ice_parameters_ RTC_GUARDED_BY(network_thread_);
  344. std::vector<IceParameters> remote_ice_parameters_
  345. RTC_GUARDED_BY(network_thread_);
  346. IceMode remote_ice_mode_ RTC_GUARDED_BY(network_thread_);
  347. IceRole ice_role_ RTC_GUARDED_BY(network_thread_);
  348. uint64_t tiebreaker_ RTC_GUARDED_BY(network_thread_);
  349. IceGatheringState gathering_state_ RTC_GUARDED_BY(network_thread_);
  350. std::unique_ptr<webrtc::BasicRegatheringController> regathering_controller_
  351. RTC_GUARDED_BY(network_thread_);
  352. int64_t last_ping_sent_ms_ RTC_GUARDED_BY(network_thread_) = 0;
  353. int weak_ping_interval_ RTC_GUARDED_BY(network_thread_) = WEAK_PING_INTERVAL;
  354. // TODO(jonasolsson): Remove state_ and rename standardized_state_ once state_
  355. // is no longer used to compute the ICE connection state.
  356. IceTransportState state_ RTC_GUARDED_BY(network_thread_) =
  357. IceTransportState::STATE_INIT;
  358. webrtc::IceTransportState standardized_state_
  359. RTC_GUARDED_BY(network_thread_) = webrtc::IceTransportState::kNew;
  360. IceConfig config_ RTC_GUARDED_BY(network_thread_);
  361. int last_sent_packet_id_ RTC_GUARDED_BY(network_thread_) =
  362. -1; // -1 indicates no packet was sent before.
  363. bool started_pinging_ RTC_GUARDED_BY(network_thread_) = false;
  364. // The value put in the "nomination" attribute for the next nominated
  365. // connection. A zero-value indicates the connection will not be nominated.
  366. uint32_t nomination_ RTC_GUARDED_BY(network_thread_) = 0;
  367. bool receiving_ RTC_GUARDED_BY(network_thread_) = false;
  368. bool writable_ RTC_GUARDED_BY(network_thread_) = false;
  369. bool has_been_writable_ RTC_GUARDED_BY(network_thread_) =
  370. false; // if writable_ has ever been true
  371. rtc::AsyncInvoker invoker_ RTC_GUARDED_BY(network_thread_);
  372. absl::optional<rtc::NetworkRoute> network_route_
  373. RTC_GUARDED_BY(network_thread_);
  374. webrtc::IceEventLog ice_event_log_ RTC_GUARDED_BY(network_thread_);
  375. std::unique_ptr<IceControllerInterface> ice_controller_
  376. RTC_GUARDED_BY(network_thread_);
  377. struct CandidateAndResolver final {
  378. CandidateAndResolver(const Candidate& candidate,
  379. rtc::AsyncResolverInterface* resolver);
  380. ~CandidateAndResolver();
  381. Candidate candidate_;
  382. rtc::AsyncResolverInterface* resolver_;
  383. };
  384. std::vector<CandidateAndResolver> resolvers_ RTC_GUARDED_BY(network_thread_);
  385. void FinishAddingRemoteCandidate(const Candidate& new_remote_candidate);
  386. void OnCandidateResolved(rtc::AsyncResolverInterface* resolver);
  387. void AddRemoteCandidateWithResolver(Candidate candidate,
  388. rtc::AsyncResolverInterface* resolver);
  389. // Number of times the selected_connection_ has been modified.
  390. uint32_t selected_candidate_pair_changes_ = 0;
  391. // When was last data received on a existing connection,
  392. // from connection->last_data_received() that uses rtc::TimeMillis().
  393. int64_t last_data_received_ms_ = 0;
  394. IceFieldTrials field_trials_;
  395. RTC_DISALLOW_COPY_AND_ASSIGN(P2PTransportChannel);
  396. };
  397. } // namespace cricket
  398. #endif // P2P_BASE_P2P_TRANSPORT_CHANNEL_H_