blob: aa806af5140ca60baba77a5e97c6e77efe05e575 [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 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_;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200191
192 std::unique_ptr<rtc::Network> ipv4_any_address_network_;
193 std::unique_ptr<rtc::Network> ipv6_any_address_network_;
194
195 IPAddress default_local_ipv4_address_;
196 IPAddress default_local_ipv6_address_;
197 // We use 16 bits to save the bandwidth consumption when sending the network
198 // id over the Internet. It is OK that the 16-bit integer overflows to get a
199 // network id 0 because we only compare the network ids in the old and the new
200 // best connections in the transport channel.
201 uint16_t next_available_network_id_ = 1;
202};
203
204// Basic implementation of the NetworkManager interface that gets list
205// of networks using OS APIs.
206class BasicNetworkManager : public NetworkManagerBase,
207 public MessageHandler,
208 public sigslot::has_slots<> {
209 public:
210 BasicNetworkManager();
211 ~BasicNetworkManager() override;
212
213 void StartUpdating() override;
214 void StopUpdating() override;
215
216 void DumpNetworks() override;
217
218 // MessageHandler interface.
219 void OnMessage(Message* msg) override;
220 bool started() { return start_count_ > 0; }
221
222 // Sets the network ignore list, which is empty by default. Any network on the
223 // ignore list will be filtered from network enumeration results.
224 void set_network_ignore_list(const std::vector<std::string>& list) {
225 network_ignore_list_ = list;
226 }
227
228#if defined(WEBRTC_LINUX)
229 // Sets the flag for ignoring non-default routes.
deadbeefbe7e9c62017-07-11 20:07:37 -0700230 // Defaults to false.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200231 void set_ignore_non_default_routes(bool value) {
deadbeefbe7e9c62017-07-11 20:07:37 -0700232 ignore_non_default_routes_ = value;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200233 }
234#endif
235
236 protected:
237#if defined(WEBRTC_POSIX)
238 // Separated from CreateNetworks for tests.
239 void ConvertIfAddrs(ifaddrs* interfaces,
240 IfAddrsConverter* converter,
241 bool include_ignored,
242 NetworkList* networks) const;
243#endif // defined(WEBRTC_POSIX)
244
245 // Creates a network object for each network available on the machine.
246 bool CreateNetworks(bool include_ignored, NetworkList* networks) const;
247
248 // Determines if a network should be ignored. This should only be determined
249 // based on the network's property instead of any individual IP.
250 bool IsIgnoredNetwork(const Network& network) const;
251
252 // This function connects a UDP socket to a public address and returns the
253 // local address associated it. Since it binds to the "any" address
254 // internally, it returns the default local address on a multi-homed endpoint.
255 IPAddress QueryDefaultLocalAddress(int family) const;
256
257 private:
258 friend class NetworkTest;
259
260 // Creates a network monitor and listens for network updates.
261 void StartNetworkMonitor();
262 // Stops and removes the network monitor.
263 void StopNetworkMonitor();
264 // Called when it receives updates from the network monitor.
265 void OnNetworksChanged();
266
267 // Updates the networks and reschedules the next update.
268 void UpdateNetworksContinually();
269 // Only updates the networks; does not reschedule the next update.
270 void UpdateNetworksOnce();
271
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200272 Thread* thread_;
273 bool sent_first_update_;
274 int start_count_;
275 std::vector<std::string> network_ignore_list_;
276 bool ignore_non_default_routes_;
277 std::unique_ptr<NetworkMonitorInterface> network_monitor_;
278};
279
280// Represents a Unix-type network interface, with a name and single address.
281class Network {
282 public:
283 Network(const std::string& name,
284 const std::string& description,
285 const IPAddress& prefix,
286 int prefix_length);
287
288 Network(const std::string& name,
289 const std::string& description,
290 const IPAddress& prefix,
291 int prefix_length,
292 AdapterType type);
Steve Anton9de3aac2017-10-24 10:08:26 -0700293 Network(const Network&);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200294 ~Network();
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700295 // This signal is fired whenever type() or underlying_type_for_vpn() changes.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200296 sigslot::signal1<const Network*> SignalTypeChanged;
297
298 const DefaultLocalAddressProvider* default_local_address_provider() {
299 return default_local_address_provider_;
300 }
301 void set_default_local_address_provider(
302 const DefaultLocalAddressProvider* provider) {
303 default_local_address_provider_ = provider;
304 }
305
306 // Returns the name of the interface this network is associated wtih.
307 const std::string& name() const { return name_; }
308
309 // Returns the OS-assigned name for this network. This is useful for
310 // debugging but should not be sent over the wire (for privacy reasons).
311 const std::string& description() const { return description_; }
312
313 // Returns the prefix for this network.
314 const IPAddress& prefix() const { return prefix_; }
315 // Returns the length, in bits, of this network's prefix.
316 int prefix_length() const { return prefix_length_; }
317
318 // |key_| has unique value per network interface. Used in sorting network
319 // interfaces. Key is derived from interface name and it's prefix.
320 std::string key() const { return key_; }
321
322 // Returns the Network's current idea of the 'best' IP it has.
323 // Or return an unset IP if this network has no active addresses.
324 // Here is the rule on how we mark the IPv6 address as ignorable for WebRTC.
325 // 1) return all global temporary dynamic and non-deprecrated ones.
326 // 2) if #1 not available, return global ones.
327 // 3) if #2 not available, use ULA ipv6 as last resort. (ULA stands
328 // for unique local address, which is not route-able in open
329 // internet but might be useful for a close WebRTC deployment.
330
331 // TODO(guoweis): rule #3 actually won't happen at current
332 // implementation. The reason being that ULA address starting with
333 // 0xfc 0r 0xfd will be grouped into its own Network. The result of
334 // that is WebRTC will have one extra Network to generate candidates
335 // but the lack of rule #3 shouldn't prevent turning on IPv6 since
336 // ULA should only be tried in a close deployment anyway.
337
338 // Note that when not specifying any flag, it's treated as case global
339 // IPv6 address
340 IPAddress GetBestIP() const;
341
342 // Keep the original function here for now.
343 // TODO(guoweis): Remove this when all callers are migrated to GetBestIP().
344 IPAddress ip() const { return GetBestIP(); }
345
346 // Adds an active IP address to this network. Does not check for duplicates.
347 void AddIP(const InterfaceAddress& ip) { ips_.push_back(ip); }
Taylor Brandstetter01cb5f22018-03-07 15:49:32 -0800348 void AddIP(const IPAddress& ip) { ips_.push_back(rtc::InterfaceAddress(ip)); }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200349
350 // Sets the network's IP address list. Returns true if new IP addresses were
351 // detected. Passing true to already_changed skips this check.
352 bool SetIPs(const std::vector<InterfaceAddress>& ips, bool already_changed);
353 // Get the list of IP Addresses associated with this network.
Yves Gerey665174f2018-06-19 15:03:05 +0200354 const std::vector<InterfaceAddress>& GetIPs() const { return ips_; }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200355 // Clear the network's list of addresses.
356 void ClearIPs() { ips_.clear(); }
Qingsi Wang09619332018-09-12 22:51:55 -0700357 // Sets the mDNS responder that can be used to obfuscate the local IP
358 // addresses of host candidates by mDNS names in ICE gathering. After a
359 // name-address mapping is created by the mDNS responder, queries for the
360 // created name will be resolved by the responder.
361 //
362 // The mDNS responder, if not null, should outlive this rtc::Network.
Qingsi Wang7852d292018-10-31 11:17:07 -0700363 void SetMdnsResponder(webrtc::MdnsResponderInterface* mdns_responder) {
Qingsi Wang09619332018-09-12 22:51:55 -0700364 mdns_responder_ = mdns_responder;
365 }
366 // Returns the mDNS responder, which is null by default.
Qingsi Wang7852d292018-10-31 11:17:07 -0700367 webrtc::MdnsResponderInterface* GetMdnsResponder() const {
Qingsi Wang09619332018-09-12 22:51:55 -0700368 return mdns_responder_;
369 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200370
371 // Returns the scope-id of the network's address.
372 // Should only be relevant for link-local IPv6 addresses.
373 int scope_id() const { return scope_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.
378 bool ignored() const { return ignored_; }
379 void set_ignored(bool ignored) { ignored_ = ignored; }
380
381 AdapterType type() const { return type_; }
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700382 // 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.
388 AdapterType underlying_type_for_vpn() const {
389 return underlying_type_for_vpn_;
390 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200391 void set_type(AdapterType type) {
392 if (type_ == type) {
393 return;
394 }
395 type_ = type;
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700396 if (type != ADAPTER_TYPE_VPN) {
397 underlying_type_for_vpn_ = ADAPTER_TYPE_UNKNOWN;
398 }
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200399 SignalTypeChanged(this);
400 }
401
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700402 void set_underlying_type_for_vpn(AdapterType type) {
403 if (underlying_type_for_vpn_ == type) {
404 return;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200405 }
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700406 underlying_type_for_vpn_ = type;
407 SignalTypeChanged(this);
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200408 }
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700409
410 bool IsVpn() const { return type_ == ADAPTER_TYPE_VPN; }
411
412 uint16_t GetCost() const;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200413 // A unique id assigned by the network manager, which may be signaled
414 // to the remote side in the candidate.
415 uint16_t id() const { return id_; }
416 void set_id(uint16_t id) { id_ = id; }
417
418 int preference() const { return preference_; }
419 void set_preference(int preference) { preference_ = preference; }
420
421 // When we enumerate networks and find a previously-seen network is missing,
422 // we do not remove it (because it may be used elsewhere). Instead, we mark
423 // it inactive, so that we can detect network changes properly.
424 bool active() const { return active_; }
425 void set_active(bool active) {
426 if (active_ != active) {
427 active_ = active;
428 }
429 }
430
431 // Debugging description of this network
432 std::string ToString() const;
433
434 private:
435 const DefaultLocalAddressProvider* default_local_address_provider_ = nullptr;
436 std::string name_;
437 std::string description_;
438 IPAddress prefix_;
439 int prefix_length_;
440 std::string key_;
441 std::vector<InterfaceAddress> ips_;
Qingsi Wang7852d292018-10-31 11:17:07 -0700442 webrtc::MdnsResponderInterface* mdns_responder_ = nullptr;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200443 int scope_id_;
444 bool ignored_;
445 AdapterType type_;
Qingsi Wangde2ed7d2018-04-27 14:25:37 -0700446 AdapterType underlying_type_for_vpn_ = ADAPTER_TYPE_UNKNOWN;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200447 int preference_;
448 bool active_ = true;
449 uint16_t id_ = 0;
450
451 friend class NetworkManager;
452};
453
454} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000455
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200456#endif // RTC_BASE_NETWORK_H_