Avoid crashing when going back/forward to debug URLs on a sad WebUI tab.
[chromium-blink-merge.git] / chrome / service / cloud_print / cloud_print_proxy_backend.cc
blob53485ccdf161867002cc3f77e1a61cfc14598925
1 // Copyright (c) 2012 The Chromium 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.
5 #include "chrome/service/cloud_print/cloud_print_proxy_backend.h"
7 #include <map>
8 #include <vector>
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/compiler_specific.h"
13 #include "base/location.h"
14 #include "base/metrics/histogram.h"
15 #include "base/rand_util.h"
16 #include "base/single_thread_task_runner.h"
17 #include "base/strings/string_util.h"
18 #include "base/thread_task_runner_handle.h"
19 #include "base/values.h"
20 #include "chrome/common/cloud_print/cloud_print_constants.h"
21 #include "chrome/service/cloud_print/cloud_print_auth.h"
22 #include "chrome/service/cloud_print/cloud_print_connector.h"
23 #include "chrome/service/cloud_print/cloud_print_service_helpers.h"
24 #include "chrome/service/cloud_print/cloud_print_token_store.h"
25 #include "chrome/service/cloud_print/connector_settings.h"
26 #include "chrome/service/net/service_url_request_context_getter.h"
27 #include "chrome/service/service_process.h"
28 #include "components/cloud_devices/common/cloud_devices_switches.h"
29 #include "google_apis/gaia/gaia_oauth_client.h"
30 #include "google_apis/gaia/gaia_urls.h"
31 #include "jingle/notifier/base/notifier_options.h"
32 #include "jingle/notifier/listener/push_client.h"
33 #include "jingle/notifier/listener/push_client_observer.h"
34 #include "url/gurl.h"
36 namespace cloud_print {
38 // The real guts of CloudPrintProxyBackend, to keep the public client API clean.
39 class CloudPrintProxyBackend::Core
40 : public base::RefCountedThreadSafe<CloudPrintProxyBackend::Core>,
41 public CloudPrintAuth::Client,
42 public CloudPrintConnector::Client,
43 public notifier::PushClientObserver {
44 public:
45 // It is OK for print_server_url to be empty. In this case system should
46 // use system default (local) print server.
47 Core(CloudPrintProxyBackend* backend,
48 const ConnectorSettings& settings,
49 const gaia::OAuthClientInfo& oauth_client_info,
50 bool enable_job_poll);
52 // Note:
54 // The Do* methods are the various entry points from CloudPrintProxyBackend
55 // It calls us on a dedicated thread to actually perform synchronous
56 // (and potentially blocking) operations.
57 void DoInitializeWithToken(const std::string& cloud_print_token);
58 void DoInitializeWithRobotToken(const std::string& robot_oauth_refresh_token,
59 const std::string& robot_email);
60 void DoInitializeWithRobotAuthCode(const std::string& robot_oauth_auth_code,
61 const std::string& robot_email);
63 // Called on the CloudPrintProxyBackend core_thread_ to perform
64 // shutdown.
65 void DoShutdown();
66 void DoRegisterSelectedPrinters(
67 const printing::PrinterList& printer_list);
68 void DoUnregisterPrinters();
70 // CloudPrintAuth::Client implementation.
71 void OnAuthenticationComplete(const std::string& access_token,
72 const std::string& robot_oauth_refresh_token,
73 const std::string& robot_email,
74 const std::string& user_email) override;
75 void OnInvalidCredentials() override;
77 // CloudPrintConnector::Client implementation.
78 void OnAuthFailed() override;
79 void OnXmppPingUpdated(int ping_timeout) override;
81 // notifier::PushClientObserver implementation.
82 void OnNotificationsEnabled() override;
83 void OnNotificationsDisabled(
84 notifier::NotificationsDisabledReason reason) override;
85 void OnIncomingNotification(
86 const notifier::Notification& notification) override;
87 void OnPingResponse() override;
89 private:
90 friend class base::RefCountedThreadSafe<Core>;
92 ~Core() override {}
94 void CreateAuthAndConnector();
95 void DestroyAuthAndConnector();
97 // NotifyXXX is how the Core communicates with the frontend across
98 // threads.
99 void NotifyPrinterListAvailable(
100 const printing::PrinterList& printer_list);
101 void NotifyAuthenticated(
102 const std::string& robot_oauth_refresh_token,
103 const std::string& robot_email,
104 const std::string& user_email);
105 void NotifyAuthenticationFailed();
106 void NotifyPrintSystemUnavailable();
107 void NotifyUnregisterPrinters(const std::string& auth_token,
108 const std::list<std::string>& printer_ids);
109 void NotifyXmppPingUpdated(int ping_timeout);
111 // Init XMPP channel
112 void InitNotifications(const std::string& robot_email,
113 const std::string& access_token);
115 void HandlePrinterNotification(const std::string& notification);
116 void PollForJobs();
117 // Schedules a task to poll for jobs. Does nothing if a task is already
118 // scheduled.
119 void ScheduleJobPoll();
120 void PingXmppServer();
121 void ScheduleXmppPing();
122 void CheckXmppPingStatus();
124 CloudPrintTokenStore* GetTokenStore();
126 // Our parent CloudPrintProxyBackend
127 CloudPrintProxyBackend* backend_;
129 // Cloud Print authenticator.
130 scoped_refptr<CloudPrintAuth> auth_;
132 // Cloud Print connector.
133 scoped_refptr<CloudPrintConnector> connector_;
135 // OAuth client info.
136 gaia::OAuthClientInfo oauth_client_info_;
137 // Notification (xmpp) handler.
138 scoped_ptr<notifier::PushClient> push_client_;
139 // Indicates whether XMPP notifications are currently enabled.
140 bool notifications_enabled_;
141 // The time when notifications were enabled. Valid only when
142 // notifications_enabled_ is true.
143 base::TimeTicks notifications_enabled_since_;
144 // Indicates whether a task to poll for jobs has been scheduled.
145 bool job_poll_scheduled_;
146 // Indicates whether we should poll for jobs when we lose XMPP connection.
147 bool enable_job_poll_;
148 // Indicates whether a task to ping xmpp server has been scheduled.
149 bool xmpp_ping_scheduled_;
150 // Number of XMPP pings pending reply from the server.
151 int pending_xmpp_pings_;
152 // Connector settings.
153 ConnectorSettings settings_;
154 std::string robot_email_;
155 scoped_ptr<CloudPrintTokenStore> token_store_;
157 DISALLOW_COPY_AND_ASSIGN(Core);
160 CloudPrintProxyBackend::CloudPrintProxyBackend(
161 CloudPrintProxyFrontend* frontend,
162 const ConnectorSettings& settings,
163 const gaia::OAuthClientInfo& oauth_client_info,
164 bool enable_job_poll)
165 : core_thread_("Chrome_CloudPrintProxyCoreThread"),
166 frontend_loop_(base::MessageLoop::current()),
167 frontend_(frontend) {
168 DCHECK(frontend_);
169 core_ = new Core(this, settings, oauth_client_info, enable_job_poll);
172 CloudPrintProxyBackend::~CloudPrintProxyBackend() { DCHECK(!core_.get()); }
174 bool CloudPrintProxyBackend::InitializeWithToken(
175 const std::string& cloud_print_token) {
176 if (!core_thread_.Start())
177 return false;
178 core_thread_.task_runner()->PostTask(
179 FROM_HERE,
180 base::Bind(&CloudPrintProxyBackend::Core::DoInitializeWithToken,
181 core_.get(), cloud_print_token));
182 return true;
185 bool CloudPrintProxyBackend::InitializeWithRobotToken(
186 const std::string& robot_oauth_refresh_token,
187 const std::string& robot_email) {
188 if (!core_thread_.Start())
189 return false;
190 core_thread_.task_runner()->PostTask(
191 FROM_HERE,
192 base::Bind(&CloudPrintProxyBackend::Core::DoInitializeWithRobotToken,
193 core_.get(), robot_oauth_refresh_token, robot_email));
194 return true;
197 bool CloudPrintProxyBackend::InitializeWithRobotAuthCode(
198 const std::string& robot_oauth_auth_code,
199 const std::string& robot_email) {
200 if (!core_thread_.Start())
201 return false;
202 core_thread_.task_runner()->PostTask(
203 FROM_HERE,
204 base::Bind(&CloudPrintProxyBackend::Core::DoInitializeWithRobotAuthCode,
205 core_.get(), robot_oauth_auth_code, robot_email));
206 return true;
209 void CloudPrintProxyBackend::Shutdown() {
210 core_thread_.task_runner()->PostTask(
211 FROM_HERE,
212 base::Bind(&CloudPrintProxyBackend::Core::DoShutdown, core_.get()));
213 core_thread_.Stop();
214 core_ = NULL; // Releases reference to core_.
217 void CloudPrintProxyBackend::UnregisterPrinters() {
218 core_thread_.task_runner()->PostTask(
219 FROM_HERE, base::Bind(&CloudPrintProxyBackend::Core::DoUnregisterPrinters,
220 core_.get()));
223 CloudPrintProxyBackend::Core::Core(
224 CloudPrintProxyBackend* backend,
225 const ConnectorSettings& settings,
226 const gaia::OAuthClientInfo& oauth_client_info,
227 bool enable_job_poll)
228 : backend_(backend),
229 oauth_client_info_(oauth_client_info),
230 notifications_enabled_(false),
231 job_poll_scheduled_(false),
232 enable_job_poll_(enable_job_poll),
233 xmpp_ping_scheduled_(false),
234 pending_xmpp_pings_(0) {
235 settings_.CopyFrom(settings);
238 void CloudPrintProxyBackend::Core::CreateAuthAndConnector() {
239 if (!auth_.get()) {
240 auth_ = new CloudPrintAuth(this, settings_.server_url(), oauth_client_info_,
241 settings_.proxy_id());
244 if (!connector_.get()) {
245 connector_ = new CloudPrintConnector(this, settings_);
249 void CloudPrintProxyBackend::Core::DestroyAuthAndConnector() {
250 auth_ = NULL;
251 connector_ = NULL;
254 void CloudPrintProxyBackend::Core::DoInitializeWithToken(
255 const std::string& cloud_print_token) {
256 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
257 CreateAuthAndConnector();
258 auth_->AuthenticateWithToken(cloud_print_token);
261 void CloudPrintProxyBackend::Core::DoInitializeWithRobotToken(
262 const std::string& robot_oauth_refresh_token,
263 const std::string& robot_email) {
264 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
265 CreateAuthAndConnector();
266 auth_->AuthenticateWithRobotToken(robot_oauth_refresh_token, robot_email);
269 void CloudPrintProxyBackend::Core::DoInitializeWithRobotAuthCode(
270 const std::string& robot_oauth_auth_code,
271 const std::string& robot_email) {
272 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
273 CreateAuthAndConnector();
274 auth_->AuthenticateWithRobotAuthCode(robot_oauth_auth_code, robot_email);
277 void CloudPrintProxyBackend::Core::OnAuthenticationComplete(
278 const std::string& access_token,
279 const std::string& robot_oauth_refresh_token,
280 const std::string& robot_email,
281 const std::string& user_email) {
282 CloudPrintTokenStore* token_store = GetTokenStore();
283 bool first_time = token_store->token().empty();
284 token_store->SetToken(access_token);
285 robot_email_ = robot_email;
286 // Let the frontend know that we have authenticated.
287 backend_->frontend_loop_->task_runner()->PostTask(
288 FROM_HERE,
289 base::Bind(&Core::NotifyAuthenticated, this, robot_oauth_refresh_token,
290 robot_email, user_email));
291 if (first_time) {
292 InitNotifications(robot_email, access_token);
293 } else {
294 // If we are refreshing a token, update the XMPP token too.
295 DCHECK(push_client_.get());
296 push_client_->UpdateCredentials(robot_email, access_token);
298 // Start cloud print connector if needed.
299 if (!connector_->IsRunning()) {
300 if (!connector_->Start()) {
301 // Let the frontend know that we do not have a print system.
302 backend_->frontend_loop_->task_runner()->PostTask(
303 FROM_HERE, base::Bind(&Core::NotifyPrintSystemUnavailable, this));
308 void CloudPrintProxyBackend::Core::OnInvalidCredentials() {
309 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
310 VLOG(1) << "CP_CONNECTOR: Auth Error";
311 backend_->frontend_loop_->task_runner()->PostTask(
312 FROM_HERE, base::Bind(&Core::NotifyAuthenticationFailed, this));
315 void CloudPrintProxyBackend::Core::OnAuthFailed() {
316 VLOG(1) << "CP_CONNECTOR: Authentication failed in connector.";
317 // Let's stop connecter and refresh token. We'll restart connecter once
318 // new token available.
319 if (connector_->IsRunning())
320 connector_->Stop();
322 // Refresh Auth token.
323 auth_->RefreshAccessToken();
326 void CloudPrintProxyBackend::Core::OnXmppPingUpdated(int ping_timeout) {
327 settings_.SetXmppPingTimeoutSec(ping_timeout);
328 backend_->frontend_loop_->task_runner()->PostTask(
329 FROM_HERE, base::Bind(&Core::NotifyXmppPingUpdated, this, ping_timeout));
332 void CloudPrintProxyBackend::Core::InitNotifications(
333 const std::string& robot_email,
334 const std::string& access_token) {
335 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
337 pending_xmpp_pings_ = 0;
338 notifier::NotifierOptions notifier_options;
339 notifier_options.request_context_getter =
340 g_service_process->GetServiceURLRequestContextGetter();
341 notifier_options.auth_mechanism = "X-OAUTH2";
342 notifier_options.try_ssltcp_first = true;
343 notifier_options.xmpp_host_port = net::HostPortPair::FromString(
344 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
345 switches::kCloudPrintXmppEndpoint));
346 push_client_ = notifier::PushClient::CreateDefault(notifier_options);
347 push_client_->AddObserver(this);
348 notifier::Subscription subscription;
349 subscription.channel = kCloudPrintPushNotificationsSource;
350 subscription.from = kCloudPrintPushNotificationsSource;
351 push_client_->UpdateSubscriptions(
352 notifier::SubscriptionList(1, subscription));
353 push_client_->UpdateCredentials(robot_email, access_token);
356 void CloudPrintProxyBackend::Core::DoShutdown() {
357 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
358 VLOG(1) << "CP_CONNECTOR: Shutdown connector, id: " << settings_.proxy_id();
360 if (connector_->IsRunning())
361 connector_->Stop();
363 // Important to delete the PushClient on this thread.
364 if (push_client_.get()) {
365 push_client_->RemoveObserver(this);
367 push_client_.reset();
368 notifications_enabled_ = false;
369 notifications_enabled_since_ = base::TimeTicks();
370 token_store_.reset();
372 DestroyAuthAndConnector();
375 void CloudPrintProxyBackend::Core::DoUnregisterPrinters() {
376 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
378 std::string access_token = GetTokenStore()->token();
380 std::list<std::string> printer_ids;
381 connector_->GetPrinterIds(&printer_ids);
383 backend_->frontend_loop_->task_runner()->PostTask(
384 FROM_HERE, base::Bind(&Core::NotifyUnregisterPrinters, this, access_token,
385 printer_ids));
388 void CloudPrintProxyBackend::Core::HandlePrinterNotification(
389 const std::string& notification) {
390 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
392 size_t pos = notification.rfind(kNotificationUpdateSettings);
393 if (pos == std::string::npos) {
394 VLOG(1) << "CP_CONNECTOR: Handle printer notification, id: "
395 << notification;
396 connector_->CheckForJobs(kJobFetchReasonNotified, notification);
397 } else {
398 DCHECK(pos == notification.length() - strlen(kNotificationUpdateSettings));
399 std::string printer_id = notification.substr(0, pos);
400 VLOG(1) << "CP_CONNECTOR: Update printer settings, id: " << printer_id;
401 connector_->UpdatePrinterSettings(printer_id);
405 void CloudPrintProxyBackend::Core::PollForJobs() {
406 VLOG(1) << "CP_CONNECTOR: Polling for jobs.";
407 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
408 // Check all printers for jobs.
409 connector_->CheckForJobs(kJobFetchReasonPoll, std::string());
411 job_poll_scheduled_ = false;
412 // If we don't have notifications and job polling is enabled, poll again
413 // after a while.
414 if (!notifications_enabled_ && enable_job_poll_)
415 ScheduleJobPoll();
418 void CloudPrintProxyBackend::Core::ScheduleJobPoll() {
419 if (!job_poll_scheduled_) {
420 base::TimeDelta interval = base::TimeDelta::FromSeconds(
421 base::RandInt(kMinJobPollIntervalSecs, kMaxJobPollIntervalSecs));
422 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
423 FROM_HERE, base::Bind(&CloudPrintProxyBackend::Core::PollForJobs, this),
424 interval);
425 job_poll_scheduled_ = true;
429 void CloudPrintProxyBackend::Core::PingXmppServer() {
430 xmpp_ping_scheduled_ = false;
432 if (!push_client_.get())
433 return;
435 push_client_->SendPing();
437 pending_xmpp_pings_++;
438 if (pending_xmpp_pings_ >= kMaxFailedXmppPings) {
439 // Check ping status when we close to the limit.
440 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
441 FROM_HERE,
442 base::Bind(&CloudPrintProxyBackend::Core::CheckXmppPingStatus, this),
443 base::TimeDelta::FromSeconds(kXmppPingCheckIntervalSecs));
446 // Schedule next ping if needed.
447 if (notifications_enabled_)
448 ScheduleXmppPing();
451 void CloudPrintProxyBackend::Core::ScheduleXmppPing() {
452 // settings_.xmpp_ping_enabled() is obsolete, we are now control
453 // XMPP pings from Cloud Print server.
454 if (!xmpp_ping_scheduled_) {
455 base::TimeDelta interval = base::TimeDelta::FromSeconds(
456 base::RandInt(settings_.xmpp_ping_timeout_sec() * 0.9,
457 settings_.xmpp_ping_timeout_sec() * 1.1));
458 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
459 FROM_HERE,
460 base::Bind(&CloudPrintProxyBackend::Core::PingXmppServer, this),
461 interval);
462 xmpp_ping_scheduled_ = true;
466 void CloudPrintProxyBackend::Core::CheckXmppPingStatus() {
467 if (pending_xmpp_pings_ >= kMaxFailedXmppPings) {
468 UMA_HISTOGRAM_COUNTS_100("CloudPrint.XmppPingTry", 99); // Max on fail.
469 // Reconnect to XMPP.
470 pending_xmpp_pings_ = 0;
471 push_client_.reset();
472 InitNotifications(robot_email_, GetTokenStore()->token());
476 CloudPrintTokenStore* CloudPrintProxyBackend::Core::GetTokenStore() {
477 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
478 if (!token_store_.get())
479 token_store_.reset(new CloudPrintTokenStore);
480 return token_store_.get();
483 void CloudPrintProxyBackend::Core::NotifyAuthenticated(
484 const std::string& robot_oauth_refresh_token,
485 const std::string& robot_email,
486 const std::string& user_email) {
487 DCHECK(base::MessageLoop::current() == backend_->frontend_loop_);
488 backend_->frontend_
489 ->OnAuthenticated(robot_oauth_refresh_token, robot_email, user_email);
492 void CloudPrintProxyBackend::Core::NotifyAuthenticationFailed() {
493 DCHECK(base::MessageLoop::current() == backend_->frontend_loop_);
494 backend_->frontend_->OnAuthenticationFailed();
497 void CloudPrintProxyBackend::Core::NotifyPrintSystemUnavailable() {
498 DCHECK(base::MessageLoop::current() == backend_->frontend_loop_);
499 backend_->frontend_->OnPrintSystemUnavailable();
502 void CloudPrintProxyBackend::Core::NotifyUnregisterPrinters(
503 const std::string& auth_token,
504 const std::list<std::string>& printer_ids) {
505 DCHECK(base::MessageLoop::current() == backend_->frontend_loop_);
506 backend_->frontend_->OnUnregisterPrinters(auth_token, printer_ids);
509 void CloudPrintProxyBackend::Core::NotifyXmppPingUpdated(int ping_timeout) {
510 DCHECK(base::MessageLoop::current() == backend_->frontend_loop_);
511 backend_->frontend_->OnXmppPingUpdated(ping_timeout);
514 void CloudPrintProxyBackend::Core::OnNotificationsEnabled() {
515 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
516 notifications_enabled_ = true;
517 notifications_enabled_since_ = base::TimeTicks::Now();
518 VLOG(1) << "Notifications for connector " << settings_.proxy_id()
519 << " were enabled at "
520 << notifications_enabled_since_.ToInternalValue();
521 // Notifications just got re-enabled. In this case we want to schedule
522 // a poll once for jobs we might have missed when we were dark.
523 // Note that ScheduleJobPoll will not schedule again if a job poll task is
524 // already scheduled.
525 ScheduleJobPoll();
527 // Schedule periodic ping for XMPP notification channel.
528 ScheduleXmppPing();
531 void CloudPrintProxyBackend::Core::OnNotificationsDisabled(
532 notifier::NotificationsDisabledReason reason) {
533 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
534 notifications_enabled_ = false;
535 LOG(ERROR) << "Notifications for connector " << settings_.proxy_id()
536 << " disabled.";
537 notifications_enabled_since_ = base::TimeTicks();
538 // We just lost notifications. This this case we want to schedule a
539 // job poll if enable_job_poll_ is true.
540 if (enable_job_poll_)
541 ScheduleJobPoll();
545 void CloudPrintProxyBackend::Core::OnIncomingNotification(
546 const notifier::Notification& notification) {
547 // Since we got some notification from the server,
548 // reset pending ping counter to 0.
549 pending_xmpp_pings_ = 0;
551 DCHECK(base::MessageLoop::current() == backend_->core_thread_.message_loop());
552 VLOG(1) << "CP_CONNECTOR: Incoming notification.";
553 if (base::EqualsCaseInsensitiveASCII(kCloudPrintPushNotificationsSource,
554 notification.channel))
555 HandlePrinterNotification(notification.data);
558 void CloudPrintProxyBackend::Core::OnPingResponse() {
559 UMA_HISTOGRAM_COUNTS_100("CloudPrint.XmppPingTry", pending_xmpp_pings_);
560 pending_xmpp_pings_ = 0;
561 VLOG(1) << "CP_CONNECTOR: Ping response received.";
564 } // namespace cloud_print