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 "cloud_print/service/service_state.h"
7 #include "base/json/json_reader.h"
8 #include "base/json/json_writer.h"
9 #include "base/logging.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "net/base/elements_upload_data_stream.h"
14 #include "net/base/escape.h"
15 #include "net/base/io_buffer.h"
16 #include "net/base/load_flags.h"
17 #include "net/base/request_priority.h"
18 #include "net/base/upload_bytes_element_reader.h"
19 #include "net/url_request/url_request.h"
20 #include "net/url_request/url_request_context.h"
21 #include "net/url_request/url_request_context_builder.h"
25 const char kCloudPrintJsonName
[] = "cloud_print";
26 const char kEnabledOptionName
[] = "enabled";
28 const char kEmailOptionName
[] = "email";
29 const char kProxyIdOptionName
[] = "proxy_id";
30 const char kRobotEmailOptionName
[] = "robot_email";
31 const char kRobotTokenOptionName
[] = "robot_refresh_token";
32 const char kAuthTokenOptionName
[] = "auth_token";
33 const char kXmppAuthTokenOptionName
[] = "xmpp_auth_token";
35 const char kClientLoginUrl
[] = "https://www.google.com/accounts/ClientLogin";
37 const int64 kRequestTimeoutMs
= 10 * 1000;
39 class ServiceStateURLRequestDelegate
: public net::URLRequest::Delegate
{
41 void OnResponseStarted(net::URLRequest
* request
) override
{
42 if (request
->GetResponseCode() == 200) {
44 if (request
->status().is_io_pending())
50 void OnReadCompleted(net::URLRequest
* request
, int bytes_read
) override
{
52 if (!request
->status().is_io_pending())
53 base::MessageLoop::current()->Quit();
56 const std::string
& data() const {
61 void Read(net::URLRequest
* request
) {
62 // Read as many bytes as are available synchronously.
63 const int kBufSize
= 100000;
64 scoped_refptr
<net::IOBuffer
> buf(new net::IOBuffer(kBufSize
));
66 while (request
->Read(buf
.get(), kBufSize
, &num_bytes
)) {
67 data_
.append(buf
->data(), buf
->data() + num_bytes
);
74 void SetNotEmptyJsonString(base::DictionaryValue
* dictionary
,
75 const std::string
& name
,
76 const std::string
& value
) {
78 dictionary
->SetString(name
, value
);
83 ServiceState::ServiceState() {
87 ServiceState::~ServiceState() {
90 void ServiceState::Reset() {
96 xmpp_auth_token_
.clear();
99 bool ServiceState::FromString(const std::string
& json
) {
101 scoped_ptr
<base::Value
> data(base::JSONReader::Read(json
));
105 const base::DictionaryValue
* services
= NULL
;
106 if (!data
->GetAsDictionary(&services
))
109 const base::DictionaryValue
* cloud_print
= NULL
;
110 if (!services
->GetDictionary(kCloudPrintJsonName
, &cloud_print
))
113 bool valid_file
= true;
114 // Don't exit on fail. Collect all data for re-use by user later.
115 if (!cloud_print
->GetBoolean(kEnabledOptionName
, &valid_file
))
118 cloud_print
->GetString(kEmailOptionName
, &email_
);
119 cloud_print
->GetString(kProxyIdOptionName
, &proxy_id_
);
120 cloud_print
->GetString(kRobotEmailOptionName
, &robot_email_
);
121 cloud_print
->GetString(kRobotTokenOptionName
, &robot_token_
);
122 cloud_print
->GetString(kAuthTokenOptionName
, &auth_token_
);
123 cloud_print
->GetString(kXmppAuthTokenOptionName
, &xmpp_auth_token_
);
125 return valid_file
&& IsValid();
128 bool ServiceState::IsValid() const {
129 if (email_
.empty() || proxy_id_
.empty())
131 bool valid_robot
= !robot_email_
.empty() && !robot_token_
.empty();
132 bool valid_auth
= !auth_token_
.empty() && !xmpp_auth_token_
.empty();
133 return valid_robot
|| valid_auth
;
136 std::string
ServiceState::ToString() {
137 scoped_ptr
<base::DictionaryValue
> cloud_print(new base::DictionaryValue());
138 cloud_print
->SetBoolean(kEnabledOptionName
, true);
140 SetNotEmptyJsonString(cloud_print
.get(), kEmailOptionName
, email_
);
141 SetNotEmptyJsonString(cloud_print
.get(), kProxyIdOptionName
, proxy_id_
);
142 SetNotEmptyJsonString(cloud_print
.get(), kRobotEmailOptionName
, robot_email_
);
143 SetNotEmptyJsonString(cloud_print
.get(), kRobotTokenOptionName
, robot_token_
);
144 SetNotEmptyJsonString(cloud_print
.get(), kAuthTokenOptionName
, auth_token_
);
145 SetNotEmptyJsonString(cloud_print
.get(), kXmppAuthTokenOptionName
,
148 base::DictionaryValue services
;
149 services
.Set(kCloudPrintJsonName
, cloud_print
.Pass());
152 base::JSONWriter::WriteWithOptions(
153 services
, base::JSONWriter::OPTIONS_PRETTY_PRINT
, &json
);
157 std::string
ServiceState::LoginToGoogle(const std::string
& service
,
158 const std::string
& email
,
159 const std::string
& password
) {
160 base::MessageLoopForIO loop
;
162 net::URLRequestContextBuilder builder
;
163 scoped_ptr
<net::URLRequestContext
> context(builder
.Build());
165 ServiceStateURLRequestDelegate fetcher_delegate
;
166 GURL
url(kClientLoginUrl
);
168 std::string post_body
;
169 post_body
+= "accountType=GOOGLE";
170 post_body
+= "&Email=" + net::EscapeUrlEncodedData(email
, true);
171 post_body
+= "&Passwd=" + net::EscapeUrlEncodedData(password
, true);
172 post_body
+= "&source=" + net::EscapeUrlEncodedData("CP-Service", true);
173 post_body
+= "&service=" + net::EscapeUrlEncodedData(service
, true);
175 scoped_ptr
<net::URLRequest
> request(context
->CreateRequest(
176 url
, net::DEFAULT_PRIORITY
, &fetcher_delegate
));
177 int load_flags
= request
->load_flags();
178 load_flags
= load_flags
| net::LOAD_DO_NOT_SEND_COOKIES
;
179 load_flags
= load_flags
| net::LOAD_DO_NOT_SAVE_COOKIES
;
180 request
->SetLoadFlags(load_flags
);
182 scoped_ptr
<net::UploadElementReader
> reader(
183 net::UploadOwnedBytesElementReader::CreateWithString(post_body
));
185 net::ElementsUploadDataStream::CreateWithReader(reader
.Pass(), 0));
186 request
->SetExtraRequestHeaderByName(
187 "Content-Type", "application/x-www-form-urlencoded", true);
188 request
->set_method("POST");
191 base::MessageLoop::current()->PostDelayedTask(
193 base::MessageLoop::QuitClosure(),
194 base::TimeDelta::FromMilliseconds(kRequestTimeoutMs
));
196 base::MessageLoop::current()->Run();
198 const char kAuthStart
[] = "Auth=";
199 std::vector
<std::string
> lines
;
200 Tokenize(fetcher_delegate
.data(), "\r\n", &lines
);
201 for (size_t i
= 0; i
< lines
.size(); ++i
) {
202 if (StartsWithASCII(lines
[i
], kAuthStart
, false))
203 return lines
[i
].substr(arraysize(kAuthStart
) - 1);
206 return std::string();
209 bool ServiceState::Configure(const std::string
& email
,
210 const std::string
& password
,
211 const std::string
& proxy_id
) {
212 robot_token_
.clear();
213 robot_email_
.clear();
215 proxy_id_
= proxy_id
;
216 auth_token_
= LoginToGoogle("cloudprint", email_
, password
);
217 xmpp_auth_token_
= LoginToGoogle("chromiumsync", email_
, password
);