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