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