Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(361)

Side by Side Diff: google_apis/gcm/engine/gcm_store_impl.cc

Issue 215363007: [GCM] Adding basic G-services handling (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Created 6 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright 2014 The Chromium Authors. All rights reserved. 1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "google_apis/gcm/engine/gcm_store_impl.h" 5 #include "google_apis/gcm/engine/gcm_store_impl.h"
6 6
7 #include "base/basictypes.h" 7 #include "base/basictypes.h"
8 #include "base/bind.h" 8 #include "base/bind.h"
9 #include "base/callback.h" 9 #include "base/callback.h"
10 #include "base/file_util.h" 10 #include "base/file_util.h"
11 #include "base/files/file_path.h" 11 #include "base/files/file_path.h"
12 #include "base/logging.h" 12 #include "base/logging.h"
13 #include "base/message_loop/message_loop_proxy.h" 13 #include "base/message_loop/message_loop_proxy.h"
14 #include "base/metrics/histogram.h" 14 #include "base/metrics/histogram.h"
15 #include "base/sequenced_task_runner.h" 15 #include "base/sequenced_task_runner.h"
16 #include "base/stl_util.h" 16 #include "base/stl_util.h"
17 #include "base/strings/string_number_conversions.h" 17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_piece.h" 18 #include "base/strings/string_piece.h"
19 #include "base/time/time.h"
19 #include "base/tracked_objects.h" 20 #include "base/tracked_objects.h"
20 #include "components/os_crypt/os_crypt.h" 21 #include "components/os_crypt/os_crypt.h"
21 #include "google_apis/gcm/base/mcs_message.h" 22 #include "google_apis/gcm/base/mcs_message.h"
22 #include "google_apis/gcm/base/mcs_util.h" 23 #include "google_apis/gcm/base/mcs_util.h"
23 #include "google_apis/gcm/protocol/mcs.pb.h" 24 #include "google_apis/gcm/protocol/mcs.pb.h"
24 #include "third_party/leveldatabase/src/include/leveldb/db.h" 25 #include "third_party/leveldatabase/src/include/leveldb/db.h"
26 #include "third_party/leveldatabase/src/include/leveldb/write_batch.h"
25 27
26 namespace gcm { 28 namespace gcm {
27 29
28 namespace { 30 namespace {
29 31
30 // Limit to the number of outstanding messages per app. 32 // Limit to the number of outstanding messages per app.
31 const int kMessagesPerAppLimit = 20; 33 const int kMessagesPerAppLimit = 20;
32 34
33 // ---- LevelDB keys. ---- 35 // ---- LevelDB keys. ----
34 // Key for this device's android id. 36 // Key for this device's android id.
(...skipping 11 matching lines...) Expand all
46 const char kIncomingMsgKeyStart[] = "incoming1-"; 48 const char kIncomingMsgKeyStart[] = "incoming1-";
47 // Key guaranteed to be higher than all incoming message keys. 49 // Key guaranteed to be higher than all incoming message keys.
48 // Used for limiting iteration. 50 // Used for limiting iteration.
49 const char kIncomingMsgKeyEnd[] = "incoming2-"; 51 const char kIncomingMsgKeyEnd[] = "incoming2-";
50 // Lowest lexicographically ordered outgoing message key. 52 // Lowest lexicographically ordered outgoing message key.
51 // Used for prefixing outgoing messages. 53 // Used for prefixing outgoing messages.
52 const char kOutgoingMsgKeyStart[] = "outgoing1-"; 54 const char kOutgoingMsgKeyStart[] = "outgoing1-";
53 // Key guaranteed to be higher than all outgoing message keys. 55 // Key guaranteed to be higher than all outgoing message keys.
54 // Used for limiting iteration. 56 // Used for limiting iteration.
55 const char kOutgoingMsgKeyEnd[] = "outgoing2-"; 57 const char kOutgoingMsgKeyEnd[] = "outgoing2-";
58 // Lowest lexicographically ordered G service settings key.
59 // Used for prefixing G services settings.
60 const char kGServiceSettingKeyStart[] = "Gservice1-";
61 // Key guaranteed to be higher than all G services settings keys.
62 // Used for limiting iteration.
63 const char kGServiceSettingKeyEnd[] = "Gservice2-";
64 // Key used to timestamp last checkin (marked with G services settings update).
65 const char kLastCheckinTimeKey[] = "last_checkin_time";
56 66
57 std::string MakeRegistrationKey(const std::string& app_id) { 67 std::string MakeRegistrationKey(const std::string& app_id) {
58 return kRegistrationKeyStart + app_id; 68 return kRegistrationKeyStart + app_id;
59 } 69 }
60 70
61 std::string ParseRegistrationKey(const std::string& key) { 71 std::string ParseRegistrationKey(const std::string& key) {
62 return key.substr(arraysize(kRegistrationKeyStart) - 1); 72 return key.substr(arraysize(kRegistrationKeyStart) - 1);
63 } 73 }
64 74
65 std::string MakeIncomingKey(const std::string& persistent_id) { 75 std::string MakeIncomingKey(const std::string& persistent_id) {
66 return kIncomingMsgKeyStart + persistent_id; 76 return kIncomingMsgKeyStart + persistent_id;
67 } 77 }
68 78
69 std::string MakeOutgoingKey(const std::string& persistent_id) { 79 std::string MakeOutgoingKey(const std::string& persistent_id) {
70 return kOutgoingMsgKeyStart + persistent_id; 80 return kOutgoingMsgKeyStart + persistent_id;
71 } 81 }
72 82
73 std::string ParseOutgoingKey(const std::string& key) { 83 std::string ParseOutgoingKey(const std::string& key) {
74 return key.substr(arraysize(kOutgoingMsgKeyStart) - 1); 84 return key.substr(arraysize(kOutgoingMsgKeyStart) - 1);
75 } 85 }
76 86
87 std::string MakeGServiceSettingKey(const std::string& setting_name) {
88 return kGServiceSettingKeyStart + setting_name;
89 }
90
91 std::string ParseGServiceSettingKey(const std::string& key) {
92 return key.substr(arraysize(kGServiceSettingKeyStart) - 1);
93 }
94
77 // Note: leveldb::Slice keeps a pointer to the data in |s|, which must therefore 95 // Note: leveldb::Slice keeps a pointer to the data in |s|, which must therefore
78 // outlive the slice. 96 // outlive the slice.
79 // For example: MakeSlice(MakeOutgoingKey(x)) is invalid. 97 // For example: MakeSlice(MakeOutgoingKey(x)) is invalid.
80 leveldb::Slice MakeSlice(const base::StringPiece& s) { 98 leveldb::Slice MakeSlice(const base::StringPiece& s) {
81 return leveldb::Slice(s.begin(), s.size()); 99 return leveldb::Slice(s.begin(), s.size());
82 } 100 }
83 101
84 } // namespace 102 } // namespace
85 103
86 class GCMStoreImpl::Backend 104 class GCMStoreImpl::Backend
(...skipping 24 matching lines...) Expand all
111 void RemoveOutgoingMessages( 129 void RemoveOutgoingMessages(
112 const PersistentIdList& persistent_ids, 130 const PersistentIdList& persistent_ids,
113 const base::Callback<void(bool, const AppIdToMessageCountMap&)> 131 const base::Callback<void(bool, const AppIdToMessageCountMap&)>
114 callback); 132 callback);
115 void AddUserSerialNumber(const std::string& username, 133 void AddUserSerialNumber(const std::string& username,
116 int64 serial_number, 134 int64 serial_number,
117 const UpdateCallback& callback); 135 const UpdateCallback& callback);
118 void RemoveUserSerialNumber(const std::string& username, 136 void RemoveUserSerialNumber(const std::string& username,
119 const UpdateCallback& callback); 137 const UpdateCallback& callback);
120 void SetNextSerialNumber(int64 serial_number, const UpdateCallback& callback); 138 void SetNextSerialNumber(int64 serial_number, const UpdateCallback& callback);
139 void UpdateGServicesSettings(
140 const std::vector<std::string>& settings_to_remove,
141 const std::map<std::string, std::string>& settings_to_add,
142 const UpdateCallback& callback);
121 143
122 private: 144 private:
123 friend class base::RefCountedThreadSafe<Backend>; 145 friend class base::RefCountedThreadSafe<Backend>;
124 ~Backend(); 146 ~Backend();
125 147
126 bool LoadDeviceCredentials(uint64* android_id, uint64* security_token); 148 bool LoadDeviceCredentials(uint64* android_id, uint64* security_token);
127 bool LoadRegistrations(RegistrationInfoMap* registrations); 149 bool LoadRegistrations(RegistrationInfoMap* registrations);
128 bool LoadIncomingMessages(std::vector<std::string>* incoming_messages); 150 bool LoadIncomingMessages(std::vector<std::string>* incoming_messages);
129 bool LoadOutgoingMessages(OutgoingMessageMap* outgoing_messages); 151 bool LoadOutgoingMessages(OutgoingMessageMap* outgoing_messages);
152 bool LoadGServicesSettings(std::map<std::string, std::string>* settings,
153 base::Time* last_checkin_time);
130 154
131 const base::FilePath path_; 155 const base::FilePath path_;
132 scoped_refptr<base::SequencedTaskRunner> foreground_task_runner_; 156 scoped_refptr<base::SequencedTaskRunner> foreground_task_runner_;
133 157
134 scoped_ptr<leveldb::DB> db_; 158 scoped_ptr<leveldb::DB> db_;
135 }; 159 };
136 160
137 GCMStoreImpl::Backend::Backend( 161 GCMStoreImpl::Backend::Backend(
138 const base::FilePath& path, 162 const base::FilePath& path,
139 scoped_refptr<base::SequencedTaskRunner> foreground_task_runner) 163 scoped_refptr<base::SequencedTaskRunner> foreground_task_runner)
(...skipping 24 matching lines...) Expand all
164 base::Bind(callback, 188 base::Bind(callback,
165 base::Passed(&result))); 189 base::Passed(&result)));
166 return; 190 return;
167 } 191 }
168 db_.reset(db); 192 db_.reset(db);
169 193
170 if (!LoadDeviceCredentials(&result->device_android_id, 194 if (!LoadDeviceCredentials(&result->device_android_id,
171 &result->device_security_token) || 195 &result->device_security_token) ||
172 !LoadRegistrations(&result->registrations) || 196 !LoadRegistrations(&result->registrations) ||
173 !LoadIncomingMessages(&result->incoming_messages) || 197 !LoadIncomingMessages(&result->incoming_messages) ||
174 !LoadOutgoingMessages(&result->outgoing_messages)) { 198 !LoadOutgoingMessages(&result->outgoing_messages) ||
199 !LoadGServicesSettings(&result->g_services_settings,
200 &result->last_checkin_time)) {
175 result->device_android_id = 0; 201 result->device_android_id = 0;
176 result->device_security_token = 0; 202 result->device_security_token = 0;
177 result->registrations.clear(); 203 result->registrations.clear();
178 result->incoming_messages.clear(); 204 result->incoming_messages.clear();
179 result->outgoing_messages.clear(); 205 result->outgoing_messages.clear();
206 result->last_checkin_time = base::Time::FromInternalValue(0LL);
180 foreground_task_runner_->PostTask(FROM_HERE, 207 foreground_task_runner_->PostTask(FROM_HERE,
181 base::Bind(callback, 208 base::Bind(callback,
182 base::Passed(&result))); 209 base::Passed(&result)));
183 return; 210 return;
184 } 211 }
185 212
186 // Only record histograms if GCM had already been set up for this device. 213 // Only record histograms if GCM had already been set up for this device.
187 if (result->device_android_id != 0 && result->device_security_token != 0) { 214 if (result->device_android_id != 0 && result->device_security_token != 0) {
188 int64 file_size = 0; 215 int64 file_size = 0;
189 if (base::GetFileSize(path_, &file_size)) { 216 if (base::GetFileSize(path_, &file_size)) {
(...skipping 248 matching lines...) Expand 10 before | Expand all | Expand 10 after
438 removed_message_counts)); 465 removed_message_counts));
439 return; 466 return;
440 } 467 }
441 LOG(ERROR) << "LevelDB remove failed: " << s.ToString(); 468 LOG(ERROR) << "LevelDB remove failed: " << s.ToString();
442 foreground_task_runner_->PostTask(FROM_HERE, 469 foreground_task_runner_->PostTask(FROM_HERE,
443 base::Bind(callback, 470 base::Bind(callback,
444 false, 471 false,
445 AppIdToMessageCountMap())); 472 AppIdToMessageCountMap()));
446 } 473 }
447 474
475
fgorski 2014/03/28 14:30:51 remove extra lines.
fgorski 2014/03/29 01:09:32 Done.
476
477 void GCMStoreImpl::Backend::UpdateGServicesSettings(
478 const std::vector<std::string>& settings_to_remove,
479 const std::map<std::string, std::string>& settings_to_add,
480 const UpdateCallback& callback) {
481 leveldb::WriteBatch write_batch;
482
483 // Delete settings to remove.
484 for (std::vector<std::string>::const_iterator iter =
485 settings_to_remove.begin();
486 iter != settings_to_remove.end(); ++iter) {
487 write_batch.Delete(MakeSlice(MakeGServiceSettingKey(*iter)));
488 }
489
490 // Add settings to add.
491 for (std::map<std::string, std::string>::const_iterator iter =
492 settings_to_add.begin();
493 iter != settings_to_add.end(); ++iter) {
494 write_batch.Put(MakeSlice(MakeGServiceSettingKey(iter->first)),
495 MakeSlice(iter->second));
496 }
497
498 // Update last checkin time. (To Now)
fgorski 2014/03/28 14:30:51 use the last_checkin_time provided as parameter.
fgorski 2014/03/29 01:09:32 Done.
499 int64 now = base::Time::Now().ToInternalValue();
500 std::string now_str = base::Int64ToString(now);
501 write_batch.Put(MakeSlice(kLastCheckinTimeKey), MakeSlice(now_str));
502
503 // Write it all in batch.
504 leveldb::WriteOptions write_options;
505 write_options.sync = true;
506
507 leveldb::Status s = db_->Write(write_options, &write_batch);
508 if (!s.ok())
509 LOG(ERROR) << "LevelDB GService Settings update failed: " << s.ToString();
510 foreground_task_runner_->PostTask(FROM_HERE, base::Bind(callback, s.ok()));
511 }
512
448 bool GCMStoreImpl::Backend::LoadDeviceCredentials(uint64* android_id, 513 bool GCMStoreImpl::Backend::LoadDeviceCredentials(uint64* android_id,
449 uint64* security_token) { 514 uint64* security_token) {
450 leveldb::ReadOptions read_options; 515 leveldb::ReadOptions read_options;
451 read_options.verify_checksums = true; 516 read_options.verify_checksums = true;
452 517
453 std::string result; 518 std::string result;
454 leveldb::Status s = db_->Get(read_options, MakeSlice(kDeviceAIDKey), &result); 519 leveldb::Status s = db_->Get(read_options, MakeSlice(kDeviceAIDKey), &result);
455 if (s.ok()) { 520 if (s.ok()) {
456 if (!base::StringToUint64(result, android_id)) { 521 if (!base::StringToUint64(result, android_id)) {
457 LOG(ERROR) << "Failed to restore device id."; 522 LOG(ERROR) << "Failed to restore device id.";
(...skipping 95 matching lines...) Expand 10 before | Expand all | Expand 10 after
553 return false; 618 return false;
554 } 619 }
555 DVLOG(1) << "Found outgoing message with id " << id << " of type " 620 DVLOG(1) << "Found outgoing message with id " << id << " of type "
556 << base::IntToString(tag); 621 << base::IntToString(tag);
557 (*outgoing_messages)[id] = make_linked_ptr(message.release()); 622 (*outgoing_messages)[id] = make_linked_ptr(message.release());
558 } 623 }
559 624
560 return true; 625 return true;
561 } 626 }
562 627
628 bool GCMStoreImpl::Backend::LoadGServicesSettings(
629 std::map<std::string, std::string>* settings,
630 base::Time* last_checkin_time) {
631 leveldb::ReadOptions read_options;
632 read_options.verify_checksums = true;
633
634 scoped_ptr<leveldb::Iterator> iter(db_->NewIterator(read_options));
635 for (iter->Seek(MakeSlice(kGServiceSettingKeyStart));
636 iter->Valid() && iter->key().ToString() < kGServiceSettingKeyEnd;
637 iter->Next()) {
638 if (iter->value().size() <= 1) {
fgorski 2014/03/28 14:30:51 std::string value = iter->value().ToString(); in t
fgorski 2014/03/29 01:09:32 Done.
639 LOG(ERROR) << "Error reading GService Settings "
640 << iter->value().ToString();
641 return false;
642 }
643 std::string id = ParseGServiceSettingKey(iter->key().ToString());
644 (*settings)[id] = iter->value().ToString();
645 DVLOG(1) << "Found G Service setting with key: " << id
646 << ", and value: " << (*settings)[id];
647 }
648
649 std::string result;
650 leveldb::Status s = db_->Get(read_options,
651 MakeSlice(kLastCheckinTimeKey),
652 &result);
653 int64 time_internal;
654 if (s.ok()) {
fgorski 2014/03/28 14:30:51 add defaulting in else to enable smooth upgrade...
fgorski 2014/03/29 01:09:32 Done.
655 if (!base::StringToInt64(result, &time_internal)) {
656 LOG(ERROR) << "Failed to restore last checkin time.";
657 return false;
658 }
659 *last_checkin_time = base::Time::FromInternalValue(time_internal);
660 }
661
662 return true;
663 }
664
563 GCMStoreImpl::GCMStoreImpl( 665 GCMStoreImpl::GCMStoreImpl(
564 bool use_mock_keychain, 666 bool use_mock_keychain,
565 const base::FilePath& path, 667 const base::FilePath& path,
566 scoped_refptr<base::SequencedTaskRunner> blocking_task_runner) 668 scoped_refptr<base::SequencedTaskRunner> blocking_task_runner)
567 : backend_(new Backend(path, base::MessageLoopProxy::current())), 669 : backend_(new Backend(path, base::MessageLoopProxy::current())),
568 blocking_task_runner_(blocking_task_runner), 670 blocking_task_runner_(blocking_task_runner),
569 weak_ptr_factory_(this) { 671 weak_ptr_factory_(this) {
570 // On OSX, prevent the Keychain permissions popup during unit tests. 672 // On OSX, prevent the Keychain permissions popup during unit tests.
571 #if defined(OS_MACOSX) 673 #if defined(OS_MACOSX)
572 OSCrypt::UseMockKeychain(use_mock_keychain); 674 OSCrypt::UseMockKeychain(use_mock_keychain);
(...skipping 154 matching lines...) Expand 10 before | Expand all | Expand 10 after
727 blocking_task_runner_->PostTask( 829 blocking_task_runner_->PostTask(
728 FROM_HERE, 830 FROM_HERE,
729 base::Bind(&GCMStoreImpl::Backend::RemoveOutgoingMessages, 831 base::Bind(&GCMStoreImpl::Backend::RemoveOutgoingMessages,
730 backend_, 832 backend_,
731 persistent_ids, 833 persistent_ids,
732 base::Bind(&GCMStoreImpl::RemoveOutgoingMessagesContinuation, 834 base::Bind(&GCMStoreImpl::RemoveOutgoingMessagesContinuation,
733 weak_ptr_factory_.GetWeakPtr(), 835 weak_ptr_factory_.GetWeakPtr(),
734 callback))); 836 callback)));
735 } 837 }
736 838
839 void GCMStoreImpl::UpdateGServicesSettings(
840 const std::vector<std::string>& settings_to_remove,
841 const std::map<std::string, std::string>& settings_to_add,
842 const UpdateCallback& callback) {
843 blocking_task_runner_->PostTask(
844 FROM_HERE,
845 base::Bind(&GCMStoreImpl::Backend::UpdateGServicesSettings,
846 backend_,
847 settings_to_remove,
848 settings_to_add,
849 callback));
850 }
851
737 void GCMStoreImpl::LoadContinuation(const LoadCallback& callback, 852 void GCMStoreImpl::LoadContinuation(const LoadCallback& callback,
738 scoped_ptr<LoadResult> result) { 853 scoped_ptr<LoadResult> result) {
739 if (!result->success) { 854 if (!result->success) {
740 callback.Run(result.Pass()); 855 callback.Run(result.Pass());
741 return; 856 return;
742 } 857 }
743 int num_throttled_apps = 0; 858 int num_throttled_apps = 0;
744 for (OutgoingMessageMap::const_iterator 859 for (OutgoingMessageMap::const_iterator
745 iter = result->outgoing_messages.begin(); 860 iter = result->outgoing_messages.begin();
746 iter != result->outgoing_messages.end(); ++iter) { 861 iter != result->outgoing_messages.end(); ++iter) {
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
781 removed_message_counts.begin(); 896 removed_message_counts.begin();
782 iter != removed_message_counts.end(); ++iter) { 897 iter != removed_message_counts.end(); ++iter) {
783 DCHECK_NE(app_message_counts_.count(iter->first), 0U); 898 DCHECK_NE(app_message_counts_.count(iter->first), 0U);
784 app_message_counts_[iter->first] -= iter->second; 899 app_message_counts_[iter->first] -= iter->second;
785 DCHECK_GE(app_message_counts_[iter->first], 0); 900 DCHECK_GE(app_message_counts_[iter->first], 0);
786 } 901 }
787 callback.Run(true); 902 callback.Run(true);
788 } 903 }
789 904
790 } // namespace gcm 905 } // namespace gcm
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698