basic_port_allocator.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. #ifndef P2P_CLIENT_BASIC_PORT_ALLOCATOR_H_
  11. #define P2P_CLIENT_BASIC_PORT_ALLOCATOR_H_
  12. #include <memory>
  13. #include <string>
  14. #include <vector>
  15. #include "api/turn_customizer.h"
  16. #include "p2p/base/port_allocator.h"
  17. #include "p2p/client/relay_port_factory_interface.h"
  18. #include "p2p/client/turn_port_factory.h"
  19. #include "rtc_base/checks.h"
  20. #include "rtc_base/network.h"
  21. #include "rtc_base/system/rtc_export.h"
  22. #include "rtc_base/thread.h"
  23. namespace cricket {
  24. class RTC_EXPORT BasicPortAllocator : public PortAllocator {
  25. public:
  26. // note: The (optional) relay_port_factory is owned by caller
  27. // and must have a life time that exceeds that of BasicPortAllocator.
  28. BasicPortAllocator(rtc::NetworkManager* network_manager,
  29. rtc::PacketSocketFactory* socket_factory,
  30. webrtc::TurnCustomizer* customizer = nullptr,
  31. RelayPortFactoryInterface* relay_port_factory = nullptr);
  32. explicit BasicPortAllocator(rtc::NetworkManager* network_manager);
  33. BasicPortAllocator(rtc::NetworkManager* network_manager,
  34. const ServerAddresses& stun_servers);
  35. BasicPortAllocator(rtc::NetworkManager* network_manager,
  36. rtc::PacketSocketFactory* socket_factory,
  37. const ServerAddresses& stun_servers);
  38. ~BasicPortAllocator() override;
  39. // Set to kDefaultNetworkIgnoreMask by default.
  40. void SetNetworkIgnoreMask(int network_ignore_mask) override;
  41. int network_ignore_mask() const {
  42. CheckRunOnValidThreadIfInitialized();
  43. return network_ignore_mask_;
  44. }
  45. rtc::NetworkManager* network_manager() const {
  46. CheckRunOnValidThreadIfInitialized();
  47. return network_manager_;
  48. }
  49. // If socket_factory() is set to NULL each PortAllocatorSession
  50. // creates its own socket factory.
  51. rtc::PacketSocketFactory* socket_factory() {
  52. CheckRunOnValidThreadIfInitialized();
  53. return socket_factory_;
  54. }
  55. PortAllocatorSession* CreateSessionInternal(
  56. const std::string& content_name,
  57. int component,
  58. const std::string& ice_ufrag,
  59. const std::string& ice_pwd) override;
  60. // Convenience method that adds a TURN server to the configuration.
  61. void AddTurnServer(const RelayServerConfig& turn_server);
  62. RelayPortFactoryInterface* relay_port_factory() {
  63. CheckRunOnValidThreadIfInitialized();
  64. return relay_port_factory_;
  65. }
  66. private:
  67. void OnIceRegathering(PortAllocatorSession* session,
  68. IceRegatheringReason reason);
  69. // This function makes sure that relay_port_factory_ is set properly.
  70. void InitRelayPortFactory(RelayPortFactoryInterface* relay_port_factory);
  71. bool MdnsObfuscationEnabled() const override;
  72. rtc::NetworkManager* network_manager_;
  73. rtc::PacketSocketFactory* socket_factory_;
  74. int network_ignore_mask_ = rtc::kDefaultNetworkIgnoreMask;
  75. // This is the factory being used.
  76. RelayPortFactoryInterface* relay_port_factory_;
  77. // This instance is created if caller does pass a factory.
  78. std::unique_ptr<RelayPortFactoryInterface> default_relay_port_factory_;
  79. };
  80. struct PortConfiguration;
  81. class AllocationSequence;
  82. enum class SessionState {
  83. GATHERING, // Actively allocating ports and gathering candidates.
  84. CLEARED, // Current allocation process has been stopped but may start
  85. // new ones.
  86. STOPPED // This session has completely stopped, no new allocation
  87. // process will be started.
  88. };
  89. class RTC_EXPORT BasicPortAllocatorSession
  90. : public PortAllocatorSession,
  91. public rtc::MessageHandlerAutoCleanup {
  92. public:
  93. BasicPortAllocatorSession(BasicPortAllocator* allocator,
  94. const std::string& content_name,
  95. int component,
  96. const std::string& ice_ufrag,
  97. const std::string& ice_pwd);
  98. ~BasicPortAllocatorSession() override;
  99. virtual BasicPortAllocator* allocator();
  100. rtc::Thread* network_thread() { return network_thread_; }
  101. rtc::PacketSocketFactory* socket_factory() { return socket_factory_; }
  102. // If the new filter allows new types of candidates compared to the previous
  103. // filter, gathered candidates that were discarded because of not matching the
  104. // previous filter will be signaled if they match the new one.
  105. //
  106. // We do not perform any regathering since the port allocator flags decide
  107. // the type of candidates to gather and the candidate filter only controls the
  108. // signaling of candidates. As a result, with the candidate filter changed
  109. // alone, all newly allowed candidates for signaling should already be
  110. // gathered by the respective cricket::Port.
  111. void SetCandidateFilter(uint32_t filter) override;
  112. void StartGettingPorts() override;
  113. void StopGettingPorts() override;
  114. void ClearGettingPorts() override;
  115. bool IsGettingPorts() override;
  116. bool IsCleared() const override;
  117. bool IsStopped() const override;
  118. // These will all be cricket::Ports.
  119. std::vector<PortInterface*> ReadyPorts() const override;
  120. std::vector<Candidate> ReadyCandidates() const override;
  121. bool CandidatesAllocationDone() const override;
  122. void RegatherOnFailedNetworks() override;
  123. void GetCandidateStatsFromReadyPorts(
  124. CandidateStatsList* candidate_stats_list) const override;
  125. void SetStunKeepaliveIntervalForReadyPorts(
  126. const absl::optional<int>& stun_keepalive_interval) override;
  127. void PruneAllPorts() override;
  128. protected:
  129. void UpdateIceParametersInternal() override;
  130. // Starts the process of getting the port configurations.
  131. virtual void GetPortConfigurations();
  132. // Adds a port configuration that is now ready. Once we have one for each
  133. // network (or a timeout occurs), we will start allocating ports.
  134. virtual void ConfigReady(PortConfiguration* config);
  135. // MessageHandler. Can be overriden if message IDs do not conflict.
  136. void OnMessage(rtc::Message* message) override;
  137. private:
  138. class PortData {
  139. public:
  140. enum State {
  141. STATE_INPROGRESS, // Still gathering candidates.
  142. STATE_COMPLETE, // All candidates allocated and ready for process.
  143. STATE_ERROR, // Error in gathering candidates.
  144. STATE_PRUNED // Pruned by higher priority ports on the same network
  145. // interface. Only TURN ports may be pruned.
  146. };
  147. PortData() {}
  148. PortData(Port* port, AllocationSequence* seq)
  149. : port_(port), sequence_(seq) {}
  150. Port* port() const { return port_; }
  151. AllocationSequence* sequence() const { return sequence_; }
  152. bool has_pairable_candidate() const { return has_pairable_candidate_; }
  153. State state() const { return state_; }
  154. bool complete() const { return state_ == STATE_COMPLETE; }
  155. bool error() const { return state_ == STATE_ERROR; }
  156. bool pruned() const { return state_ == STATE_PRUNED; }
  157. bool inprogress() const { return state_ == STATE_INPROGRESS; }
  158. // Returns true if this port is ready to be used.
  159. bool ready() const {
  160. return has_pairable_candidate_ && state_ != STATE_ERROR &&
  161. state_ != STATE_PRUNED;
  162. }
  163. // Sets the state to "PRUNED" and prunes the Port.
  164. void Prune() {
  165. state_ = STATE_PRUNED;
  166. if (port()) {
  167. port()->Prune();
  168. }
  169. }
  170. void set_has_pairable_candidate(bool has_pairable_candidate) {
  171. if (has_pairable_candidate) {
  172. RTC_DCHECK(state_ == STATE_INPROGRESS);
  173. }
  174. has_pairable_candidate_ = has_pairable_candidate;
  175. }
  176. void set_state(State state) {
  177. RTC_DCHECK(state != STATE_ERROR || state_ == STATE_INPROGRESS);
  178. state_ = state;
  179. }
  180. private:
  181. Port* port_ = nullptr;
  182. AllocationSequence* sequence_ = nullptr;
  183. bool has_pairable_candidate_ = false;
  184. State state_ = STATE_INPROGRESS;
  185. };
  186. void OnConfigReady(PortConfiguration* config);
  187. void OnConfigStop();
  188. void AllocatePorts();
  189. void OnAllocate();
  190. void DoAllocate(bool disable_equivalent_phases);
  191. void OnNetworksChanged();
  192. void OnAllocationSequenceObjectsCreated();
  193. void DisableEquivalentPhases(rtc::Network* network,
  194. PortConfiguration* config,
  195. uint32_t* flags);
  196. void AddAllocatedPort(Port* port,
  197. AllocationSequence* seq,
  198. bool prepare_address);
  199. void OnCandidateReady(Port* port, const Candidate& c);
  200. void OnCandidateError(Port* port, const IceCandidateErrorEvent& event);
  201. void OnPortComplete(Port* port);
  202. void OnPortError(Port* port);
  203. void OnProtocolEnabled(AllocationSequence* seq, ProtocolType proto);
  204. void OnPortDestroyed(PortInterface* port);
  205. void MaybeSignalCandidatesAllocationDone();
  206. void OnPortAllocationComplete(AllocationSequence* seq);
  207. PortData* FindPort(Port* port);
  208. std::vector<rtc::Network*> GetNetworks();
  209. std::vector<rtc::Network*> GetFailedNetworks();
  210. void Regather(const std::vector<rtc::Network*>& networks,
  211. bool disable_equivalent_phases,
  212. IceRegatheringReason reason);
  213. bool CheckCandidateFilter(const Candidate& c) const;
  214. bool CandidatePairable(const Candidate& c, const Port* port) const;
  215. std::vector<PortData*> GetUnprunedPorts(
  216. const std::vector<rtc::Network*>& networks);
  217. // Prunes ports and signal the remote side to remove the candidates that
  218. // were previously signaled from these ports.
  219. void PrunePortsAndRemoveCandidates(
  220. const std::vector<PortData*>& port_data_list);
  221. // Gets filtered and sanitized candidates generated from a port and
  222. // append to |candidates|.
  223. void GetCandidatesFromPort(const PortData& data,
  224. std::vector<Candidate>* candidates) const;
  225. Port* GetBestTurnPortForNetwork(const std::string& network_name) const;
  226. // Returns true if at least one TURN port is pruned.
  227. bool PruneTurnPorts(Port* newly_pairable_turn_port);
  228. bool PruneNewlyPairableTurnPort(PortData* newly_pairable_turn_port);
  229. BasicPortAllocator* allocator_;
  230. rtc::Thread* network_thread_;
  231. std::unique_ptr<rtc::PacketSocketFactory> owned_socket_factory_;
  232. rtc::PacketSocketFactory* socket_factory_;
  233. bool allocation_started_;
  234. bool network_manager_started_;
  235. bool allocation_sequences_created_;
  236. std::vector<PortConfiguration*> configs_;
  237. std::vector<AllocationSequence*> sequences_;
  238. std::vector<PortData> ports_;
  239. std::vector<IceCandidateErrorEvent> candidate_error_events_;
  240. uint32_t candidate_filter_ = CF_ALL;
  241. // Policy on how to prune turn ports, taken from the port allocator.
  242. webrtc::PortPrunePolicy turn_port_prune_policy_;
  243. SessionState state_ = SessionState::CLEARED;
  244. friend class AllocationSequence;
  245. };
  246. // Records configuration information useful in creating ports.
  247. // TODO(deadbeef): Rename "relay" to "turn_server" in this struct.
  248. struct RTC_EXPORT PortConfiguration : public rtc::MessageData {
  249. // TODO(jiayl): remove |stun_address| when Chrome is updated.
  250. rtc::SocketAddress stun_address;
  251. ServerAddresses stun_servers;
  252. std::string username;
  253. std::string password;
  254. bool use_turn_server_as_stun_server_disabled = false;
  255. typedef std::vector<RelayServerConfig> RelayList;
  256. RelayList relays;
  257. // TODO(jiayl): remove this ctor when Chrome is updated.
  258. PortConfiguration(const rtc::SocketAddress& stun_address,
  259. const std::string& username,
  260. const std::string& password);
  261. PortConfiguration(const ServerAddresses& stun_servers,
  262. const std::string& username,
  263. const std::string& password);
  264. ~PortConfiguration() override;
  265. // Returns addresses of both the explicitly configured STUN servers,
  266. // and TURN servers that should be used as STUN servers.
  267. ServerAddresses StunServers();
  268. // Adds another relay server, with the given ports and modifier, to the list.
  269. void AddRelay(const RelayServerConfig& config);
  270. // Determines whether the given relay server supports the given protocol.
  271. bool SupportsProtocol(const RelayServerConfig& relay,
  272. ProtocolType type) const;
  273. bool SupportsProtocol(ProtocolType type) const;
  274. // Helper method returns the server addresses for the matching RelayType and
  275. // Protocol type.
  276. ServerAddresses GetRelayServerAddresses(ProtocolType type) const;
  277. };
  278. class UDPPort;
  279. class TurnPort;
  280. // Performs the allocation of ports, in a sequenced (timed) manner, for a given
  281. // network and IP address.
  282. class AllocationSequence : public rtc::MessageHandlerAutoCleanup,
  283. public sigslot::has_slots<> {
  284. public:
  285. enum State {
  286. kInit, // Initial state.
  287. kRunning, // Started allocating ports.
  288. kStopped, // Stopped from running.
  289. kCompleted, // All ports are allocated.
  290. // kInit --> kRunning --> {kCompleted|kStopped}
  291. };
  292. AllocationSequence(BasicPortAllocatorSession* session,
  293. rtc::Network* network,
  294. PortConfiguration* config,
  295. uint32_t flags);
  296. ~AllocationSequence() override;
  297. void Init();
  298. void Clear();
  299. void OnNetworkFailed();
  300. State state() const { return state_; }
  301. rtc::Network* network() const { return network_; }
  302. bool network_failed() const { return network_failed_; }
  303. void set_network_failed() { network_failed_ = true; }
  304. // Disables the phases for a new sequence that this one already covers for an
  305. // equivalent network setup.
  306. void DisableEquivalentPhases(rtc::Network* network,
  307. PortConfiguration* config,
  308. uint32_t* flags);
  309. // Starts and stops the sequence. When started, it will continue allocating
  310. // new ports on its own timed schedule.
  311. void Start();
  312. void Stop();
  313. // MessageHandler
  314. void OnMessage(rtc::Message* msg) override;
  315. // Signal from AllocationSequence, when it's done with allocating ports.
  316. // This signal is useful, when port allocation fails which doesn't result
  317. // in any candidates. Using this signal BasicPortAllocatorSession can send
  318. // its candidate discovery conclusion signal. Without this signal,
  319. // BasicPortAllocatorSession doesn't have any event to trigger signal. This
  320. // can also be achieved by starting timer in BPAS.
  321. sigslot::signal1<AllocationSequence*> SignalPortAllocationComplete;
  322. protected:
  323. // For testing.
  324. void CreateTurnPort(const RelayServerConfig& config);
  325. private:
  326. typedef std::vector<ProtocolType> ProtocolList;
  327. bool IsFlagSet(uint32_t flag) { return ((flags_ & flag) != 0); }
  328. void CreateUDPPorts();
  329. void CreateTCPPorts();
  330. void CreateStunPorts();
  331. void CreateRelayPorts();
  332. void OnReadPacket(rtc::AsyncPacketSocket* socket,
  333. const char* data,
  334. size_t size,
  335. const rtc::SocketAddress& remote_addr,
  336. const int64_t& packet_time_us);
  337. void OnPortDestroyed(PortInterface* port);
  338. BasicPortAllocatorSession* session_;
  339. bool network_failed_ = false;
  340. rtc::Network* network_;
  341. // Compared with the new best IP in DisableEquivalentPhases.
  342. rtc::IPAddress previous_best_ip_;
  343. PortConfiguration* config_;
  344. State state_;
  345. uint32_t flags_;
  346. ProtocolList protocols_;
  347. std::unique_ptr<rtc::AsyncPacketSocket> udp_socket_;
  348. // There will be only one udp port per AllocationSequence.
  349. UDPPort* udp_port_;
  350. std::vector<Port*> relay_ports_;
  351. int phase_;
  352. };
  353. } // namespace cricket
  354. #endif // P2P_CLIENT_BASIC_PORT_ALLOCATOR_H_