network.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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 RTC_BASE_NETWORK_H_
  11. #define RTC_BASE_NETWORK_H_
  12. #include <stdint.h>
  13. #include <deque>
  14. #include <map>
  15. #include <memory>
  16. #include <string>
  17. #include <vector>
  18. #include "rtc_base/ip_address.h"
  19. #include "rtc_base/mdns_responder_interface.h"
  20. #include "rtc_base/message_handler.h"
  21. #include "rtc_base/network_monitor.h"
  22. #include "rtc_base/system/rtc_export.h"
  23. #include "rtc_base/third_party/sigslot/sigslot.h"
  24. #if defined(WEBRTC_POSIX)
  25. struct ifaddrs;
  26. #endif // defined(WEBRTC_POSIX)
  27. namespace rtc {
  28. extern const char kPublicIPv4Host[];
  29. extern const char kPublicIPv6Host[];
  30. class IfAddrsConverter;
  31. class Network;
  32. class NetworkMonitorInterface;
  33. class Thread;
  34. // By default, ignore loopback interfaces on the host.
  35. const int kDefaultNetworkIgnoreMask = ADAPTER_TYPE_LOOPBACK;
  36. // Makes a string key for this network. Used in the network manager's maps.
  37. // Network objects are keyed on interface name, network prefix and the
  38. // length of that prefix.
  39. std::string MakeNetworkKey(const std::string& name,
  40. const IPAddress& prefix,
  41. int prefix_length);
  42. // Utility function that attempts to determine an adapter type by an interface
  43. // name (e.g., "wlan0"). Can be used by NetworkManager subclasses when other
  44. // mechanisms fail to determine the type.
  45. RTC_EXPORT AdapterType GetAdapterTypeFromName(const char* network_name);
  46. class DefaultLocalAddressProvider {
  47. public:
  48. virtual ~DefaultLocalAddressProvider() = default;
  49. // The default local address is the local address used in multi-homed endpoint
  50. // when the any address (0.0.0.0 or ::) is used as the local address. It's
  51. // important to check the return value as a IP family may not be enabled.
  52. virtual bool GetDefaultLocalAddress(int family, IPAddress* ipaddr) const = 0;
  53. };
  54. class MdnsResponderProvider {
  55. public:
  56. virtual ~MdnsResponderProvider() = default;
  57. // Returns the mDNS responder that can be used to obfuscate the local IP
  58. // addresses of ICE host candidates by mDNS hostnames.
  59. //
  60. // The provider MUST outlive the mDNS responder.
  61. virtual webrtc::MdnsResponderInterface* GetMdnsResponder() const = 0;
  62. };
  63. // Generic network manager interface. It provides list of local
  64. // networks.
  65. //
  66. // Every method of NetworkManager (including the destructor) must be called on
  67. // the same thread, except for the constructor which may be called on any
  68. // thread.
  69. //
  70. // This allows constructing a NetworkManager subclass on one thread and
  71. // passing it into an object that uses it on a different thread.
  72. class RTC_EXPORT NetworkManager : public DefaultLocalAddressProvider,
  73. public MdnsResponderProvider {
  74. public:
  75. typedef std::vector<Network*> NetworkList;
  76. // This enum indicates whether adapter enumeration is allowed.
  77. enum EnumerationPermission {
  78. ENUMERATION_ALLOWED, // Adapter enumeration is allowed. Getting 0 network
  79. // from GetNetworks means that there is no network
  80. // available.
  81. ENUMERATION_BLOCKED, // Adapter enumeration is disabled.
  82. // GetAnyAddressNetworks() should be used instead.
  83. };
  84. NetworkManager();
  85. ~NetworkManager() override;
  86. // Called when network list is updated.
  87. sigslot::signal0<> SignalNetworksChanged;
  88. // Indicates a failure when getting list of network interfaces.
  89. sigslot::signal0<> SignalError;
  90. // This should be called on the NetworkManager's thread before the
  91. // NetworkManager is used. Subclasses may override this if necessary.
  92. virtual void Initialize() {}
  93. // Start/Stop monitoring of network interfaces
  94. // list. SignalNetworksChanged or SignalError is emitted immediately
  95. // after StartUpdating() is called. After that SignalNetworksChanged
  96. // is emitted whenever list of networks changes.
  97. virtual void StartUpdating() = 0;
  98. virtual void StopUpdating() = 0;
  99. // Returns the current list of networks available on this machine.
  100. // StartUpdating() must be called before this method is called.
  101. // It makes sure that repeated calls return the same object for a
  102. // given network, so that quality is tracked appropriately. Does not
  103. // include ignored networks.
  104. virtual void GetNetworks(NetworkList* networks) const = 0;
  105. // Returns the current permission state of GetNetworks().
  106. virtual EnumerationPermission enumeration_permission() const;
  107. // "AnyAddressNetwork" is a network which only contains single "any address"
  108. // IP address. (i.e. INADDR_ANY for IPv4 or in6addr_any for IPv6). This is
  109. // useful as binding to such interfaces allow default routing behavior like
  110. // http traffic.
  111. //
  112. // This method appends the "any address" networks to the list, such that this
  113. // can optionally be called after GetNetworks.
  114. //
  115. // TODO(guoweis): remove this body when chromium implements this.
  116. virtual void GetAnyAddressNetworks(NetworkList* networks) {}
  117. // Dumps the current list of networks in the network manager.
  118. virtual void DumpNetworks() {}
  119. bool GetDefaultLocalAddress(int family, IPAddress* ipaddr) const override;
  120. struct Stats {
  121. int ipv4_network_count;
  122. int ipv6_network_count;
  123. Stats() {
  124. ipv4_network_count = 0;
  125. ipv6_network_count = 0;
  126. }
  127. };
  128. // MdnsResponderProvider interface.
  129. webrtc::MdnsResponderInterface* GetMdnsResponder() const override;
  130. };
  131. // Base class for NetworkManager implementations.
  132. class RTC_EXPORT NetworkManagerBase : public NetworkManager {
  133. public:
  134. NetworkManagerBase();
  135. ~NetworkManagerBase() override;
  136. void GetNetworks(NetworkList* networks) const override;
  137. void GetAnyAddressNetworks(NetworkList* networks) override;
  138. EnumerationPermission enumeration_permission() const override;
  139. bool GetDefaultLocalAddress(int family, IPAddress* ipaddr) const override;
  140. protected:
  141. typedef std::map<std::string, Network*> NetworkMap;
  142. // Updates |networks_| with the networks listed in |list|. If
  143. // |network_map_| already has a Network object for a network listed
  144. // in the |list| then it is reused. Accept ownership of the Network
  145. // objects in the |list|. |changed| will be set to true if there is
  146. // any change in the network list.
  147. void MergeNetworkList(const NetworkList& list, bool* changed);
  148. // |stats| will be populated even if |*changed| is false.
  149. void MergeNetworkList(const NetworkList& list,
  150. bool* changed,
  151. NetworkManager::Stats* stats);
  152. void set_enumeration_permission(EnumerationPermission state) {
  153. enumeration_permission_ = state;
  154. }
  155. void set_default_local_addresses(const IPAddress& ipv4,
  156. const IPAddress& ipv6);
  157. private:
  158. friend class NetworkTest;
  159. Network* GetNetworkFromAddress(const rtc::IPAddress& ip) const;
  160. EnumerationPermission enumeration_permission_;
  161. NetworkList networks_;
  162. NetworkMap networks_map_;
  163. std::unique_ptr<rtc::Network> ipv4_any_address_network_;
  164. std::unique_ptr<rtc::Network> ipv6_any_address_network_;
  165. IPAddress default_local_ipv4_address_;
  166. IPAddress default_local_ipv6_address_;
  167. // We use 16 bits to save the bandwidth consumption when sending the network
  168. // id over the Internet. It is OK that the 16-bit integer overflows to get a
  169. // network id 0 because we only compare the network ids in the old and the new
  170. // best connections in the transport channel.
  171. uint16_t next_available_network_id_ = 1;
  172. };
  173. // Basic implementation of the NetworkManager interface that gets list
  174. // of networks using OS APIs.
  175. class RTC_EXPORT BasicNetworkManager : public NetworkManagerBase,
  176. public MessageHandler,
  177. public sigslot::has_slots<> {
  178. public:
  179. BasicNetworkManager();
  180. ~BasicNetworkManager() override;
  181. void StartUpdating() override;
  182. void StopUpdating() override;
  183. void DumpNetworks() override;
  184. // MessageHandler interface.
  185. void OnMessage(Message* msg) override;
  186. bool started() { return start_count_ > 0; }
  187. // Sets the network ignore list, which is empty by default. Any network on the
  188. // ignore list will be filtered from network enumeration results.
  189. void set_network_ignore_list(const std::vector<std::string>& list) {
  190. network_ignore_list_ = list;
  191. }
  192. protected:
  193. #if defined(WEBRTC_POSIX)
  194. // Separated from CreateNetworks for tests.
  195. void ConvertIfAddrs(ifaddrs* interfaces,
  196. IfAddrsConverter* converter,
  197. bool include_ignored,
  198. NetworkList* networks) const;
  199. #endif // defined(WEBRTC_POSIX)
  200. // Creates a network object for each network available on the machine.
  201. bool CreateNetworks(bool include_ignored, NetworkList* networks) const;
  202. // Determines if a network should be ignored. This should only be determined
  203. // based on the network's property instead of any individual IP.
  204. bool IsIgnoredNetwork(const Network& network) const;
  205. // This function connects a UDP socket to a public address and returns the
  206. // local address associated it. Since it binds to the "any" address
  207. // internally, it returns the default local address on a multi-homed endpoint.
  208. IPAddress QueryDefaultLocalAddress(int family) const;
  209. private:
  210. friend class NetworkTest;
  211. // Creates a network monitor and listens for network updates.
  212. void StartNetworkMonitor();
  213. // Stops and removes the network monitor.
  214. void StopNetworkMonitor();
  215. // Called when it receives updates from the network monitor.
  216. void OnNetworksChanged();
  217. // Updates the networks and reschedules the next update.
  218. void UpdateNetworksContinually();
  219. // Only updates the networks; does not reschedule the next update.
  220. void UpdateNetworksOnce();
  221. Thread* thread_;
  222. bool sent_first_update_;
  223. int start_count_;
  224. std::vector<std::string> network_ignore_list_;
  225. std::unique_ptr<NetworkMonitorInterface> network_monitor_;
  226. };
  227. // Represents a Unix-type network interface, with a name and single address.
  228. class RTC_EXPORT Network {
  229. public:
  230. Network(const std::string& name,
  231. const std::string& description,
  232. const IPAddress& prefix,
  233. int prefix_length);
  234. Network(const std::string& name,
  235. const std::string& description,
  236. const IPAddress& prefix,
  237. int prefix_length,
  238. AdapterType type);
  239. Network(const Network&);
  240. ~Network();
  241. // This signal is fired whenever type() or underlying_type_for_vpn() changes.
  242. sigslot::signal1<const Network*> SignalTypeChanged;
  243. const DefaultLocalAddressProvider* default_local_address_provider() {
  244. return default_local_address_provider_;
  245. }
  246. void set_default_local_address_provider(
  247. const DefaultLocalAddressProvider* provider) {
  248. default_local_address_provider_ = provider;
  249. }
  250. void set_mdns_responder_provider(const MdnsResponderProvider* provider) {
  251. mdns_responder_provider_ = provider;
  252. }
  253. // Returns the name of the interface this network is associated with.
  254. const std::string& name() const { return name_; }
  255. // Returns the OS-assigned name for this network. This is useful for
  256. // debugging but should not be sent over the wire (for privacy reasons).
  257. const std::string& description() const { return description_; }
  258. // Returns the prefix for this network.
  259. const IPAddress& prefix() const { return prefix_; }
  260. // Returns the length, in bits, of this network's prefix.
  261. int prefix_length() const { return prefix_length_; }
  262. // |key_| has unique value per network interface. Used in sorting network
  263. // interfaces. Key is derived from interface name and it's prefix.
  264. std::string key() const { return key_; }
  265. // Returns the Network's current idea of the 'best' IP it has.
  266. // Or return an unset IP if this network has no active addresses.
  267. // Here is the rule on how we mark the IPv6 address as ignorable for WebRTC.
  268. // 1) return all global temporary dynamic and non-deprecated ones.
  269. // 2) if #1 not available, return global ones.
  270. // 3) if #2 not available, use ULA ipv6 as last resort. (ULA stands
  271. // for unique local address, which is not route-able in open
  272. // internet but might be useful for a close WebRTC deployment.
  273. // TODO(guoweis): rule #3 actually won't happen at current
  274. // implementation. The reason being that ULA address starting with
  275. // 0xfc 0r 0xfd will be grouped into its own Network. The result of
  276. // that is WebRTC will have one extra Network to generate candidates
  277. // but the lack of rule #3 shouldn't prevent turning on IPv6 since
  278. // ULA should only be tried in a close deployment anyway.
  279. // Note that when not specifying any flag, it's treated as case global
  280. // IPv6 address
  281. IPAddress GetBestIP() const;
  282. // Keep the original function here for now.
  283. // TODO(guoweis): Remove this when all callers are migrated to GetBestIP().
  284. IPAddress ip() const { return GetBestIP(); }
  285. // Adds an active IP address to this network. Does not check for duplicates.
  286. void AddIP(const InterfaceAddress& ip) { ips_.push_back(ip); }
  287. void AddIP(const IPAddress& ip) { ips_.push_back(rtc::InterfaceAddress(ip)); }
  288. // Sets the network's IP address list. Returns true if new IP addresses were
  289. // detected. Passing true to already_changed skips this check.
  290. bool SetIPs(const std::vector<InterfaceAddress>& ips, bool already_changed);
  291. // Get the list of IP Addresses associated with this network.
  292. const std::vector<InterfaceAddress>& GetIPs() const { return ips_; }
  293. // Clear the network's list of addresses.
  294. void ClearIPs() { ips_.clear(); }
  295. // Returns the mDNS responder that can be used to obfuscate the local IP
  296. // addresses of host candidates by mDNS names in ICE gathering. After a
  297. // name-address mapping is created by the mDNS responder, queries for the
  298. // created name will be resolved by the responder.
  299. webrtc::MdnsResponderInterface* GetMdnsResponder() const;
  300. // Returns the scope-id of the network's address.
  301. // Should only be relevant for link-local IPv6 addresses.
  302. int scope_id() const { return scope_id_; }
  303. void set_scope_id(int id) { scope_id_ = id; }
  304. // Indicates whether this network should be ignored, perhaps because
  305. // the IP is 0, or the interface is one we know is invalid.
  306. bool ignored() const { return ignored_; }
  307. void set_ignored(bool ignored) { ignored_ = ignored; }
  308. AdapterType type() const { return type_; }
  309. // When type() is ADAPTER_TYPE_VPN, this returns the type of the underlying
  310. // network interface used by the VPN, typically the preferred network type
  311. // (see for example, the method setUnderlyingNetworks(android.net.Network[])
  312. // on https://developer.android.com/reference/android/net/VpnService.html).
  313. // When this information is unavailable from the OS, ADAPTER_TYPE_UNKNOWN is
  314. // returned.
  315. AdapterType underlying_type_for_vpn() const {
  316. return underlying_type_for_vpn_;
  317. }
  318. void set_type(AdapterType type) {
  319. if (type_ == type) {
  320. return;
  321. }
  322. type_ = type;
  323. if (type != ADAPTER_TYPE_VPN) {
  324. underlying_type_for_vpn_ = ADAPTER_TYPE_UNKNOWN;
  325. }
  326. SignalTypeChanged(this);
  327. }
  328. void set_underlying_type_for_vpn(AdapterType type) {
  329. if (underlying_type_for_vpn_ == type) {
  330. return;
  331. }
  332. underlying_type_for_vpn_ = type;
  333. SignalTypeChanged(this);
  334. }
  335. bool IsVpn() const { return type_ == ADAPTER_TYPE_VPN; }
  336. bool IsCellular() const { return IsCellular(type_); }
  337. static bool IsCellular(AdapterType type) {
  338. switch (type) {
  339. case ADAPTER_TYPE_CELLULAR:
  340. case ADAPTER_TYPE_CELLULAR_2G:
  341. case ADAPTER_TYPE_CELLULAR_3G:
  342. case ADAPTER_TYPE_CELLULAR_4G:
  343. case ADAPTER_TYPE_CELLULAR_5G:
  344. return true;
  345. default:
  346. return false;
  347. }
  348. }
  349. uint16_t GetCost() const;
  350. // A unique id assigned by the network manager, which may be signaled
  351. // to the remote side in the candidate.
  352. uint16_t id() const { return id_; }
  353. void set_id(uint16_t id) { id_ = id; }
  354. int preference() const { return preference_; }
  355. void set_preference(int preference) { preference_ = preference; }
  356. // When we enumerate networks and find a previously-seen network is missing,
  357. // we do not remove it (because it may be used elsewhere). Instead, we mark
  358. // it inactive, so that we can detect network changes properly.
  359. bool active() const { return active_; }
  360. void set_active(bool active) {
  361. if (active_ != active) {
  362. active_ = active;
  363. }
  364. }
  365. // Debugging description of this network
  366. std::string ToString() const;
  367. private:
  368. const DefaultLocalAddressProvider* default_local_address_provider_ = nullptr;
  369. const MdnsResponderProvider* mdns_responder_provider_ = nullptr;
  370. std::string name_;
  371. std::string description_;
  372. IPAddress prefix_;
  373. int prefix_length_;
  374. std::string key_;
  375. std::vector<InterfaceAddress> ips_;
  376. int scope_id_;
  377. bool ignored_;
  378. AdapterType type_;
  379. AdapterType underlying_type_for_vpn_ = ADAPTER_TYPE_UNKNOWN;
  380. int preference_;
  381. bool active_ = true;
  382. uint16_t id_ = 0;
  383. bool use_differentiated_cellular_costs_ = false;
  384. friend class NetworkManager;
  385. };
  386. } // namespace rtc
  387. #endif // RTC_BASE_NETWORK_H_