port.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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_BASE_PORT_H_
  11. #define P2P_BASE_PORT_H_
  12. #include <map>
  13. #include <memory>
  14. #include <set>
  15. #include <string>
  16. #include <utility>
  17. #include <vector>
  18. #include "absl/types/optional.h"
  19. #include "api/candidate.h"
  20. #include "api/packet_socket_factory.h"
  21. #include "api/rtc_error.h"
  22. #include "api/transport/stun.h"
  23. #include "logging/rtc_event_log/events/rtc_event_ice_candidate_pair.h"
  24. #include "logging/rtc_event_log/events/rtc_event_ice_candidate_pair_config.h"
  25. #include "logging/rtc_event_log/ice_logger.h"
  26. #include "p2p/base/candidate_pair_interface.h"
  27. #include "p2p/base/connection.h"
  28. #include "p2p/base/connection_info.h"
  29. #include "p2p/base/p2p_constants.h"
  30. #include "p2p/base/port_interface.h"
  31. #include "p2p/base/stun_request.h"
  32. #include "rtc_base/async_packet_socket.h"
  33. #include "rtc_base/checks.h"
  34. #include "rtc_base/net_helper.h"
  35. #include "rtc_base/network.h"
  36. #include "rtc_base/proxy_info.h"
  37. #include "rtc_base/rate_tracker.h"
  38. #include "rtc_base/socket_address.h"
  39. #include "rtc_base/system/rtc_export.h"
  40. #include "rtc_base/third_party/sigslot/sigslot.h"
  41. #include "rtc_base/thread.h"
  42. #include "rtc_base/weak_ptr.h"
  43. namespace cricket {
  44. RTC_EXPORT extern const char LOCAL_PORT_TYPE[];
  45. RTC_EXPORT extern const char STUN_PORT_TYPE[];
  46. RTC_EXPORT extern const char PRFLX_PORT_TYPE[];
  47. RTC_EXPORT extern const char RELAY_PORT_TYPE[];
  48. // RFC 6544, TCP candidate encoding rules.
  49. extern const int DISCARD_PORT;
  50. extern const char TCPTYPE_ACTIVE_STR[];
  51. extern const char TCPTYPE_PASSIVE_STR[];
  52. extern const char TCPTYPE_SIMOPEN_STR[];
  53. enum IcePriorityValue {
  54. ICE_TYPE_PREFERENCE_RELAY_TLS = 0,
  55. ICE_TYPE_PREFERENCE_RELAY_TCP = 1,
  56. ICE_TYPE_PREFERENCE_RELAY_UDP = 2,
  57. ICE_TYPE_PREFERENCE_PRFLX_TCP = 80,
  58. ICE_TYPE_PREFERENCE_HOST_TCP = 90,
  59. ICE_TYPE_PREFERENCE_SRFLX = 100,
  60. ICE_TYPE_PREFERENCE_PRFLX = 110,
  61. ICE_TYPE_PREFERENCE_HOST = 126
  62. };
  63. enum class MdnsNameRegistrationStatus {
  64. // IP concealment with mDNS is not enabled or the name registration process is
  65. // not started yet.
  66. kNotStarted,
  67. // A request to create and register an mDNS name for a local IP address of a
  68. // host candidate is sent to the mDNS responder.
  69. kInProgress,
  70. // The name registration is complete and the created name is returned by the
  71. // mDNS responder.
  72. kCompleted,
  73. };
  74. // Stats that we can return about the port of a STUN candidate.
  75. class StunStats {
  76. public:
  77. StunStats() = default;
  78. StunStats(const StunStats&) = default;
  79. ~StunStats() = default;
  80. StunStats& operator=(const StunStats& other) = default;
  81. int stun_binding_requests_sent = 0;
  82. int stun_binding_responses_received = 0;
  83. double stun_binding_rtt_ms_total = 0;
  84. double stun_binding_rtt_ms_squared_total = 0;
  85. };
  86. // Stats that we can return about a candidate.
  87. class CandidateStats {
  88. public:
  89. CandidateStats();
  90. explicit CandidateStats(Candidate candidate);
  91. CandidateStats(const CandidateStats&);
  92. ~CandidateStats();
  93. Candidate candidate;
  94. // STUN port stats if this candidate is a STUN candidate.
  95. absl::optional<StunStats> stun_stats;
  96. };
  97. typedef std::vector<CandidateStats> CandidateStatsList;
  98. const char* ProtoToString(ProtocolType proto);
  99. bool StringToProto(const char* value, ProtocolType* proto);
  100. struct ProtocolAddress {
  101. rtc::SocketAddress address;
  102. ProtocolType proto;
  103. ProtocolAddress(const rtc::SocketAddress& a, ProtocolType p)
  104. : address(a), proto(p) {}
  105. bool operator==(const ProtocolAddress& o) const {
  106. return address == o.address && proto == o.proto;
  107. }
  108. bool operator!=(const ProtocolAddress& o) const { return !(*this == o); }
  109. };
  110. struct IceCandidateErrorEvent {
  111. IceCandidateErrorEvent() = default;
  112. IceCandidateErrorEvent(std::string address,
  113. int port,
  114. std::string url,
  115. int error_code,
  116. std::string error_text)
  117. : address(std::move(address)),
  118. port(port),
  119. url(std::move(url)),
  120. error_code(error_code),
  121. error_text(std::move(error_text)) {}
  122. std::string address;
  123. int port = 0;
  124. std::string url;
  125. int error_code = 0;
  126. std::string error_text;
  127. };
  128. struct CandidatePairChangeEvent {
  129. CandidatePair selected_candidate_pair;
  130. int64_t last_data_received_ms;
  131. std::string reason;
  132. };
  133. typedef std::set<rtc::SocketAddress> ServerAddresses;
  134. // Represents a local communication mechanism that can be used to create
  135. // connections to similar mechanisms of the other client. Subclasses of this
  136. // one add support for specific mechanisms like local UDP ports.
  137. class Port : public PortInterface,
  138. public rtc::MessageHandler,
  139. public sigslot::has_slots<> {
  140. public:
  141. // INIT: The state when a port is just created.
  142. // KEEP_ALIVE_UNTIL_PRUNED: A port should not be destroyed even if no
  143. // connection is using it.
  144. // PRUNED: It will be destroyed if no connection is using it for a period of
  145. // 30 seconds.
  146. enum class State { INIT, KEEP_ALIVE_UNTIL_PRUNED, PRUNED };
  147. Port(rtc::Thread* thread,
  148. const std::string& type,
  149. rtc::PacketSocketFactory* factory,
  150. rtc::Network* network,
  151. const std::string& username_fragment,
  152. const std::string& password);
  153. Port(rtc::Thread* thread,
  154. const std::string& type,
  155. rtc::PacketSocketFactory* factory,
  156. rtc::Network* network,
  157. uint16_t min_port,
  158. uint16_t max_port,
  159. const std::string& username_fragment,
  160. const std::string& password);
  161. ~Port() override;
  162. // Note that the port type does NOT uniquely identify different subclasses of
  163. // Port. Use the 2-tuple of the port type AND the protocol (GetProtocol()) to
  164. // uniquely identify subclasses. Whenever a new subclass of Port introduces a
  165. // conflit in the value of the 2-tuple, make sure that the implementation that
  166. // relies on this 2-tuple for RTTI is properly changed.
  167. const std::string& Type() const override;
  168. rtc::Network* Network() const override;
  169. // Methods to set/get ICE role and tiebreaker values.
  170. IceRole GetIceRole() const override;
  171. void SetIceRole(IceRole role) override;
  172. void SetIceTiebreaker(uint64_t tiebreaker) override;
  173. uint64_t IceTiebreaker() const override;
  174. bool SharedSocket() const override;
  175. void ResetSharedSocket() { shared_socket_ = false; }
  176. // Should not destroy the port even if no connection is using it. Called when
  177. // a port is ready to use.
  178. void KeepAliveUntilPruned();
  179. // Allows a port to be destroyed if no connection is using it.
  180. void Prune();
  181. // The thread on which this port performs its I/O.
  182. rtc::Thread* thread() { return thread_; }
  183. // The factory used to create the sockets of this port.
  184. rtc::PacketSocketFactory* socket_factory() const { return factory_; }
  185. void set_socket_factory(rtc::PacketSocketFactory* factory) {
  186. factory_ = factory;
  187. }
  188. // For debugging purposes.
  189. const std::string& content_name() const { return content_name_; }
  190. void set_content_name(const std::string& content_name) {
  191. content_name_ = content_name;
  192. }
  193. int component() const { return component_; }
  194. void set_component(int component) { component_ = component; }
  195. bool send_retransmit_count_attribute() const {
  196. return send_retransmit_count_attribute_;
  197. }
  198. void set_send_retransmit_count_attribute(bool enable) {
  199. send_retransmit_count_attribute_ = enable;
  200. }
  201. // Identifies the generation that this port was created in.
  202. uint32_t generation() const { return generation_; }
  203. void set_generation(uint32_t generation) { generation_ = generation; }
  204. const std::string username_fragment() const;
  205. const std::string& password() const { return password_; }
  206. // May be called when this port was initially created by a pooled
  207. // PortAllocatorSession, and is now being assigned to an ICE transport.
  208. // Updates the information for candidates as well.
  209. void SetIceParameters(int component,
  210. const std::string& username_fragment,
  211. const std::string& password);
  212. // Fired when candidates are discovered by the port. When all candidates
  213. // are discovered that belong to port SignalAddressReady is fired.
  214. sigslot::signal2<Port*, const Candidate&> SignalCandidateReady;
  215. // Provides all of the above information in one handy object.
  216. const std::vector<Candidate>& Candidates() const override;
  217. // Fired when candidate discovery failed using certain server.
  218. sigslot::signal2<Port*, const IceCandidateErrorEvent&> SignalCandidateError;
  219. // SignalPortComplete is sent when port completes the task of candidates
  220. // allocation.
  221. sigslot::signal1<Port*> SignalPortComplete;
  222. // This signal sent when port fails to allocate candidates and this port
  223. // can't be used in establishing the connections. When port is in shared mode
  224. // and port fails to allocate one of the candidates, port shouldn't send
  225. // this signal as other candidates might be usefull in establishing the
  226. // connection.
  227. sigslot::signal1<Port*> SignalPortError;
  228. // Returns a map containing all of the connections of this port, keyed by the
  229. // remote address.
  230. typedef std::map<rtc::SocketAddress, Connection*> AddressMap;
  231. const AddressMap& connections() { return connections_; }
  232. // Returns the connection to the given address or NULL if none exists.
  233. Connection* GetConnection(const rtc::SocketAddress& remote_addr) override;
  234. // Called each time a connection is created.
  235. sigslot::signal2<Port*, Connection*> SignalConnectionCreated;
  236. // In a shared socket mode each port which shares the socket will decide
  237. // to accept the packet based on the |remote_addr|. Currently only UDP
  238. // port implemented this method.
  239. // TODO(mallinath) - Make it pure virtual.
  240. virtual bool HandleIncomingPacket(rtc::AsyncPacketSocket* socket,
  241. const char* data,
  242. size_t size,
  243. const rtc::SocketAddress& remote_addr,
  244. int64_t packet_time_us);
  245. // Shall the port handle packet from this |remote_addr|.
  246. // This method is overridden by TurnPort.
  247. virtual bool CanHandleIncomingPacketsFrom(
  248. const rtc::SocketAddress& remote_addr) const;
  249. // Sends a response error to the given request.
  250. void SendBindingErrorResponse(StunMessage* request,
  251. const rtc::SocketAddress& addr,
  252. int error_code,
  253. const std::string& reason) override;
  254. void SendUnknownAttributesErrorResponse(
  255. StunMessage* request,
  256. const rtc::SocketAddress& addr,
  257. const std::vector<uint16_t>& unknown_types);
  258. void set_proxy(const std::string& user_agent, const rtc::ProxyInfo& proxy) {
  259. user_agent_ = user_agent;
  260. proxy_ = proxy;
  261. }
  262. const std::string& user_agent() { return user_agent_; }
  263. const rtc::ProxyInfo& proxy() { return proxy_; }
  264. void EnablePortPackets() override;
  265. // Called if the port has no connections and is no longer useful.
  266. void Destroy();
  267. void OnMessage(rtc::Message* pmsg) override;
  268. // Debugging description of this port
  269. std::string ToString() const override;
  270. uint16_t min_port() { return min_port_; }
  271. uint16_t max_port() { return max_port_; }
  272. // Timeout shortening function to speed up unit tests.
  273. void set_timeout_delay(int delay) { timeout_delay_ = delay; }
  274. // This method will return local and remote username fragements from the
  275. // stun username attribute if present.
  276. bool ParseStunUsername(const StunMessage* stun_msg,
  277. std::string* local_username,
  278. std::string* remote_username) const;
  279. void CreateStunUsername(const std::string& remote_username,
  280. std::string* stun_username_attr_str) const;
  281. bool MaybeIceRoleConflict(const rtc::SocketAddress& addr,
  282. IceMessage* stun_msg,
  283. const std::string& remote_ufrag);
  284. // Called when a packet has been sent to the socket.
  285. // This is made pure virtual to notify subclasses of Port that they MUST
  286. // listen to AsyncPacketSocket::SignalSentPacket and then call
  287. // PortInterface::OnSentPacket.
  288. virtual void OnSentPacket(rtc::AsyncPacketSocket* socket,
  289. const rtc::SentPacket& sent_packet) = 0;
  290. // Called when the socket is currently able to send.
  291. void OnReadyToSend();
  292. // Called when the Connection discovers a local peer reflexive candidate.
  293. // Returns the index of the new local candidate.
  294. size_t AddPrflxCandidate(const Candidate& local);
  295. int16_t network_cost() const { return network_cost_; }
  296. void GetStunStats(absl::optional<StunStats>* stats) override {}
  297. // Foundation: An arbitrary string that is the same for two candidates
  298. // that have the same type, base IP address, protocol (UDP, TCP,
  299. // etc.), and STUN or TURN server. If any of these are different,
  300. // then the foundation will be different. Two candidate pairs with
  301. // the same foundation pairs are likely to have similar network
  302. // characteristics. Foundations are used in the frozen algorithm.
  303. static std::string ComputeFoundation(const std::string& type,
  304. const std::string& protocol,
  305. const std::string& relay_protocol,
  306. const rtc::SocketAddress& base_address);
  307. protected:
  308. enum { MSG_DESTROY_IF_DEAD = 0, MSG_FIRST_AVAILABLE };
  309. virtual void UpdateNetworkCost();
  310. void set_type(const std::string& type) { type_ = type; }
  311. void AddAddress(const rtc::SocketAddress& address,
  312. const rtc::SocketAddress& base_address,
  313. const rtc::SocketAddress& related_address,
  314. const std::string& protocol,
  315. const std::string& relay_protocol,
  316. const std::string& tcptype,
  317. const std::string& type,
  318. uint32_t type_preference,
  319. uint32_t relay_preference,
  320. const std::string& url,
  321. bool is_final);
  322. void FinishAddingAddress(const Candidate& c, bool is_final);
  323. virtual void PostAddAddress(bool is_final);
  324. // Adds the given connection to the map keyed by the remote candidate address.
  325. // If an existing connection has the same address, the existing one will be
  326. // replaced and destroyed.
  327. void AddOrReplaceConnection(Connection* conn);
  328. // Called when a packet is received from an unknown address that is not
  329. // currently a connection. If this is an authenticated STUN binding request,
  330. // then we will signal the client.
  331. void OnReadPacket(const char* data,
  332. size_t size,
  333. const rtc::SocketAddress& addr,
  334. ProtocolType proto);
  335. // If the given data comprises a complete and correct STUN message then the
  336. // return value is true, otherwise false. If the message username corresponds
  337. // with this port's username fragment, msg will contain the parsed STUN
  338. // message. Otherwise, the function may send a STUN response internally.
  339. // remote_username contains the remote fragment of the STUN username.
  340. bool GetStunMessage(const char* data,
  341. size_t size,
  342. const rtc::SocketAddress& addr,
  343. std::unique_ptr<IceMessage>* out_msg,
  344. std::string* out_username);
  345. // Checks if the address in addr is compatible with the port's ip.
  346. bool IsCompatibleAddress(const rtc::SocketAddress& addr);
  347. // Returns DSCP value packets generated by the port itself should use.
  348. virtual rtc::DiffServCodePoint StunDscpValue() const;
  349. // Extra work to be done in subclasses when a connection is destroyed.
  350. virtual void HandleConnectionDestroyed(Connection* conn) {}
  351. void CopyPortInformationToPacketInfo(rtc::PacketInfo* info) const;
  352. MdnsNameRegistrationStatus mdns_name_registration_status() const {
  353. return mdns_name_registration_status_;
  354. }
  355. void set_mdns_name_registration_status(MdnsNameRegistrationStatus status) {
  356. mdns_name_registration_status_ = status;
  357. }
  358. private:
  359. void Construct();
  360. // Called when one of our connections deletes itself.
  361. void OnConnectionDestroyed(Connection* conn);
  362. void OnNetworkTypeChanged(const rtc::Network* network);
  363. rtc::Thread* thread_;
  364. rtc::PacketSocketFactory* factory_;
  365. std::string type_;
  366. bool send_retransmit_count_attribute_;
  367. rtc::Network* network_;
  368. uint16_t min_port_;
  369. uint16_t max_port_;
  370. std::string content_name_;
  371. int component_;
  372. uint32_t generation_;
  373. // In order to establish a connection to this Port (so that real data can be
  374. // sent through), the other side must send us a STUN binding request that is
  375. // authenticated with this username_fragment and password.
  376. // PortAllocatorSession will provide these username_fragment and password.
  377. //
  378. // Note: we should always use username_fragment() instead of using
  379. // |ice_username_fragment_| directly. For the details see the comment on
  380. // username_fragment().
  381. std::string ice_username_fragment_;
  382. std::string password_;
  383. std::vector<Candidate> candidates_;
  384. AddressMap connections_;
  385. int timeout_delay_;
  386. bool enable_port_packets_;
  387. IceRole ice_role_;
  388. uint64_t tiebreaker_;
  389. bool shared_socket_;
  390. // Information to use when going through a proxy.
  391. std::string user_agent_;
  392. rtc::ProxyInfo proxy_;
  393. // A virtual cost perceived by the user, usually based on the network type
  394. // (WiFi. vs. Cellular). It takes precedence over the priority when
  395. // comparing two connections.
  396. int16_t network_cost_;
  397. State state_ = State::INIT;
  398. int64_t last_time_all_connections_removed_ = 0;
  399. MdnsNameRegistrationStatus mdns_name_registration_status_ =
  400. MdnsNameRegistrationStatus::kNotStarted;
  401. rtc::WeakPtrFactory<Port> weak_factory_;
  402. bool MaybeObfuscateAddress(Candidate* c,
  403. const std::string& type,
  404. bool is_final);
  405. friend class Connection;
  406. };
  407. } // namespace cricket
  408. #endif // P2P_BASE_PORT_H_