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