1 // Copyright 2013 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 // A standalone tool for testing MCS connections and the MCS client on their
13 #include "base/at_exit.h"
14 #include "base/command_line.h"
15 #include "base/compiler_specific.h"
16 #include "base/logging.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/message_loop/message_loop.h"
20 #include "base/run_loop.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/threading/thread.h"
23 #include "base/threading/worker_pool.h"
24 #include "base/time/default_clock.h"
25 #include "base/values.h"
26 #include "google_apis/gcm/base/fake_encryptor.h"
27 #include "google_apis/gcm/base/mcs_message.h"
28 #include "google_apis/gcm/base/mcs_util.h"
29 #include "google_apis/gcm/engine/checkin_request.h"
30 #include "google_apis/gcm/engine/connection_factory_impl.h"
31 #include "google_apis/gcm/engine/gcm_store_impl.h"
32 #include "google_apis/gcm/engine/gservices_settings.h"
33 #include "google_apis/gcm/engine/mcs_client.h"
34 #include "google_apis/gcm/monitoring/fake_gcm_stats_recorder.h"
35 #include "net/base/host_mapping_rules.h"
36 #include "net/base/net_log_logger.h"
37 #include "net/cert/cert_verifier.h"
38 #include "net/dns/host_resolver.h"
39 #include "net/http/http_auth_handler_factory.h"
40 #include "net/http/http_network_session.h"
41 #include "net/http/http_server_properties_impl.h"
42 #include "net/http/transport_security_state.h"
43 #include "net/socket/client_socket_factory.h"
44 #include "net/socket/ssl_client_socket.h"
45 #include "net/ssl/channel_id_service.h"
46 #include "net/ssl/default_channel_id_store.h"
47 #include "net/url_request/url_request_test_util.h"
49 #if defined(OS_MACOSX)
50 #include "base/mac/scoped_nsautorelease_pool.h"
53 // This is a simple utility that initializes an mcs client and
54 // prints out any events.
58 const net::BackoffEntry::Policy kDefaultBackoffPolicy
= {
59 // Number of initial errors (in sequence) to ignore before applying
60 // exponential back-off rules.
63 // Initial delay for exponential back-off in ms.
66 // Factor by which the waiting time will be multiplied.
69 // Fuzzing percentage. ex: 10% will spread requests randomly
70 // between 90%-100% of the calculated time.
73 // Maximum amount of time we are willing to delay our request in ms.
74 1000 * 60 * 5, // 5 minutes.
76 // Time to keep an entry from being discarded even when it
77 // has no significant state, -1 to never discard.
80 // Don't use initial delay unless the last request was an error.
84 // Default values used to communicate with the check-in server.
85 const char kChromeVersion
[] = "Chrome MCS Probe";
87 // The default server to communicate with.
88 const char kMCSServerHost
[] = "mtalk.google.com";
89 const uint16 kMCSServerPort
= 5228;
91 // Command line switches.
92 const char kRMQFileName
[] = "rmq_file";
93 const char kAndroidIdSwitch
[] = "android_id";
94 const char kSecretSwitch
[] = "secret";
95 const char kLogFileSwitch
[] = "log-file";
96 const char kIgnoreCertSwitch
[] = "ignore-certs";
97 const char kServerHostSwitch
[] = "host";
98 const char kServerPortSwitch
[] = "port";
100 void MessageReceivedCallback(const MCSMessage
& message
) {
101 LOG(INFO
) << "Received message with id "
102 << GetPersistentId(message
.GetProtobuf()) << " and tag "
103 << static_cast<int>(message
.tag());
105 if (message
.tag() == kDataMessageStanzaTag
) {
106 const mcs_proto::DataMessageStanza
& data_message
=
107 reinterpret_cast<const mcs_proto::DataMessageStanza
&>(
108 message
.GetProtobuf());
109 DVLOG(1) << " to: " << data_message
.to();
110 DVLOG(1) << " from: " << data_message
.from();
111 DVLOG(1) << " category: " << data_message
.category();
112 DVLOG(1) << " sent: " << data_message
.sent();
113 for (int i
= 0; i
< data_message
.app_data_size(); ++i
) {
114 DVLOG(1) << " App data " << i
<< " "
115 << data_message
.app_data(i
).key() << " : "
116 << data_message
.app_data(i
).value();
121 void MessageSentCallback(int64 user_serial_number
,
122 const std::string
& app_id
,
123 const std::string
& message_id
,
124 MCSClient::MessageSendStatus status
) {
125 LOG(INFO
) << "Message sent. Serial number: " << user_serial_number
126 << " Application ID: " << app_id
127 << " Message ID: " << message_id
128 << " Message send status: " << status
;
131 // Needed to use a real host resolver.
132 class MyTestURLRequestContext
: public net::TestURLRequestContext
{
134 MyTestURLRequestContext() : TestURLRequestContext(true) {
135 context_storage_
.set_host_resolver(
136 net::HostResolver::CreateDefaultResolver(NULL
));
137 context_storage_
.set_transport_security_state(
138 new net::TransportSecurityState());
142 ~MyTestURLRequestContext() override
{}
145 class MyTestURLRequestContextGetter
: public net::TestURLRequestContextGetter
{
147 explicit MyTestURLRequestContextGetter(
148 const scoped_refptr
<base::MessageLoopProxy
>& io_message_loop_proxy
)
149 : TestURLRequestContextGetter(io_message_loop_proxy
) {}
151 net::TestURLRequestContext
* GetURLRequestContext() override
{
152 // Construct |context_| lazily so it gets constructed on the right
153 // thread (the IO thread).
155 context_
.reset(new MyTestURLRequestContext());
156 return context_
.get();
160 ~MyTestURLRequestContextGetter() override
{}
162 scoped_ptr
<MyTestURLRequestContext
> context_
;
165 // A cert verifier that access all certificates.
166 class MyTestCertVerifier
: public net::CertVerifier
{
168 MyTestCertVerifier() {}
169 ~MyTestCertVerifier() override
{}
171 int Verify(net::X509Certificate
* cert
,
172 const std::string
& hostname
,
174 net::CRLSet
* crl_set
,
175 net::CertVerifyResult
* verify_result
,
176 const net::CompletionCallback
& callback
,
177 RequestHandle
* out_req
,
178 const net::BoundNetLog
& net_log
) override
{
182 void CancelRequest(RequestHandle req
) override
{
190 const base::CommandLine
& command_line
,
191 scoped_refptr
<net::URLRequestContextGetter
> url_request_context_getter
);
196 uint64
android_id() const { return android_id_
; }
197 uint64
secret() const { return secret_
; }
201 void InitializeNetworkState();
202 void BuildNetworkSession();
204 void LoadCallback(scoped_ptr
<GCMStore::LoadResult
> load_result
);
205 void UpdateCallback(bool success
);
206 void ErrorCallback();
207 void OnCheckInCompleted(
208 const checkin_proto::AndroidCheckinResponse
& checkin_response
);
209 void StartMCSLogin();
211 base::DefaultClock clock_
;
213 base::CommandLine command_line_
;
215 base::FilePath gcm_store_path_
;
218 std::string server_host_
;
222 scoped_refptr
<net::URLRequestContextGetter
> url_request_context_getter_
;
223 net::NetLog net_log_
;
224 scoped_ptr
<net::NetLogLogger
> logger_
;
225 scoped_ptr
<net::HostResolver
> host_resolver_
;
226 scoped_ptr
<net::CertVerifier
> cert_verifier_
;
227 scoped_ptr
<net::ChannelIDService
> system_channel_id_service_
;
228 scoped_ptr
<net::TransportSecurityState
> transport_security_state_
;
229 scoped_ptr
<net::URLSecurityManager
> url_security_manager_
;
230 scoped_ptr
<net::HttpAuthHandlerFactory
> http_auth_handler_factory_
;
231 scoped_ptr
<net::HttpServerPropertiesImpl
> http_server_properties_
;
232 scoped_ptr
<net::HostMappingRules
> host_mapping_rules_
;
233 scoped_refptr
<net::HttpNetworkSession
> network_session_
;
234 scoped_ptr
<net::ProxyService
> proxy_service_
;
236 FakeGCMStatsRecorder recorder_
;
237 scoped_ptr
<GCMStore
> gcm_store_
;
238 scoped_ptr
<MCSClient
> mcs_client_
;
239 scoped_ptr
<CheckinRequest
> checkin_request_
;
241 scoped_ptr
<ConnectionFactoryImpl
> connection_factory_
;
243 base::Thread file_thread_
;
245 scoped_ptr
<base::RunLoop
> run_loop_
;
249 const base::CommandLine
& command_line
,
250 scoped_refptr
<net::URLRequestContextGetter
> url_request_context_getter
)
251 : command_line_(command_line
),
252 gcm_store_path_(base::FilePath(FILE_PATH_LITERAL("gcm_store"))),
256 url_request_context_getter_(url_request_context_getter
),
257 file_thread_("FileThread") {
258 if (command_line
.HasSwitch(kRMQFileName
)) {
259 gcm_store_path_
= command_line
.GetSwitchValuePath(kRMQFileName
);
261 if (command_line
.HasSwitch(kAndroidIdSwitch
)) {
262 base::StringToUint64(command_line
.GetSwitchValueASCII(kAndroidIdSwitch
),
265 if (command_line
.HasSwitch(kSecretSwitch
)) {
266 base::StringToUint64(command_line
.GetSwitchValueASCII(kSecretSwitch
),
269 server_host_
= kMCSServerHost
;
270 if (command_line
.HasSwitch(kServerHostSwitch
)) {
271 server_host_
= command_line
.GetSwitchValueASCII(kServerHostSwitch
);
273 server_port_
= kMCSServerPort
;
274 if (command_line
.HasSwitch(kServerPortSwitch
)) {
275 base::StringToInt(command_line
.GetSwitchValueASCII(kServerPortSwitch
),
280 MCSProbe::~MCSProbe() {
284 void MCSProbe::Start() {
285 file_thread_
.Start();
286 InitializeNetworkState();
287 BuildNetworkSession();
288 std::vector
<GURL
> endpoints(1,
290 net::HostPortPair(server_host_
,
291 server_port_
).ToString()));
292 connection_factory_
.reset(
293 new ConnectionFactoryImpl(endpoints
,
294 kDefaultBackoffPolicy
,
300 new GCMStoreImpl(gcm_store_path_
,
301 file_thread_
.message_loop_proxy(),
302 make_scoped_ptr
<Encryptor
>(new FakeEncryptor
)));
303 mcs_client_
.reset(new MCSClient("probe",
305 connection_factory_
.get(),
308 run_loop_
.reset(new base::RunLoop());
309 gcm_store_
->Load(base::Bind(&MCSProbe::LoadCallback
,
310 base::Unretained(this)));
314 void MCSProbe::LoadCallback(scoped_ptr
<GCMStore::LoadResult
> load_result
) {
315 DCHECK(load_result
->success
);
316 if (android_id_
!= 0 && secret_
!= 0) {
317 DVLOG(1) << "Presetting MCS id " << android_id_
;
318 load_result
->device_android_id
= android_id_
;
319 load_result
->device_security_token
= secret_
;
320 gcm_store_
->SetDeviceCredentials(android_id_
,
322 base::Bind(&MCSProbe::UpdateCallback
,
323 base::Unretained(this)));
325 android_id_
= load_result
->device_android_id
;
326 secret_
= load_result
->device_security_token
;
327 DVLOG(1) << "Loaded MCS id " << android_id_
;
329 mcs_client_
->Initialize(
330 base::Bind(&MCSProbe::ErrorCallback
, base::Unretained(this)),
331 base::Bind(&MessageReceivedCallback
),
332 base::Bind(&MessageSentCallback
),
335 if (!android_id_
|| !secret_
) {
336 DVLOG(1) << "Checkin to generate new MCS credentials.";
344 void MCSProbe::UpdateCallback(bool success
) {
347 void MCSProbe::InitializeNetworkState() {
348 FILE* log_file
= NULL
;
349 if (command_line_
.HasSwitch(kLogFileSwitch
)) {
350 base::FilePath log_path
= command_line_
.GetSwitchValuePath(kLogFileSwitch
);
352 log_file
= _wfopen(log_path
.value().c_str(), L
"w");
353 #elif defined(OS_POSIX)
354 log_file
= fopen(log_path
.value().c_str(), "w");
357 if (log_file
!= NULL
) {
358 scoped_ptr
<base::Value
> net_constants(net::NetLogLogger::GetConstants());
359 logger_
.reset(new net::NetLogLogger(log_file
, *net_constants
));
360 logger_
->set_log_level(net::NetLog::LOG_ALL_BUT_BYTES
);
361 logger_
->StartObserving(&net_log_
);
364 host_resolver_
= net::HostResolver::CreateDefaultResolver(&net_log_
);
366 if (command_line_
.HasSwitch(kIgnoreCertSwitch
)) {
367 cert_verifier_
.reset(new MyTestCertVerifier());
369 cert_verifier_
.reset(net::CertVerifier::CreateDefault());
371 system_channel_id_service_
.reset(
372 new net::ChannelIDService(
373 new net::DefaultChannelIDStore(NULL
),
374 base::WorkerPool::GetTaskRunner(true)));
376 transport_security_state_
.reset(new net::TransportSecurityState());
377 url_security_manager_
.reset(net::URLSecurityManager::Create(NULL
, NULL
));
378 http_auth_handler_factory_
.reset(
379 net::HttpAuthHandlerRegistryFactory::Create(
380 std::vector
<std::string
>(1, "basic"),
381 url_security_manager_
.get(),
382 host_resolver_
.get(),
386 http_server_properties_
.reset(new net::HttpServerPropertiesImpl());
387 host_mapping_rules_
.reset(new net::HostMappingRules());
388 proxy_service_
.reset(net::ProxyService::CreateDirectWithNetLog(&net_log_
));
391 void MCSProbe::BuildNetworkSession() {
392 net::HttpNetworkSession::Params session_params
;
393 session_params
.host_resolver
= host_resolver_
.get();
394 session_params
.cert_verifier
= cert_verifier_
.get();
395 session_params
.channel_id_service
= system_channel_id_service_
.get();
396 session_params
.transport_security_state
= transport_security_state_
.get();
397 session_params
.ssl_config_service
= new net::SSLConfigServiceDefaults();
398 session_params
.http_auth_handler_factory
= http_auth_handler_factory_
.get();
399 session_params
.http_server_properties
=
400 http_server_properties_
->GetWeakPtr();
401 session_params
.network_delegate
= NULL
; // TODO(zea): implement?
402 session_params
.host_mapping_rules
= host_mapping_rules_
.get();
403 session_params
.ignore_certificate_errors
= true;
404 session_params
.testing_fixed_http_port
= 0;
405 session_params
.testing_fixed_https_port
= 0;
406 session_params
.net_log
= &net_log_
;
407 session_params
.proxy_service
= proxy_service_
.get();
409 network_session_
= new net::HttpNetworkSession(session_params
);
412 void MCSProbe::ErrorCallback() {
413 LOG(INFO
) << "MCS error happened";
416 void MCSProbe::CheckIn() {
417 LOG(INFO
) << "Check-in request initiated.";
418 checkin_proto::ChromeBuildProto chrome_build_proto
;
419 chrome_build_proto
.set_platform(
420 checkin_proto::ChromeBuildProto::PLATFORM_LINUX
);
421 chrome_build_proto
.set_channel(
422 checkin_proto::ChromeBuildProto::CHANNEL_CANARY
);
423 chrome_build_proto
.set_chrome_version(kChromeVersion
);
425 CheckinRequest::RequestInfo
request_info(0,
427 std::map
<std::string
, std::string
>(),
431 checkin_request_
.reset(new CheckinRequest(
432 GServicesSettings::DefaultCheckinURL(),
434 kDefaultBackoffPolicy
,
435 base::Bind(&MCSProbe::OnCheckInCompleted
, base::Unretained(this)),
436 url_request_context_getter_
.get(),
438 checkin_request_
->Start();
441 void MCSProbe::OnCheckInCompleted(
442 const checkin_proto::AndroidCheckinResponse
& checkin_response
) {
443 bool success
= checkin_response
.has_android_id() &&
444 checkin_response
.android_id() != 0UL &&
445 checkin_response
.has_security_token() &&
446 checkin_response
.security_token() != 0UL;
447 LOG(INFO
) << "Check-in request completion "
448 << (success
? "success!" : "failure!");
453 android_id_
= checkin_response
.android_id();
454 secret_
= checkin_response
.security_token();
456 gcm_store_
->SetDeviceCredentials(android_id_
,
458 base::Bind(&MCSProbe::UpdateCallback
,
459 base::Unretained(this)));
464 void MCSProbe::StartMCSLogin() {
465 LOG(INFO
) << "MCS login initiated.";
467 mcs_client_
->Login(android_id_
, secret_
);
470 int MCSProbeMain(int argc
, char* argv
[]) {
471 base::AtExitManager exit_manager
;
473 base::CommandLine::Init(argc
, argv
);
474 logging::LoggingSettings settings
;
475 settings
.logging_dest
= logging::LOG_TO_SYSTEM_DEBUG_LOG
;
476 logging::InitLogging(settings
);
478 base::MessageLoopForIO message_loop
;
480 // For check-in and creating registration ids.
481 const scoped_refptr
<MyTestURLRequestContextGetter
> context_getter
=
482 new MyTestURLRequestContextGetter(
483 base::MessageLoop::current()->message_loop_proxy());
485 const base::CommandLine
& command_line
=
486 *base::CommandLine::ForCurrentProcess();
488 MCSProbe
mcs_probe(command_line
, context_getter
);
491 base::RunLoop run_loop
;
500 int main(int argc
, char* argv
[]) {
501 return gcm::MCSProbeMain(argc
, argv
);