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