summaryrefslogtreecommitdiffstats
path: root/chromecast/net/connectivity_checker_impl.cc
blob: 3ca50c1990ea139a47b4cb73142d103deb8b1c19 (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
// Copyright 2015 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 "chromecast/net/connectivity_checker_impl.h"

#include "base/command_line.h"
#include "base/logging.h"
#include "base/message_loop/message_loop.h"
#include "chromecast/net/net_switches.h"
#include "net/base/request_priority.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/http/http_status_code.h"
#include "net/proxy/proxy_config.h"
#include "net/proxy/proxy_config_service_fixed.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_builder.h"

namespace chromecast {

namespace {

// How often connectivity checks are performed in seconds.
const unsigned int kConnectivityPeriodSeconds = 1;

// Number of consecutive connectivity check errors before status is changed
// to offline.
const unsigned int kNumErrorsToNotifyOffline = 3;

// Default url for connectivity checking.
const char kDefaultConnectivityCheckUrl[] =
    "https://clients3.google.com/generate_204";

}  // namespace

ConnectivityCheckerImpl::ConnectivityCheckerImpl(
    const scoped_refptr<base::SingleThreadTaskRunner>& task_runner)
    : ConnectivityChecker(),
      task_runner_(task_runner),
      connected_(false),
      check_errors_(0) {
  DCHECK(task_runner_.get());
  task_runner->PostTask(FROM_HERE,
                        base::Bind(&ConnectivityCheckerImpl::Initialize, this));
}

void ConnectivityCheckerImpl::Initialize() {
  base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  base::CommandLine::StringType check_url_str =
      command_line->GetSwitchValueNative(switches::kConnectivityCheckUrl);
  connectivity_check_url_.reset(new GURL(
      check_url_str.empty() ? kDefaultConnectivityCheckUrl : check_url_str));

  net::URLRequestContextBuilder builder;
  builder.set_proxy_config_service(
      new net::ProxyConfigServiceFixed(net::ProxyConfig::CreateDirect()));
  builder.DisableHttpCache();
  url_request_context_.reset(builder.Build());

  net::NetworkChangeNotifier::AddConnectionTypeObserver(this);
  net::NetworkChangeNotifier::AddIPAddressObserver(this);
  task_runner_->PostTask(FROM_HERE,
                         base::Bind(&ConnectivityCheckerImpl::Check, this));
}

ConnectivityCheckerImpl::~ConnectivityCheckerImpl() {
  DCHECK(task_runner_.get());
  net::NetworkChangeNotifier::RemoveIPAddressObserver(this);
  net::NetworkChangeNotifier::RemoveConnectionTypeObserver(this);
  task_runner_->DeleteSoon(FROM_HERE, url_request_.release());
  task_runner_->DeleteSoon(FROM_HERE, url_request_context_.release());
}

bool ConnectivityCheckerImpl::Connected() const {
  return connected_;
}

void ConnectivityCheckerImpl::SetConnected(bool connected) {
  if (connected_ == connected)
    return;

  connected_ = connected;
  Notify(connected);
  LOG(INFO) << "Global connection is: " << (connected ? "Up" : "Down");
}

void ConnectivityCheckerImpl::Check() {
  if (!task_runner_->BelongsToCurrentThread()) {
    task_runner_->PostTask(FROM_HERE,
                           base::Bind(&ConnectivityCheckerImpl::Check, this));
    return;
  }
  DCHECK(url_request_context_.get());

  // Don't check connectivity if network is offline, because Internet could be
  // accessible via netifs ignored.
  if (net::NetworkChangeNotifier::IsOffline())
    return;

  // If url_request_ is non-null, there is already a check going on. Don't
  // start another.
  if (url_request_.get())
    return;

  VLOG(1) << "Connectivity check: url=" << *connectivity_check_url_;
  url_request_ = url_request_context_->CreateRequest(
      *connectivity_check_url_, net::MAXIMUM_PRIORITY, this);
  url_request_->set_method("HEAD");
  url_request_->Start();
}

void ConnectivityCheckerImpl::OnConnectionTypeChanged(
    net::NetworkChangeNotifier::ConnectionType type) {
  VLOG(2) << "OnConnectionTypeChanged " << type;
  if (type == net::NetworkChangeNotifier::CONNECTION_NONE)
    SetConnected(false);

  Cancel();
  Check();
}

void ConnectivityCheckerImpl::OnIPAddressChanged() {
  VLOG(2) << "OnIPAddressChanged";

  Cancel();
  Check();
}

void ConnectivityCheckerImpl::OnResponseStarted(net::URLRequest* request) {
  int http_response_code =
      (request->status().is_success() &&
       request->response_info().headers.get() != NULL)
          ? request->response_info().headers->response_code()
          : net::HTTP_BAD_REQUEST;

  // Clears resources.
  url_request_.reset(NULL);  // URLRequest::Cancel() is called in destructor.

  if (http_response_code < 400) {
    VLOG(1) << "Connectivity check succeeded";
    check_errors_ = 0;
    SetConnected(true);
    return;
  }
  VLOG(1) << "Connectivity check failed: " << http_response_code;
  OnUrlRequestError();
}

void ConnectivityCheckerImpl::OnSSLCertificateError(
    net::URLRequest* request,
    const net::SSLInfo& ssl_info,
    bool fatal) {
  LOG(ERROR) << "OnSSLCertificateError";
  OnUrlRequestError();
}

void ConnectivityCheckerImpl::OnUrlRequestError() {
  ++check_errors_;
  if (check_errors_ > kNumErrorsToNotifyOffline) {
    check_errors_ = kNumErrorsToNotifyOffline;
    SetConnected(false);
  }
  url_request_.reset(NULL);
  // Check again.
  task_runner_->PostDelayedTask(
      FROM_HERE, base::Bind(&ConnectivityCheckerImpl::Check, this),
      base::TimeDelta::FromSeconds(kConnectivityPeriodSeconds));
}

void ConnectivityCheckerImpl::OnReadCompleted(net::URLRequest* request,
                                              int bytes_read) {
  NOTREACHED();
}

void ConnectivityCheckerImpl::Cancel() {
  if (url_request_.get()) {
    VLOG(2) << "Cancel connectivity check in progress";
    url_request_.reset(NULL);  // URLRequest::Cancel() is called in destructor.
  }
}

}  // namespace chromecast