connection.cc revision 182888eab7478f28001b1235f8d2b75063445db8
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 if (!local().IsValid()) { 315 return ""; 316 } 317 return base::StringPrintf("%s/%d", 318 local().GetNetworkPart().ToString().c_str(), 319 local().prefix()); 320} 321 322// static 323bool Connection::FixGatewayReachability(IPAddress *local, 324 IPAddress *peer, 325 IPAddress *gateway, 326 const IPAddress &trusted_ip) { 327 if (!gateway->IsValid()) { 328 LOG(WARNING) << "No gateway address was provided for this connection."; 329 return false; 330 } 331 332 if (peer->IsValid()) { 333 if (!gateway->Equals(*peer)) { 334 LOG(WARNING) << "Gateway address " 335 << gateway->ToString() 336 << " does not match peer address " 337 << peer->ToString(); 338 return false; 339 } 340 if (gateway->Equals(trusted_ip)) { 341 // In order to send outgoing traffic in a point-to-point network, 342 // the gateway IP address isn't of significance. As opposed to 343 // broadcast networks, we never ARP for the gateway IP address, 344 // but just send the IP packet addressed to the recipient. As 345 // such, since using the external trusted IP address as the 346 // gateway or peer wreaks havoc on the routing rules, we choose 347 // not to supply a gateway address. Here's an example: 348 // 349 // Client <-> Internet <-> VPN Gateway <-> Internal Network 350 // 192.168.1.2 10.0.1.25 172.16.5.0/24 351 // 352 // In this example, a client connects to a VPN gateway on its 353 // public IP address 10.0.1.25. It gets issued an IP address 354 // from the VPN internal pool. For some VPN gateways, this 355 // results in a pushed-down PPP configuration which specifies: 356 // 357 // Client local address: 172.16.5.13 358 // Client peer address: 10.0.1.25 359 // Client default gateway: 10.0.1.25 360 // 361 // If we take this literally, we need to resolve the fact that 362 // 10.0.1.25 is now listed as the default gateway and interface 363 // peer address for the point-to-point interface. However, in 364 // order to route tunneled packets to the VPN gateway we must 365 // use the external route through the physical interface and 366 // not the tunnel, or else we end up in an infinite loop 367 // re-entering the tunnel trying to route towards the VPN server. 368 // 369 // We can do this by pinning a route, but we would need to wait 370 // for the pinning process to complete before assigning this 371 // address. Currently this process is asynchronous and will 372 // complete only after returning to the event loop. Additionally, 373 // since there's no metric associated with assigning an address 374 // to an interface, it's always possible that having the peer 375 // address of the interface might still trump a host route. 376 // 377 // To solve this problem, we reset the peer and gateway 378 // addresses. Neither is required in order to perform the 379 // underlying routing task. A gateway route can be specified 380 // without an IP endpoint on point-to-point links, and simply 381 // specify the outbound interface index. Similarly, a peer 382 // IP address is not necessary either, and will be assigned 383 // the same IP address as the local IP. This approach 384 // simplifies routing and doesn't change the desired 385 // functional behavior. 386 // 387 LOG(INFO) << "Removing gateway and peer addresses to preserve " 388 << "routability to trusted IP address."; 389 peer->SetAddressToDefault(); 390 gateway->SetAddressToDefault(); 391 } 392 return true; 393 } 394 395 if (local->CanReachAddress(*gateway)) { 396 return true; 397 } 398 399 LOG(WARNING) << "Gateway " 400 << gateway->ToString() 401 << " is unreachable from local address/prefix " 402 << local->ToString() << "/" << local->prefix(); 403 404 bool found_new_prefix = false; 405 size_t original_prefix = local->prefix(); 406 // Only try to expand the netmask if the configured prefix is 407 // less than "all ones". This special-cases the "all-ones" 408 // prefix as a forced conversion to point-to-point networking. 409 if (local->prefix() < IPAddress::GetMaxPrefixLength(local->family())) { 410 size_t prefix = original_prefix - 1; 411 for (; prefix >= local->GetMinPrefixLength(); --prefix) { 412 local->set_prefix(prefix); 413 if (local->CanReachAddress(*gateway)) { 414 found_new_prefix = true; 415 break; 416 } 417 } 418 } 419 420 if (!found_new_prefix) { 421 // Restore the original prefix since we cannot find a better one. 422 local->set_prefix(original_prefix); 423 DCHECK(!peer->IsValid()); 424 LOG(WARNING) << "Assuming point-to-point configuration."; 425 *peer = *gateway; 426 return true; 427 } 428 429 LOG(WARNING) << "Mitigating this by setting local prefix to " 430 << local->prefix(); 431 return true; 432} 433 434uint32_t Connection::GetMetric(bool is_default) { 435 // If this is not the default route, assign a metric based on the interface 436 // index. This way all non-default routes (even to the same gateway IP) end 437 // up with unique metrics so they do not collide. 438 return is_default ? kDefaultMetric : kNonDefaultMetricBase + interface_index_; 439} 440 441bool Connection::PinHostRoute(const IPAddress &trusted_ip, 442 const IPAddress &gateway) { 443 SLOG(this, 2) << __func__; 444 if (!trusted_ip.IsValid()) { 445 LOG(ERROR) << "No trusted IP -- unable to pin host route."; 446 return false; 447 } 448 449 if (!gateway.IsValid()) { 450 // Although we cannot pin a host route, we are also not going to create 451 // a gateway route that will interfere with our primary connection, so 452 // it is okay to return success here. 453 LOG(WARNING) << "No gateway -- unable to pin host route."; 454 return true; 455 } 456 457 return RequestHostRoute(trusted_ip); 458} 459 460void Connection::OnRouteQueryResponse(int interface_index, 461 const RoutingTableEntry &entry) { 462 SLOG(this, 2) << __func__ << "(" << interface_index << ", " 463 << entry.tag << ")" << " @ " << interface_name_; 464 lower_binder_.Attach(nullptr); 465 DeviceRefPtr device = device_info_->GetDevice(interface_index); 466 if (!device) { 467 LOG(ERROR) << "Unable to lookup device for index " << interface_index; 468 return; 469 } 470 ConnectionRefPtr connection = device->connection(); 471 if (!connection) { 472 LOG(ERROR) << "Device " << interface_index << " has no connection."; 473 return; 474 } 475 lower_binder_.Attach(connection); 476 connection->CreateGatewayRoute(); 477 device->OnConnectionUpdated(); 478} 479 480bool Connection::CreateGatewayRoute() { 481 // Ensure that the gateway for the lower connection remains reachable, 482 // since we may create routes that conflict with it. 483 if (!has_broadcast_domain_) { 484 return false; 485 } 486 487 // If there is no gateway, don't try to create a route to it. 488 if (!gateway_.IsValid()) { 489 return false; 490 } 491 492 // It is not worth keeping track of this route, since it is benign, 493 // and only pins persistent state that was already true of the connection. 494 // If DHCP parameters change later (without the connection having been 495 // destroyed and recreated), the binding processes will likely terminate 496 // and restart, causing a new link route to be created. 497 return routing_table_->CreateLinkRoute(interface_index_, local_, gateway_); 498} 499 500void Connection::OnLowerDisconnect() { 501 SLOG(this, 2) << __func__ << " @ " << interface_name_; 502 // Ensures that |this| instance doesn't get destroyed in the middle of 503 // notifying the binders. This method needs to be separate from 504 // NotifyBindersOnDisconnect because the latter may be invoked by Connection's 505 // destructor when |this| instance's reference count is already 0. 506 ConnectionRefPtr connection(this); 507 connection->NotifyBindersOnDisconnect(); 508} 509 510void Connection::NotifyBindersOnDisconnect() { 511 // Note that this method may be invoked by the destructor. 512 SLOG(this, 2) << __func__ << " @ " << interface_name_; 513 514 // Unbinds the lower connection before notifying the binders. This ensures 515 // correct behavior in case of circular binding. 516 lower_binder_.Attach(nullptr); 517 while (!binders_.empty()) { 518 // Pop the binder first and then notify it to ensure that each binder is 519 // notified only once. 520 Binder *binder = binders_.front(); 521 binders_.pop_front(); 522 binder->OnDisconnect(); 523 } 524} 525 526void Connection::AttachBinder(Binder *binder) { 527 SLOG(this, 2) << __func__ << "(" << binder->name() << ")" << " @ " 528 << interface_name_; 529 binders_.push_back(binder); 530} 531 532void Connection::DetachBinder(Binder *binder) { 533 SLOG(this, 2) << __func__ << "(" << binder->name() << ")" << " @ " 534 << interface_name_; 535 for (auto it = binders_.begin(); it != binders_.end(); ++it) { 536 if (binder == *it) { 537 binders_.erase(it); 538 return; 539 } 540 } 541} 542 543ConnectionRefPtr Connection::GetCarrierConnection() { 544 SLOG(this, 2) << __func__ << " @ " << interface_name_; 545 set<Connection *> visited; 546 ConnectionRefPtr carrier = this; 547 while (carrier->GetLowerConnection()) { 548 if (ContainsKey(visited, carrier.get())) { 549 LOG(ERROR) << "Circular connection chain starting at: " 550 << carrier->interface_name(); 551 // If a loop is detected return a NULL value to signal that the carrier 552 // connection is unknown. 553 return nullptr; 554 } 555 visited.insert(carrier.get()); 556 carrier = carrier->GetLowerConnection(); 557 } 558 SLOG(this, 2) << "Carrier connection: " << carrier->interface_name() 559 << " @ " << interface_name_; 560 return carrier; 561} 562 563bool Connection::IsIPv6() { 564 return local_.family() == IPAddress::kFamilyIPv6; 565} 566 567} // namespace shill 568