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