summaryrefslogtreecommitdiffstats
path: root/extensions/shell/browser/shell_network_controller_chromeos.cc
blob: 4ff45c70b6227880ebe3421c5030f47937edcfac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/shell/browser/shell_network_controller_chromeos.h"

#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/strings/stringprintf.h"
#include "base/time/time.h"
#include "chromeos/network/network_connection_handler.h"
#include "chromeos/network/network_device_handler.h"
#include "chromeos/network/network_handler.h"
#include "chromeos/network/network_handler_callbacks.h"
#include "chromeos/network/network_state.h"
#include "chromeos/network/network_state_handler.h"
#include "third_party/cros_system_api/dbus/service_constants.h"

namespace extensions {

namespace {

// Frequency at which networks should be scanned when not connected to a network
// or when connected to a non-preferred network.
const int kScanIntervalSec = 10;

void HandleEnableWifiError(const std::string& error_name,
                           scoped_ptr<base::DictionaryValue> error_data) {
  LOG(WARNING) << "Unable to enable wifi: " << error_name;
}

// Returns a human-readable name for the network described by |network|.
std::string GetNetworkName(const chromeos::NetworkState& network) {
  return !network.name().empty()
             ? network.name()
             : base::StringPrintf("[%s]", network.type().c_str());
}

// Returns true if shill is either connected or connecting to a network.
bool IsConnectedOrConnecting() {
  chromeos::NetworkStateHandler* state_handler =
      chromeos::NetworkHandler::Get()->network_state_handler();
  return state_handler->ConnectedNetworkByType(
             chromeos::NetworkTypePattern::Default()) ||
         state_handler->ConnectingNetworkByType(
             chromeos::NetworkTypePattern::Default());
}

}  // namespace

ShellNetworkController::ShellNetworkController(
    const std::string& preferred_network_name)
    : state_(STATE_IDLE),
      preferred_network_name_(preferred_network_name),
      preferred_network_is_active_(false),
      weak_ptr_factory_(this) {
  chromeos::NetworkStateHandler* state_handler =
      chromeos::NetworkHandler::Get()->network_state_handler();
  state_handler->AddObserver(this, FROM_HERE);
  state_handler->SetTechnologyEnabled(
      chromeos::NetworkTypePattern::Primitive(shill::kTypeWifi),
      true,
      base::Bind(&HandleEnableWifiError));

  // If we're unconnected, trigger a connection attempt and start scanning.
  NetworkConnectionStateChanged(NULL);
}

ShellNetworkController::~ShellNetworkController() {
  chromeos::NetworkHandler::Get()->network_state_handler()->RemoveObserver(
      this, FROM_HERE);
}

void ShellNetworkController::NetworkListChanged() {
  VLOG(1) << "Network list changed";
  ConnectIfUnconnected();
}

void ShellNetworkController::NetworkConnectionStateChanged(
    const chromeos::NetworkState* network) {
  if (network) {
    VLOG(1) << "Network connection state changed:"
            << " name=" << GetNetworkName(*network)
            << " type=" << network->type() << " path=" << network->path()
            << " state=" << network->connection_state();
  } else {
    VLOG(1) << "Network connection state changed: [none]";
  }

  const chromeos::NetworkState* wifi_network = GetActiveWiFiNetwork();
  preferred_network_is_active_ =
      wifi_network && wifi_network->name() == preferred_network_name_;
  VLOG(2) << "Active WiFi network is "
          << (wifi_network ? wifi_network->name() : std::string("[none]"));

  if (preferred_network_is_active_ ||
      (preferred_network_name_.empty() && wifi_network)) {
    SetScanningEnabled(false);
  } else {
    SetScanningEnabled(true);
    ConnectIfUnconnected();
  }
}

void ShellNetworkController::SetCellularAllowRoaming(bool allow_roaming) {
  chromeos::NetworkDeviceHandler* device_handler =
      chromeos::NetworkHandler::Get()->network_device_handler();
  device_handler->SetCellularAllowRoaming(allow_roaming);
}

const chromeos::NetworkState* ShellNetworkController::GetActiveWiFiNetwork() {
  chromeos::NetworkStateHandler* state_handler =
      chromeos::NetworkHandler::Get()->network_state_handler();
  const chromeos::NetworkState* network = state_handler->FirstNetworkByType(
      chromeos::NetworkTypePattern::Primitive(shill::kTypeWifi));
  return network &&
                 (network->IsConnectedState() || network->IsConnectingState())
             ? network
             : NULL;
}

void ShellNetworkController::SetScanningEnabled(bool enabled) {
  const bool currently_enabled = scan_timer_.IsRunning();
  if (enabled == currently_enabled)
    return;

  VLOG(1) << (enabled ? "Starting" : "Stopping") << " scanning";
  if (enabled) {
    RequestScan();
    scan_timer_.Start(FROM_HERE,
                      base::TimeDelta::FromSeconds(kScanIntervalSec),
                      this,
                      &ShellNetworkController::RequestScan);
  } else {
    scan_timer_.Stop();
  }
}

void ShellNetworkController::RequestScan() {
  VLOG(1) << "Requesting scan";
  chromeos::NetworkHandler::Get()->network_state_handler()->RequestScan();
}

void ShellNetworkController::ConnectIfUnconnected() {
  // Don't do anything if the default network is already the preferred one or if
  // we have a pending request to connect to it.
  if (preferred_network_is_active_ ||
      state_ == STATE_WAITING_FOR_PREFERRED_RESULT)
    return;

  const chromeos::NetworkState* best_network = NULL;
  bool can_connect_to_preferred_network = false;

  chromeos::NetworkHandler* handler = chromeos::NetworkHandler::Get();
  chromeos::NetworkStateHandler::NetworkStateList network_list;
  handler->network_state_handler()->GetVisibleNetworkListByType(
      chromeos::NetworkTypePattern::WiFi(), &network_list);
  for (chromeos::NetworkStateHandler::NetworkStateList::const_iterator it =
           network_list.begin();
       it != network_list.end();
       ++it) {
    const chromeos::NetworkState* network = *it;
    if (!network->connectable())
      continue;

    if (!preferred_network_name_.empty() &&
        network->name() == preferred_network_name_) {
      best_network = network;
      can_connect_to_preferred_network = true;
      break;
    } else if (!best_network) {
      best_network = network;
    }
  }

  // Don't switch networks if we're already connecting/connected and wouldn't be
  // switching to the preferred network.
  if ((IsConnectedOrConnecting() || state_ != STATE_IDLE) &&
      !can_connect_to_preferred_network)
    return;

  if (!best_network) {
    VLOG(1) << "Didn't find any connectable networks";
    return;
  }

  VLOG(1) << "Connecting to network " << GetNetworkName(*best_network)
          << " with path " << best_network->path() << " and strength "
          << best_network->signal_strength();
  state_ = can_connect_to_preferred_network
               ? STATE_WAITING_FOR_PREFERRED_RESULT
               : STATE_WAITING_FOR_NON_PREFERRED_RESULT;
  handler->network_connection_handler()->ConnectToNetwork(
      best_network->path(),
      base::Bind(&ShellNetworkController::HandleConnectionSuccess,
                 weak_ptr_factory_.GetWeakPtr()),
      base::Bind(&ShellNetworkController::HandleConnectionError,
                 weak_ptr_factory_.GetWeakPtr()),
      false /* check_error_state */);
}

void ShellNetworkController::HandleConnectionSuccess() {
  VLOG(1) << "Successfully connected to network";
  state_ = STATE_IDLE;
}

void ShellNetworkController::HandleConnectionError(
    const std::string& error_name,
    scoped_ptr<base::DictionaryValue> error_data) {
  LOG(WARNING) << "Unable to connect to network: " << error_name;
  state_ = STATE_IDLE;
}

}  // namespace extensions