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