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