blob: b3b43d834fc08b50ec1a9f787b15253debdee675 [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
Patrik Höglund581df612017-10-02 09:12:39 +000041static const uint16_t kNetworkCostMax = 999;
42static const uint16_t kNetworkCostHigh = 900;
43static const uint16_t kNetworkCostUnknown = 50;
44static const uint16_t kNetworkCostLow = 10;
45static const uint16_t kNetworkCostMin = 0;
46
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +020047// By default, ignore loopback interfaces on the host.
48const int kDefaultNetworkIgnoreMask = ADAPTER_TYPE_LOOPBACK;
49
50// Makes a string key for this network. Used in the network manager's maps.
51// Network objects are keyed on interface name, network prefix and the
52// length of that prefix.
53std::string MakeNetworkKey(const std::string& name, const IPAddress& prefix,
54 int prefix_length);
55
56class 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 16:09:33 -0700150
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200151 // Defaults to true.
deadbeef3427f532017-07-26 16:09:33 -0700152 // TODO(deadbeef): Remove this. Nothing but tests use this; IPv6 is enabled
153 // by default everywhere else.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200154 bool ipv6_enabled() const { return ipv6_enabled_; }
155 void set_ipv6_enabled(bool enabled) { ipv6_enabled_ = enabled; }
156
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200157 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 07:52:50 +0200190
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-11 20:07:37 -0700232 // Defaults to false.
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200233 void set_ignore_non_default_routes(bool value) {
deadbeefbe7e9c62017-07-11 20:07:37 -0700234 ignore_non_default_routes_ = value;
Henrik Kjellanderec78f1c2017-06-29 07:52:50 +0200235 }
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
274 AdapterType GetAdapterTypeFromName(const char* network_name) const;
275
276 Thread* thread_;
277 bool sent_first_update_;
278 int start_count_;
279 std::vector<std::string> network_ignore_list_;
280 bool ignore_non_default_routes_;
281 std::unique_ptr<NetworkMonitorInterface> network_monitor_;
282};
283
284// Represents a Unix-type network interface, with a name and single address.
285class Network {
286 public:
287 Network(const std::string& name,
288 const std::string& description,
289 const IPAddress& prefix,
290 int prefix_length);
291
292 Network(const std::string& name,
293 const std::string& description,
294 const IPAddress& prefix,
295 int prefix_length,
296 AdapterType type);
297 ~Network();
298
299 sigslot::signal1<const Network*> SignalTypeChanged;
300
301 const DefaultLocalAddressProvider* default_local_address_provider() {
302 return default_local_address_provider_;
303 }
304 void set_default_local_address_provider(
305 const DefaultLocalAddressProvider* provider) {
306 default_local_address_provider_ = provider;
307 }
308
309 // Returns the name of the interface this network is associated wtih.
310 const std::string& name() const { return name_; }
311
312 // Returns the OS-assigned name for this network. This is useful for
313 // debugging but should not be sent over the wire (for privacy reasons).
314 const std::string& description() const { return description_; }
315
316 // Returns the prefix for this network.
317 const IPAddress& prefix() const { return prefix_; }
318 // Returns the length, in bits, of this network's prefix.
319 int prefix_length() const { return prefix_length_; }
320
321 // |key_| has unique value per network interface. Used in sorting network
322 // interfaces. Key is derived from interface name and it's prefix.
323 std::string key() const { return key_; }
324
325 // Returns the Network's current idea of the 'best' IP it has.
326 // Or return an unset IP if this network has no active addresses.
327 // Here is the rule on how we mark the IPv6 address as ignorable for WebRTC.
328 // 1) return all global temporary dynamic and non-deprecrated ones.
329 // 2) if #1 not available, return global ones.
330 // 3) if #2 not available, use ULA ipv6 as last resort. (ULA stands
331 // for unique local address, which is not route-able in open
332 // internet but might be useful for a close WebRTC deployment.
333
334 // TODO(guoweis): rule #3 actually won't happen at current
335 // implementation. The reason being that ULA address starting with
336 // 0xfc 0r 0xfd will be grouped into its own Network. The result of
337 // that is WebRTC will have one extra Network to generate candidates
338 // but the lack of rule #3 shouldn't prevent turning on IPv6 since
339 // ULA should only be tried in a close deployment anyway.
340
341 // Note that when not specifying any flag, it's treated as case global
342 // IPv6 address
343 IPAddress GetBestIP() const;
344
345 // Keep the original function here for now.
346 // TODO(guoweis): Remove this when all callers are migrated to GetBestIP().
347 IPAddress ip() const { return GetBestIP(); }
348
349 // Adds an active IP address to this network. Does not check for duplicates.
350 void AddIP(const InterfaceAddress& ip) { ips_.push_back(ip); }
351
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.
356 const std::vector<InterfaceAddress>& GetIPs() const { return ips_;}
357 // 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_; }
371 void set_type(AdapterType type) {
372 if (type_ == type) {
373 return;
374 }
375 type_ = type;
376 SignalTypeChanged(this);
377 }
378
379 uint16_t GetCost() const {
380 switch (type_) {
381 case rtc::ADAPTER_TYPE_ETHERNET:
382 case rtc::ADAPTER_TYPE_LOOPBACK:
383 return kNetworkCostMin;
384 case rtc::ADAPTER_TYPE_WIFI:
385 case rtc::ADAPTER_TYPE_VPN:
386 return kNetworkCostLow;
387 case rtc::ADAPTER_TYPE_CELLULAR:
388 return kNetworkCostHigh;
389 default:
390 return kNetworkCostUnknown;
391 }
392 }
393 // A unique id assigned by the network manager, which may be signaled
394 // to the remote side in the candidate.
395 uint16_t id() const { return id_; }
396 void set_id(uint16_t id) { id_ = id; }
397
398 int preference() const { return preference_; }
399 void set_preference(int preference) { preference_ = preference; }
400
401 // When we enumerate networks and find a previously-seen network is missing,
402 // we do not remove it (because it may be used elsewhere). Instead, we mark
403 // it inactive, so that we can detect network changes properly.
404 bool active() const { return active_; }
405 void set_active(bool active) {
406 if (active_ != active) {
407 active_ = active;
408 }
409 }
410
411 // Debugging description of this network
412 std::string ToString() const;
413
414 private:
415 const DefaultLocalAddressProvider* default_local_address_provider_ = nullptr;
416 std::string name_;
417 std::string description_;
418 IPAddress prefix_;
419 int prefix_length_;
420 std::string key_;
421 std::vector<InterfaceAddress> ips_;
422 int scope_id_;
423 bool ignored_;
424 AdapterType type_;
425 int preference_;
426 bool active_ = true;
427 uint16_t id_ = 0;
428
429 friend class NetworkManager;
430};
431
432} // namespace rtc
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000433
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200434#endif // RTC_BASE_NETWORK_H_