connection.cc revision 2cb3fa7317cfa3248cff72d0b9d64c4f2f630472
1// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "shill/connection.h"
6
7#include <arpa/inet.h>
8#include <linux/rtnetlink.h>
9
10#include <set>
11
12#include <base/strings/stringprintf.h>
13
14#include "shill/device_info.h"
15#include "shill/logging.h"
16#include "shill/net/rtnl_handler.h"
17#include "shill/resolver.h"
18#include "shill/routing_table.h"
19
20using base::Bind;
21using base::Closure;
22using base::Unretained;
23using std::deque;
24using std::set;
25using std::string;
26using std::vector;
27
28namespace shill {
29
30namespace Logging {
31static auto kModuleLogScope = ScopeLogger::kConnection;
32static string ObjectID(Connection *c) {
33  return c->interface_name();
34}
35}
36
37// static
38const uint32_t Connection::kDefaultMetric = 1;
39// static
40const uint32_t Connection::kNonDefaultMetricBase = 10;
41
42Connection::Binder::Binder(const string &name,
43                           const Closure &disconnect_callback)
44    : name_(name),
45      client_disconnect_callback_(disconnect_callback) {}
46
47Connection::Binder::~Binder() {
48  Attach(nullptr);
49}
50
51void Connection::Binder::Attach(const ConnectionRefPtr &to_connection) {
52  if (connection_) {
53    connection_->DetachBinder(this);
54    LOG(INFO) << name_ << ": unbound from connection: "
55              << connection_->interface_name();
56    connection_.reset();
57  }
58  if (to_connection) {
59    connection_ = to_connection->weak_ptr_factory_.GetWeakPtr();
60    connection_->AttachBinder(this);
61    LOG(INFO) << name_ << ": bound to connection: "
62              << connection_->interface_name();
63  }
64}
65
66void Connection::Binder::OnDisconnect() {
67  LOG(INFO) << name_ << ": bound connection disconnected: "
68            << connection_->interface_name();
69  connection_.reset();
70  if (!client_disconnect_callback_.is_null()) {
71    SLOG(connection_.get(), 2) << "Running client disconnect callback.";
72    client_disconnect_callback_.Run();
73  }
74}
75
76Connection::Connection(int interface_index,
77                       const std::string& interface_name,
78                       Technology::Identifier technology,
79                       const DeviceInfo *device_info)
80    : weak_ptr_factory_(this),
81      is_default_(false),
82      has_broadcast_domain_(false),
83      routing_request_count_(0),
84      interface_index_(interface_index),
85      interface_name_(interface_name),
86      technology_(technology),
87      local_(IPAddress::kFamilyUnknown),
88      gateway_(IPAddress::kFamilyUnknown),
89      lower_binder_(
90          interface_name_,
91          // Connection owns a single instance of |lower_binder_| so it's safe
92          // to use an Unretained callback.
93          Bind(&Connection::OnLowerDisconnect, Unretained(this))),
94      device_info_(device_info),
95      resolver_(Resolver::GetInstance()),
96      routing_table_(RoutingTable::GetInstance()),
97      rtnl_handler_(RTNLHandler::GetInstance()) {
98  SLOG(this, 2) << __func__ << "(" << interface_index << ", "
99                << interface_name << ", "
100                << Technology::NameFromIdentifier(technology) << ")";
101}
102
103Connection::~Connection() {
104  SLOG(this, 2) << __func__ << " " << interface_name_;
105
106  NotifyBindersOnDisconnect();
107
108  DCHECK(!routing_request_count_);
109  routing_table_->FlushRoutes(interface_index_);
110  routing_table_->FlushRoutesWithTag(interface_index_);
111  device_info_->FlushAddresses(interface_index_);
112}
113
114void Connection::UpdateFromIPConfig(const IPConfigRefPtr &config) {
115  SLOG(this, 2) << __func__ << " " << interface_name_;
116
117  const IPConfig::Properties &properties = config->properties();
118  IPAddress gateway(properties.address_family);
119  if (!properties.gateway.empty() &&
120      !gateway.SetAddressFromString(properties.gateway)) {
121    LOG(ERROR) << "Gateway address " << properties.gateway << " is invalid";
122    return;
123  }
124
125  IPAddress trusted_ip(properties.address_family);
126  if (!properties.trusted_ip.empty()) {
127    if (!trusted_ip.SetAddressFromString(properties.trusted_ip)) {
128      LOG(ERROR) << "Trusted IP address "
129                 << properties.trusted_ip << " is invalid";
130      return;
131    }
132    if (!PinHostRoute(trusted_ip, gateway)) {
133      LOG(ERROR) << "Unable to pin host route to " << properties.trusted_ip;
134      return;
135    }
136  }
137
138  IPAddress local(properties.address_family);
139  if (!local.SetAddressFromString(properties.address)) {
140    LOG(ERROR) << "Local address " << properties.address << " is invalid";
141    return;
142  }
143  local.set_prefix(properties.subnet_prefix);
144
145  IPAddress broadcast(properties.address_family);
146  if (properties.broadcast_address.empty()) {
147    if (properties.peer_address.empty()) {
148      LOG(WARNING) << "Broadcast address is not set.  Using default.";
149      broadcast = local.GetDefaultBroadcast();
150    }
151  } else if (!broadcast.SetAddressFromString(properties.broadcast_address)) {
152    LOG(ERROR) << "Broadcast address " << properties.broadcast_address
153               << " is invalid";
154    return;
155  }
156
157  IPAddress peer(properties.address_family);
158  if (!properties.peer_address.empty() &&
159      !peer.SetAddressFromString(properties.peer_address)) {
160    LOG(ERROR) << "Peer address " << properties.peer_address
161               << " is invalid";
162    return;
163  }
164
165  if (!FixGatewayReachability(&local, &peer, &gateway, trusted_ip)) {
166    LOG(WARNING) << "Expect limited network connectivity.";
167  }
168
169  if (device_info_->HasOtherAddress(interface_index_, local)) {
170    // The address has changed for this interface.  We need to flush
171    // everything and start over.
172    LOG(INFO) << __func__ << ": Flushing old addresses and routes.";
173    routing_table_->FlushRoutes(interface_index_);
174    device_info_->FlushAddresses(interface_index_);
175  }
176
177  LOG(INFO) << __func__ << ": Installing with parameters:"
178            << " local=" << local.ToString()
179            << " broadcast=" << broadcast.ToString()
180            << " peer=" << peer.ToString()
181            << " gateway=" << gateway.ToString();
182  rtnl_handler_->AddInterfaceAddress(interface_index_, local, broadcast, peer);
183
184  if (gateway.IsValid()) {
185    routing_table_->SetDefaultRoute(interface_index_, gateway,
186                                    GetMetric(is_default_));
187  }
188
189  // Install any explicitly configured routes at the default metric.
190  routing_table_->ConfigureRoutes(interface_index_, config, kDefaultMetric);
191
192  if (properties.blackhole_ipv6) {
193    routing_table_->CreateBlackholeRoute(interface_index_,
194                                         IPAddress::kFamilyIPv6,
195                                         kDefaultMetric);
196  }
197
198  // Save a copy of the last non-null DNS config.
199  if (!config->properties().dns_servers.empty()) {
200    dns_servers_ = config->properties().dns_servers;
201  }
202
203  if (!config->properties().domain_search.empty()) {
204    dns_domain_search_ = config->properties().domain_search;
205  }
206
207  if (!config->properties().domain_name.empty()) {
208    dns_domain_name_ = config->properties().domain_name;
209  }
210
211  ipconfig_rpc_identifier_ = config->GetRpcIdentifier();
212
213  PushDNSConfig();
214
215  local_ = local;
216  gateway_ = gateway;
217  has_broadcast_domain_ = !peer.IsValid();
218}
219
220void Connection::SetIsDefault(bool is_default) {
221  SLOG(this, 2) << __func__ << " " << interface_name_
222                << " (index " << interface_index_ << ") "
223                << is_default_ << " -> " << is_default;
224  if (is_default == is_default_) {
225    return;
226  }
227
228  routing_table_->SetDefaultMetric(interface_index_, GetMetric(is_default));
229
230  is_default_ = is_default;
231
232  PushDNSConfig();
233  if (is_default) {
234    DeviceRefPtr device = device_info_->GetDevice(interface_index_);
235    if (device) {
236      device->RequestPortalDetection();
237    }
238  }
239  routing_table_->FlushCache();
240}
241
242void Connection::UpdateDNSServers(const vector<string> &dns_servers) {
243  dns_servers_ = dns_servers;
244  PushDNSConfig();
245}
246
247void Connection::PushDNSConfig() {
248  if (!is_default_) {
249    return;
250  }
251
252  vector<string> domain_search = dns_domain_search_;
253  if (domain_search.empty() && !dns_domain_name_.empty()) {
254    SLOG(this, 2) << "Setting domain search to domain name "
255                  << dns_domain_name_;
256    domain_search.push_back(dns_domain_name_ + ".");
257  }
258  resolver_->SetDNSFromLists(dns_servers_, domain_search);
259}
260
261void Connection::RequestRouting() {
262  if (routing_request_count_++ == 0) {
263    DeviceRefPtr device = device_info_->GetDevice(interface_index_);
264    DCHECK(device.get());
265    if (!device.get()) {
266      LOG(ERROR) << "Device is NULL!";
267      return;
268    }
269    device->SetLooseRouting(true);
270  }
271}
272
273void Connection::ReleaseRouting() {
274  DCHECK_GT(routing_request_count_, 0);
275  if (--routing_request_count_ == 0) {
276    DeviceRefPtr device = device_info_->GetDevice(interface_index_);
277    DCHECK(device.get());
278    if (!device.get()) {
279      LOG(ERROR) << "Device is NULL!";
280      return;
281    }
282    device->SetLooseRouting(false);
283
284    // Clear any cached routes that might have accumulated while reverse-path
285    // filtering was disabled.
286    routing_table_->FlushCache();
287  }
288}
289
290bool Connection::RequestHostRoute(const IPAddress &address) {
291  // Set the prefix to be the entire address size.
292  IPAddress address_prefix(address);
293  address_prefix.set_prefix(address_prefix.GetLength() * 8);
294
295  // Do not set interface_index_ since this may not be the default route through
296  // which this destination can be found.  However, we should tag the created
297  // route with our interface index so we can clean this route up when this
298  // connection closes.  Also, add route query callback to determine the lower
299  // connection and bind to it.
300  if (!routing_table_->RequestRouteToHost(
301          address_prefix,
302          -1,
303          interface_index_,
304          Bind(&Connection::OnRouteQueryResponse,
305               weak_ptr_factory_.GetWeakPtr()))) {
306    LOG(ERROR) << "Could not request route to " << address.ToString();
307    return false;
308  }
309
310  return true;
311}
312
313string Connection::GetSubnetName() const {
314  return base::StringPrintf("%s/%d",
315                            local().GetNetworkPart().ToString().c_str(),
316                            local().prefix());
317}
318
319// static
320bool Connection::FixGatewayReachability(IPAddress *local,
321                                        IPAddress *peer,
322                                        IPAddress *gateway,
323                                        const IPAddress &trusted_ip) {
324  if (!gateway->IsValid()) {
325    LOG(WARNING) << "No gateway address was provided for this connection.";
326    return false;
327  }
328
329  if (peer->IsValid()) {
330    if (!gateway->Equals(*peer)) {
331      LOG(WARNING) << "Gateway address "
332                   << gateway->ToString()
333                   << " does not match peer address "
334                   << peer->ToString();
335      return false;
336    }
337    if (gateway->Equals(trusted_ip)) {
338      // In order to send outgoing traffic in a point-to-point network,
339      // the gateway IP address isn't of significance.  As opposed to
340      // broadcast networks, we never ARP for the gateway IP address,
341      // but just send the IP packet addressed to the recipient.  As
342      // such, since using the external trusted IP address as the
343      // gateway or peer wreaks havoc on the routing rules, we choose
344      // not to supply a gateway address.  Here's an example:
345      //
346      //     Client    <->  Internet  <->  VPN Gateway  <->  Internal Network
347      //   192.168.1.2                      10.0.1.25         172.16.5.0/24
348      //
349      // In this example, a client connects to a VPN gateway on its
350      // public IP address 10.0.1.25.  It gets issued an IP address
351      // from the VPN internal pool.  For some VPN gateways, this
352      // results in a pushed-down PPP configuration which specifies:
353      //
354      //    Client local address:   172.16.5.13
355      //    Client peer address:    10.0.1.25
356      //    Client default gateway: 10.0.1.25
357      //
358      // If we take this literally, we need to resolve the fact that
359      // 10.0.1.25 is now listed as the default gateway and interface
360      // peer address for the point-to-point interface.  However, in
361      // order to route tunneled packets to the VPN gateway we must
362      // use the external route through the physical interface and
363      // not the tunnel, or else we end up in an infinite loop
364      // re-entering the tunnel trying to route towards the VPN server.
365      //
366      // We can do this by pinning a route, but we would need to wait
367      // for the pinning process to complete before assigning this
368      // address.  Currently this process is asynchronous and will
369      // complete only after returning to the event loop.  Additionally,
370      // since there's no metric associated with assigning an address
371      // to an interface, it's always possible that having the peer
372      // address of the interface might still trump a host route.
373      //
374      // To solve this problem, we reset the peer and gateway
375      // addresses.  Neither is required in order to perform the
376      // underlying routing task.  A gateway route can be specified
377      // without an IP endpoint on point-to-point links, and simply
378      // specify the outbound interface index.  Similarly, a peer
379      // IP address is not necessary either, and will be assigned
380      // the same IP address as the local IP.  This approach
381      // simplifies routing and doesn't change the desired
382      // functional behavior.
383      //
384      LOG(INFO) << "Removing gateway and peer addresses to preserve "
385                << "routability to trusted IP address.";
386      peer->SetAddressToDefault();
387      gateway->SetAddressToDefault();
388    }
389    return true;
390  }
391
392  if (local->CanReachAddress(*gateway)) {
393    return true;
394  }
395
396  LOG(WARNING) << "Gateway "
397               << gateway->ToString()
398               << " is unreachable from local address/prefix "
399               << local->ToString() << "/" << local->prefix();
400
401  bool found_new_prefix = false;
402  size_t original_prefix = local->prefix();
403  // Only try to expand the netmask if the configured prefix is
404  // less than "all ones".  This special-cases the "all-ones"
405  // prefix as a forced conversion to point-to-point networking.
406  if (local->prefix() < IPAddress::GetMaxPrefixLength(local->family())) {
407    size_t prefix = original_prefix - 1;
408    for (; prefix >= local->GetMinPrefixLength(); --prefix) {
409      local->set_prefix(prefix);
410      if (local->CanReachAddress(*gateway)) {
411        found_new_prefix = true;
412        break;
413      }
414    }
415  }
416
417  if (!found_new_prefix) {
418    // Restore the original prefix since we cannot find a better one.
419    local->set_prefix(original_prefix);
420    DCHECK(!peer->IsValid());
421    LOG(WARNING) << "Assuming point-to-point configuration.";
422    *peer = *gateway;
423    return true;
424  }
425
426  LOG(WARNING) << "Mitigating this by setting local prefix to "
427               << local->prefix();
428  return true;
429}
430
431uint32_t Connection::GetMetric(bool is_default) {
432  // If this is not the default route, assign a metric based on the interface
433  // index.  This way all non-default routes (even to the same gateway IP) end
434  // up with unique metrics so they do not collide.
435  return is_default ? kDefaultMetric : kNonDefaultMetricBase + interface_index_;
436}
437
438bool Connection::PinHostRoute(const IPAddress &trusted_ip,
439                              const IPAddress &gateway) {
440  SLOG(this, 2) << __func__;
441  if (!trusted_ip.IsValid()) {
442    LOG(ERROR) << "No trusted IP -- unable to pin host route.";
443    return false;
444  }
445
446  if (!gateway.IsValid()) {
447    // Although we cannot pin a host route, we are also not going to create
448    // a gateway route that will interfere with our primary connection, so
449    // it is okay to return success here.
450    LOG(WARNING) << "No gateway -- unable to pin host route.";
451    return true;
452  }
453
454  return RequestHostRoute(trusted_ip);
455}
456
457void Connection::OnRouteQueryResponse(int interface_index,
458                                      const RoutingTableEntry &entry) {
459  SLOG(this, 2) << __func__ << "(" << interface_index << ", "
460                << entry.tag << ")" << " @ " << interface_name_;
461  lower_binder_.Attach(nullptr);
462  DeviceRefPtr device = device_info_->GetDevice(interface_index);
463  if (!device) {
464    LOG(ERROR) << "Unable to lookup device for index " << interface_index;
465    return;
466  }
467  ConnectionRefPtr connection = device->connection();
468  if (!connection) {
469    LOG(ERROR) << "Device " << interface_index << " has no connection.";
470    return;
471  }
472  lower_binder_.Attach(connection);
473  connection->CreateGatewayRoute();
474  device->OnConnectionUpdated();
475}
476
477bool Connection::CreateGatewayRoute() {
478  // Ensure that the gateway for the lower connection remains reachable,
479  // since we may create routes that conflict with it.
480  if (!has_broadcast_domain_) {
481    return false;
482  }
483
484  // If there is no gateway, don't try to create a route to it.
485  if (!gateway_.IsValid()) {
486    return false;
487  }
488
489  // It is not worth keeping track of this route, since it is benign,
490  // and only pins persistent state that was already true of the connection.
491  // If DHCP parameters change later (without the connection having been
492  // destroyed and recreated), the binding processes will likely terminate
493  // and restart, causing a new link route to be created.
494  return routing_table_->CreateLinkRoute(interface_index_, local_, gateway_);
495}
496
497void Connection::OnLowerDisconnect() {
498  SLOG(this, 2) << __func__ << " @ " << interface_name_;
499  // Ensures that |this| instance doesn't get destroyed in the middle of
500  // notifying the binders. This method needs to be separate from
501  // NotifyBindersOnDisconnect because the latter may be invoked by Connection's
502  // destructor when |this| instance's reference count is already 0.
503  ConnectionRefPtr connection(this);
504  connection->NotifyBindersOnDisconnect();
505}
506
507void Connection::NotifyBindersOnDisconnect() {
508  // Note that this method may be invoked by the destructor.
509  SLOG(this, 2) << __func__ << " @ " << interface_name_;
510
511  // Unbinds the lower connection before notifying the binders. This ensures
512  // correct behavior in case of circular binding.
513  lower_binder_.Attach(nullptr);
514  while (!binders_.empty()) {
515    // Pop the binder first and then notify it to ensure that each binder is
516    // notified only once.
517    Binder *binder = binders_.front();
518    binders_.pop_front();
519    binder->OnDisconnect();
520  }
521}
522
523void Connection::AttachBinder(Binder *binder) {
524  SLOG(this, 2) << __func__ << "(" << binder->name() << ")" << " @ "
525                            << interface_name_;
526  binders_.push_back(binder);
527}
528
529void Connection::DetachBinder(Binder *binder) {
530  SLOG(this, 2) << __func__ << "(" << binder->name() << ")" << " @ "
531                            << interface_name_;
532  for (auto it = binders_.begin(); it != binders_.end(); ++it) {
533    if (binder == *it) {
534      binders_.erase(it);
535      return;
536    }
537  }
538}
539
540ConnectionRefPtr Connection::GetCarrierConnection() {
541  SLOG(this, 2) << __func__ << " @ " << interface_name_;
542  set<Connection *> visited;
543  ConnectionRefPtr carrier = this;
544  while (carrier->GetLowerConnection()) {
545    if (ContainsKey(visited, carrier.get())) {
546      LOG(ERROR) << "Circular connection chain starting at: "
547                 << carrier->interface_name();
548      // If a loop is detected return a NULL value to signal that the carrier
549      // connection is unknown.
550      return nullptr;
551    }
552    visited.insert(carrier.get());
553    carrier = carrier->GetLowerConnection();
554  }
555  SLOG(this, 2) << "Carrier connection: " << carrier->interface_name()
556                << " @ " << interface_name_;
557  return carrier;
558}
559
560bool Connection::IsIPv6() {
561  return local_.family() == IPAddress::kFamilyIPv6;
562}
563
564}  // namespace shill
565