port.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. // How long do we estimate that we've been disconnected.
  133. int64_t estimated_disconnected_time_ms;
  134. };
  135. typedef std::set<rtc::SocketAddress> ServerAddresses;
  136. // Represents a local communication mechanism that can be used to create
  137. // connections to similar mechanisms of the other client. Subclasses of this
  138. // one add support for specific mechanisms like local UDP ports.
  139. class Port : public PortInterface,
  140. public rtc::MessageHandlerAutoCleanup,
  141. public sigslot::has_slots<> {
  142. public:
  143. // INIT: The state when a port is just created.
  144. // KEEP_ALIVE_UNTIL_PRUNED: A port should not be destroyed even if no
  145. // connection is using it.
  146. // PRUNED: It will be destroyed if no connection is using it for a period of
  147. // 30 seconds.
  148. enum class State { INIT, KEEP_ALIVE_UNTIL_PRUNED, PRUNED };
  149. Port(rtc::Thread* thread,
  150. const std::string& type,
  151. rtc::PacketSocketFactory* factory,
  152. rtc::Network* network,
  153. const std::string& username_fragment,
  154. const std::string& password);
  155. Port(rtc::Thread* thread,
  156. const std::string& type,
  157. rtc::PacketSocketFactory* factory,
  158. rtc::Network* network,
  159. uint16_t min_port,
  160. uint16_t max_port,
  161. const std::string& username_fragment,
  162. const std::string& password);
  163. ~Port() override;
  164. // Note that the port type does NOT uniquely identify different subclasses of
  165. // Port. Use the 2-tuple of the port type AND the protocol (GetProtocol()) to
  166. // uniquely identify subclasses. Whenever a new subclass of Port introduces a
  167. // conflit in the value of the 2-tuple, make sure that the implementation that
  168. // relies on this 2-tuple for RTTI is properly changed.
  169. const std::string& Type() const override;
  170. rtc::Network* Network() const override;
  171. // Methods to set/get ICE role and tiebreaker values.
  172. IceRole GetIceRole() const override;
  173. void SetIceRole(IceRole role) override;
  174. void SetIceTiebreaker(uint64_t tiebreaker) override;
  175. uint64_t IceTiebreaker() const override;
  176. bool SharedSocket() const override;
  177. void ResetSharedSocket() { shared_socket_ = false; }
  178. // Should not destroy the port even if no connection is using it. Called when
  179. // a port is ready to use.
  180. void KeepAliveUntilPruned();
  181. // Allows a port to be destroyed if no connection is using it.
  182. void Prune();
  183. // The thread on which this port performs its I/O.
  184. rtc::Thread* thread() { return thread_; }
  185. // The factory used to create the sockets of this port.
  186. rtc::PacketSocketFactory* socket_factory() const { return factory_; }
  187. void set_socket_factory(rtc::PacketSocketFactory* factory) {
  188. factory_ = factory;
  189. }
  190. // For debugging purposes.
  191. const std::string& content_name() const { return content_name_; }
  192. void set_content_name(const std::string& content_name) {
  193. content_name_ = content_name;
  194. }
  195. int component() const { return component_; }
  196. void set_component(int component) { component_ = component; }
  197. bool send_retransmit_count_attribute() const {
  198. return send_retransmit_count_attribute_;
  199. }
  200. void set_send_retransmit_count_attribute(bool enable) {
  201. send_retransmit_count_attribute_ = enable;
  202. }
  203. // Identifies the generation that this port was created in.
  204. uint32_t generation() const { return generation_; }
  205. void set_generation(uint32_t generation) { generation_ = generation; }
  206. const std::string username_fragment() const;
  207. const std::string& password() const { return password_; }
  208. // May be called when this port was initially created by a pooled
  209. // PortAllocatorSession, and is now being assigned to an ICE transport.
  210. // Updates the information for candidates as well.
  211. void SetIceParameters(int component,
  212. const std::string& username_fragment,
  213. const std::string& password);
  214. // Fired when candidates are discovered by the port. When all candidates
  215. // are discovered that belong to port SignalAddressReady is fired.
  216. sigslot::signal2<Port*, const Candidate&> SignalCandidateReady;
  217. // Provides all of the above information in one handy object.
  218. const std::vector<Candidate>& Candidates() const override;
  219. // Fired when candidate discovery failed using certain server.
  220. sigslot::signal2<Port*, const IceCandidateErrorEvent&> SignalCandidateError;
  221. // SignalPortComplete is sent when port completes the task of candidates
  222. // allocation.
  223. sigslot::signal1<Port*> SignalPortComplete;
  224. // This signal sent when port fails to allocate candidates and this port
  225. // can't be used in establishing the connections. When port is in shared mode
  226. // and port fails to allocate one of the candidates, port shouldn't send
  227. // this signal as other candidates might be usefull in establishing the
  228. // connection.
  229. sigslot::signal1<Port*> SignalPortError;
  230. // Returns a map containing all of the connections of this port, keyed by the
  231. // remote address.
  232. typedef std::map<rtc::SocketAddress, Connection*> AddressMap;
  233. const AddressMap& connections() { return connections_; }
  234. // Returns the connection to the given address or NULL if none exists.
  235. Connection* GetConnection(const rtc::SocketAddress& remote_addr) override;
  236. // Called each time a connection is created.
  237. sigslot::signal2<Port*, Connection*> SignalConnectionCreated;
  238. // In a shared socket mode each port which shares the socket will decide
  239. // to accept the packet based on the |remote_addr|. Currently only UDP
  240. // port implemented this method.
  241. // TODO(mallinath) - Make it pure virtual.
  242. virtual bool HandleIncomingPacket(rtc::AsyncPacketSocket* socket,
  243. const char* data,
  244. size_t size,
  245. const rtc::SocketAddress& remote_addr,
  246. int64_t packet_time_us);
  247. // Shall the port handle packet from this |remote_addr|.
  248. // This method is overridden by TurnPort.
  249. virtual bool CanHandleIncomingPacketsFrom(
  250. const rtc::SocketAddress& remote_addr) const;
  251. // Sends a response error to the given request.
  252. void SendBindingErrorResponse(StunMessage* request,
  253. const rtc::SocketAddress& addr,
  254. int error_code,
  255. const std::string& reason) override;
  256. void SendUnknownAttributesErrorResponse(
  257. StunMessage* request,
  258. const rtc::SocketAddress& addr,
  259. const std::vector<uint16_t>& unknown_types);
  260. void set_proxy(const std::string& user_agent, const rtc::ProxyInfo& proxy) {
  261. user_agent_ = user_agent;
  262. proxy_ = proxy;
  263. }
  264. const std::string& user_agent() { return user_agent_; }
  265. const rtc::ProxyInfo& proxy() { return proxy_; }
  266. void EnablePortPackets() override;
  267. // Called if the port has no connections and is no longer useful.
  268. void Destroy();
  269. void OnMessage(rtc::Message* pmsg) override;
  270. // Debugging description of this port
  271. std::string ToString() const override;
  272. uint16_t min_port() { return min_port_; }
  273. uint16_t max_port() { return max_port_; }
  274. // Timeout shortening function to speed up unit tests.
  275. void set_timeout_delay(int delay) { timeout_delay_ = delay; }
  276. // This method will return local and remote username fragements from the
  277. // stun username attribute if present.
  278. bool ParseStunUsername(const StunMessage* stun_msg,
  279. std::string* local_username,
  280. std::string* remote_username) const;
  281. void CreateStunUsername(const std::string& remote_username,
  282. std::string* stun_username_attr_str) const;
  283. bool MaybeIceRoleConflict(const rtc::SocketAddress& addr,
  284. IceMessage* stun_msg,
  285. const std::string& remote_ufrag);
  286. // Called when a packet has been sent to the socket.
  287. // This is made pure virtual to notify subclasses of Port that they MUST
  288. // listen to AsyncPacketSocket::SignalSentPacket and then call
  289. // PortInterface::OnSentPacket.
  290. virtual void OnSentPacket(rtc::AsyncPacketSocket* socket,
  291. const rtc::SentPacket& sent_packet) = 0;
  292. // Called when the socket is currently able to send.
  293. void OnReadyToSend();
  294. // Called when the Connection discovers a local peer reflexive candidate.
  295. // Returns the index of the new local candidate.
  296. size_t AddPrflxCandidate(const Candidate& local);
  297. int16_t network_cost() const { return network_cost_; }
  298. void GetStunStats(absl::optional<StunStats>* stats) override {}
  299. // Foundation: An arbitrary string that is the same for two candidates
  300. // that have the same type, base IP address, protocol (UDP, TCP,
  301. // etc.), and STUN or TURN server. If any of these are different,
  302. // then the foundation will be different. Two candidate pairs with
  303. // the same foundation pairs are likely to have similar network
  304. // characteristics. Foundations are used in the frozen algorithm.
  305. static std::string ComputeFoundation(const std::string& type,
  306. const std::string& protocol,
  307. const std::string& relay_protocol,
  308. const rtc::SocketAddress& base_address);
  309. protected:
  310. enum { MSG_DESTROY_IF_DEAD = 0, MSG_FIRST_AVAILABLE };
  311. virtual void UpdateNetworkCost();
  312. void set_type(const std::string& type) { type_ = type; }
  313. void AddAddress(const rtc::SocketAddress& address,
  314. const rtc::SocketAddress& base_address,
  315. const rtc::SocketAddress& related_address,
  316. const std::string& protocol,
  317. const std::string& relay_protocol,
  318. const std::string& tcptype,
  319. const std::string& type,
  320. uint32_t type_preference,
  321. uint32_t relay_preference,
  322. const std::string& url,
  323. bool is_final);
  324. void FinishAddingAddress(const Candidate& c, bool is_final);
  325. virtual void PostAddAddress(bool is_final);
  326. // Adds the given connection to the map keyed by the remote candidate address.
  327. // If an existing connection has the same address, the existing one will be
  328. // replaced and destroyed.
  329. void AddOrReplaceConnection(Connection* conn);
  330. // Called when a packet is received from an unknown address that is not
  331. // currently a connection. If this is an authenticated STUN binding request,
  332. // then we will signal the client.
  333. void OnReadPacket(const char* data,
  334. size_t size,
  335. const rtc::SocketAddress& addr,
  336. ProtocolType proto);
  337. // If the given data comprises a complete and correct STUN message then the
  338. // return value is true, otherwise false. If the message username corresponds
  339. // with this port's username fragment, msg will contain the parsed STUN
  340. // message. Otherwise, the function may send a STUN response internally.
  341. // remote_username contains the remote fragment of the STUN username.
  342. bool GetStunMessage(const char* data,
  343. size_t size,
  344. const rtc::SocketAddress& addr,
  345. std::unique_ptr<IceMessage>* out_msg,
  346. std::string* out_username);
  347. // Checks if the address in addr is compatible with the port's ip.
  348. bool IsCompatibleAddress(const rtc::SocketAddress& addr);
  349. // Returns DSCP value packets generated by the port itself should use.
  350. virtual rtc::DiffServCodePoint StunDscpValue() const;
  351. // Extra work to be done in subclasses when a connection is destroyed.
  352. virtual void HandleConnectionDestroyed(Connection* conn) {}
  353. void CopyPortInformationToPacketInfo(rtc::PacketInfo* info) const;
  354. MdnsNameRegistrationStatus mdns_name_registration_status() const {
  355. return mdns_name_registration_status_;
  356. }
  357. void set_mdns_name_registration_status(MdnsNameRegistrationStatus status) {
  358. mdns_name_registration_status_ = status;
  359. }
  360. private:
  361. void Construct();
  362. // Called when one of our connections deletes itself.
  363. void OnConnectionDestroyed(Connection* conn);
  364. void OnNetworkTypeChanged(const rtc::Network* network);
  365. rtc::Thread* thread_;
  366. rtc::PacketSocketFactory* factory_;
  367. std::string type_;
  368. bool send_retransmit_count_attribute_;
  369. rtc::Network* network_;
  370. uint16_t min_port_;
  371. uint16_t max_port_;
  372. std::string content_name_;
  373. int component_;
  374. uint32_t generation_;
  375. // In order to establish a connection to this Port (so that real data can be
  376. // sent through), the other side must send us a STUN binding request that is
  377. // authenticated with this username_fragment and password.
  378. // PortAllocatorSession will provide these username_fragment and password.
  379. //
  380. // Note: we should always use username_fragment() instead of using
  381. // |ice_username_fragment_| directly. For the details see the comment on
  382. // username_fragment().
  383. std::string ice_username_fragment_;
  384. std::string password_;
  385. std::vector<Candidate> candidates_;
  386. AddressMap connections_;
  387. int timeout_delay_;
  388. bool enable_port_packets_;
  389. IceRole ice_role_;
  390. uint64_t tiebreaker_;
  391. bool shared_socket_;
  392. // Information to use when going through a proxy.
  393. std::string user_agent_;
  394. rtc::ProxyInfo proxy_;
  395. // A virtual cost perceived by the user, usually based on the network type
  396. // (WiFi. vs. Cellular). It takes precedence over the priority when
  397. // comparing two connections.
  398. int16_t network_cost_;
  399. State state_ = State::INIT;
  400. int64_t last_time_all_connections_removed_ = 0;
  401. MdnsNameRegistrationStatus mdns_name_registration_status_ =
  402. MdnsNameRegistrationStatus::kNotStarted;
  403. rtc::WeakPtrFactory<Port> weak_factory_;
  404. bool MaybeObfuscateAddress(Candidate* c,
  405. const std::string& type,
  406. bool is_final);
  407. friend class Connection;
  408. };
  409. } // namespace cricket
  410. #endif // P2P_BASE_PORT_H_