network.h 18 KB

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