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