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

Side by Side Diff: components/safe_browsing_db/v4_update_protocol_manager.cc

Issue 1848973004: Makes V4UpdateProtocolManager auto-schedule update fetching (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@v4_01_
Patch Set: git fetch && git pull && gclient sync Created 4 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
OLDNEW
1 // Copyright 2016 The Chromium Authors. All rights reserved. 1 // Copyright 2016 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 "components/safe_browsing_db/v4_update_protocol_manager.h" 5 #include "components/safe_browsing_db/v4_update_protocol_manager.h"
6 6
7 #include <utility> 7 #include <utility>
8 8
9 #include "base/base64.h" 9 #include "base/base64.h"
10 #include "base/macros.h" 10 #include "base/macros.h"
11 #include "base/metrics/histogram_macros.h" 11 #include "base/metrics/histogram_macros.h"
12 #include "base/rand_util.h"
12 #include "base/timer/timer.h" 13 #include "base/timer/timer.h"
13 #include "components/safe_browsing_db/safebrowsing.pb.h" 14 #include "components/safe_browsing_db/safebrowsing.pb.h"
14 #include "net/base/load_flags.h" 15 #include "net/base/load_flags.h"
15 #include "net/http/http_response_headers.h" 16 #include "net/http/http_response_headers.h"
16 #include "net/http/http_status_code.h" 17 #include "net/http/http_status_code.h"
17 #include "net/url_request/url_fetcher.h" 18 #include "net/url_request/url_fetcher.h"
18 #include "net/url_request/url_request_context_getter.h" 19 #include "net/url_request/url_request_context_getter.h"
19 20
20 using base::Time; 21 using base::Time;
21 using base::TimeDelta; 22 using base::TimeDelta;
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
54 void RecordUpdateResult(safe_browsing::V4OperationResult result) { 55 void RecordUpdateResult(safe_browsing::V4OperationResult result) {
55 UMA_HISTOGRAM_ENUMERATION( 56 UMA_HISTOGRAM_ENUMERATION(
56 "SafeBrowsing.V4UpdateResult", result, 57 "SafeBrowsing.V4UpdateResult", result,
57 safe_browsing::V4OperationResult::OPERATION_RESULT_MAX); 58 safe_browsing::V4OperationResult::OPERATION_RESULT_MAX);
58 } 59 }
59 60
60 } // namespace 61 } // namespace
61 62
62 namespace safe_browsing { 63 namespace safe_browsing {
63 64
65 // Minimum time, in seconds, from start up before we must issue an update query.
66 static const int kV4TimerStartIntervalSecMin = 60;
67
68 // Maximum time, in seconds, from start up before we must issue an update query.
69 static const int kV4TimerStartIntervalSecMax = 300;
70
64 // The default V4UpdateProtocolManagerFactory. 71 // The default V4UpdateProtocolManagerFactory.
65 class V4UpdateProtocolManagerFactoryImpl 72 class V4UpdateProtocolManagerFactoryImpl
66 : public V4UpdateProtocolManagerFactory { 73 : public V4UpdateProtocolManagerFactory {
67 public: 74 public:
68 V4UpdateProtocolManagerFactoryImpl() {} 75 V4UpdateProtocolManagerFactoryImpl() {}
69 ~V4UpdateProtocolManagerFactoryImpl() override {} 76 ~V4UpdateProtocolManagerFactoryImpl() override {}
70 V4UpdateProtocolManager* CreateProtocolManager( 77 scoped_ptr<V4UpdateProtocolManager> CreateProtocolManager(
71 net::URLRequestContextGetter* request_context_getter, 78 net::URLRequestContextGetter* request_context_getter,
72 const V4ProtocolConfig& config) override { 79 const V4ProtocolConfig& config,
73 return new V4UpdateProtocolManager(request_context_getter, config); 80 const base::hash_map<UpdateListIdentifier, std::string>&
81 current_list_states,
82 V4UpdateCallback callback) override {
83 return scoped_ptr<V4UpdateProtocolManager>(new V4UpdateProtocolManager(
84 request_context_getter, config, current_list_states, callback));
74 } 85 }
75 86
76 private: 87 private:
77 DISALLOW_COPY_AND_ASSIGN(V4UpdateProtocolManagerFactoryImpl); 88 DISALLOW_COPY_AND_ASSIGN(V4UpdateProtocolManagerFactoryImpl);
78 }; 89 };
79 90
80 // V4UpdateProtocolManager implementation -------------------------------- 91 // V4UpdateProtocolManager implementation --------------------------------
81 92
82 // static 93 // static
83 V4UpdateProtocolManagerFactory* V4UpdateProtocolManager::factory_ = NULL; 94 V4UpdateProtocolManagerFactory* V4UpdateProtocolManager::factory_ = NULL;
84 95
85 // static 96 // static
86 V4UpdateProtocolManager* V4UpdateProtocolManager::Create( 97 scoped_ptr<V4UpdateProtocolManager> V4UpdateProtocolManager::Create(
87 net::URLRequestContextGetter* request_context_getter, 98 net::URLRequestContextGetter* request_context_getter,
88 const V4ProtocolConfig& config) { 99 const V4ProtocolConfig& config,
100 const base::hash_map<UpdateListIdentifier, std::string>&
101 current_list_states,
102 V4UpdateCallback callback) {
89 if (!factory_) 103 if (!factory_)
90 factory_ = new V4UpdateProtocolManagerFactoryImpl(); 104 factory_ = new V4UpdateProtocolManagerFactoryImpl();
91 return factory_->CreateProtocolManager(request_context_getter, config); 105 return factory_->CreateProtocolManager(request_context_getter, config,
106 current_list_states, callback);
92 } 107 }
93 108
94 void V4UpdateProtocolManager::ResetUpdateErrors() { 109 void V4UpdateProtocolManager::ResetUpdateErrors() {
95 update_error_count_ = 0; 110 update_error_count_ = 0;
96 update_back_off_mult_ = 1; 111 update_back_off_mult_ = 1;
97 } 112 }
98 113
99 V4UpdateProtocolManager::V4UpdateProtocolManager( 114 V4UpdateProtocolManager::V4UpdateProtocolManager(
100 net::URLRequestContextGetter* request_context_getter, 115 net::URLRequestContextGetter* request_context_getter,
101 const V4ProtocolConfig& config) 116 const V4ProtocolConfig& config,
102 : update_error_count_(0), 117 const base::hash_map<UpdateListIdentifier, std::string>&
118 current_list_states,
119 V4UpdateCallback callback)
120 : current_list_states_(current_list_states),
121 update_error_count_(0),
103 update_back_off_mult_(1), 122 update_back_off_mult_(1),
104 next_update_time_(base::Time()), 123 next_update_interval_(base::TimeDelta::FromSeconds(
124 base::RandInt(kV4TimerStartIntervalSecMin,
125 kV4TimerStartIntervalSecMax))),
105 config_(config), 126 config_(config),
106 request_context_getter_(request_context_getter), 127 request_context_getter_(request_context_getter),
107 url_fetcher_id_(0) {} 128 url_fetcher_id_(0),
108 129 callback_(callback) {
109 V4UpdateProtocolManager::~V4UpdateProtocolManager() { 130 ScheduleNextUpdate(false /* no back off */);
110 } 131 }
111 132
112 std::string V4UpdateProtocolManager::GetUpdateRequest( 133 V4UpdateProtocolManager::~V4UpdateProtocolManager() {}
113 const base::hash_set<UpdateListIdentifier>& lists_to_update, 134
135 bool V4UpdateProtocolManager::IsUpdateScheduled() const {
136 return update_timer_.IsRunning();
137 }
138
139 void V4UpdateProtocolManager::ScheduleNextUpdate(bool back_off) {
140 // TODO(vakh): Set disable_auto_update correctly using the command line
141 // switch.
142 if (config_.disable_auto_update) {
143 DCHECK(!IsUpdateScheduled());
144 return;
145 }
146
147 // Reschedule with the new update.
148 base::TimeDelta next_update_interval = GetNextUpdateInterval(back_off);
149 ScheduleNextUpdateAfterInterval(next_update_interval);
150 }
151
152 // According to section 5 of the SafeBrowsing protocol specification, we must
153 // back off after a certain number of errors.
154 base::TimeDelta V4UpdateProtocolManager::GetNextUpdateInterval(bool back_off) {
155 DCHECK(CalledOnValidThread());
156 DCHECK(next_update_interval_ > base::TimeDelta());
157 base::TimeDelta next = next_update_interval_;
158 if (back_off) {
159 next = V4ProtocolManagerUtil::GetNextBackOffInterval(
160 &update_error_count_, &update_back_off_mult_);
161 }
162 return next;
163 }
164
165 void V4UpdateProtocolManager::ScheduleNextUpdateAfterInterval(
166 base::TimeDelta interval) {
167 DCHECK(CalledOnValidThread());
168 DCHECK(interval >= base::TimeDelta());
169 // Unschedule any current timer.
170 update_timer_.Stop();
171 update_timer_.Start(FROM_HERE, interval, this,
172 &V4UpdateProtocolManager::IssueUpdateRequest);
173 }
174
175 std::string V4UpdateProtocolManager::GetBase64SerializedUpdateRequestProto(
114 const base::hash_map<UpdateListIdentifier, std::string>& 176 const base::hash_map<UpdateListIdentifier, std::string>&
115 current_list_states) { 177 current_list_states) {
116 // Build the request. Client info and client states are not added to the 178 // Build the request. Client info and client states are not added to the
117 // request protocol buffer. Client info is passed as params in the url. 179 // request protocol buffer. Client info is passed as params in the url.
118 FetchThreatListUpdatesRequest request; 180 FetchThreatListUpdatesRequest request;
119 for (const auto& list_to_update : lists_to_update) { 181 for (const auto& entry : current_list_states) {
182 const auto& list_to_update = entry.first;
183 const auto& state = entry.second;
120 ListUpdateRequest* list_update_request = request.add_list_update_requests(); 184 ListUpdateRequest* list_update_request = request.add_list_update_requests();
121 list_update_request->set_platform_type(list_to_update.platform_type); 185 list_update_request->set_platform_type(list_to_update.platform_type);
122 list_update_request->set_threat_entry_type( 186 list_update_request->set_threat_entry_type(
123 list_to_update.threat_entry_type); 187 list_to_update.threat_entry_type);
124 list_update_request->set_threat_type(list_to_update.threat_type); 188 list_update_request->set_threat_type(list_to_update.threat_type);
125 189
126 // If the current state of the list is available, add that to the proto. 190 if (!state.empty()) {
127 base::hash_map<UpdateListIdentifier, std::string>::const_iterator 191 list_update_request->set_state(state);
128 list_iter = current_list_states.find(list_to_update);
129 if (list_iter != current_list_states.end()) {
130 list_update_request->set_state(list_iter->second);
131 } 192 }
132 } 193 }
133 194
134 // Serialize and Base64 encode. 195 // Serialize and Base64 encode.
135 std::string req_data, req_base64; 196 std::string req_data, req_base64;
136 request.SerializeToString(&req_data); 197 request.SerializeToString(&req_data);
137 base::Base64Encode(req_data, &req_base64); 198 base::Base64Encode(req_data, &req_base64);
138 199
139 return req_base64; 200 return req_base64;
140 } 201 }
141 202
142 bool V4UpdateProtocolManager::ParseUpdateResponse( 203 bool V4UpdateProtocolManager::ParseUpdateResponse(
143 const std::string& data, 204 const std::string& data,
144 std::vector<ListUpdateResponse>* list_update_responses) { 205 std::vector<ListUpdateResponse>* list_update_responses) {
145 FetchThreatListUpdatesResponse response; 206 FetchThreatListUpdatesResponse response;
146 207
147 if (!response.ParseFromString(data)) { 208 if (!response.ParseFromString(data)) {
148 RecordParseUpdateResult(PARSE_FROM_STRING_ERROR); 209 RecordParseUpdateResult(PARSE_FROM_STRING_ERROR);
149 return false; 210 return false;
150 } 211 }
151 212
152 if (response.has_minimum_wait_duration()) { 213 if (response.has_minimum_wait_duration()) {
153 // Seconds resolution is good enough so we ignore the nanos field. 214 // Seconds resolution is good enough so we ignore the nanos field.
154 base::TimeDelta next_update_interval = base::TimeDelta::FromSeconds( 215 int64_t minimum_wait_duration_seconds =
155 response.minimum_wait_duration().seconds()); 216 response.minimum_wait_duration().seconds();
156 next_update_time_ = Time::Now() + next_update_interval; 217
218 // Do not let the next_update_interval_ to be too low.
219 if (minimum_wait_duration_seconds < kV4TimerStartIntervalSecMin) {
220 minimum_wait_duration_seconds = kV4TimerStartIntervalSecMin;
221 }
222 next_update_interval_ =
223 base::TimeDelta::FromSeconds(minimum_wait_duration_seconds);
157 } 224 }
158 225
159 // TODO(vakh): Do something useful with this response. 226 // TODO(vakh): Do something useful with this response.
160 for (const ListUpdateResponse& list_update_response : 227 for (const ListUpdateResponse& list_update_response :
161 response.list_update_responses()) { 228 response.list_update_responses()) {
162 if (!list_update_response.has_platform_type()) { 229 if (!list_update_response.has_platform_type()) {
163 RecordParseUpdateResult(NO_PLATFORM_TYPE_ERROR); 230 RecordParseUpdateResult(NO_PLATFORM_TYPE_ERROR);
164 } else if (!list_update_response.has_threat_entry_type()) { 231 } else if (!list_update_response.has_threat_entry_type()) {
165 RecordParseUpdateResult(NO_THREAT_ENTRY_TYPE_ERROR); 232 RecordParseUpdateResult(NO_THREAT_ENTRY_TYPE_ERROR);
166 } else if (!list_update_response.has_threat_type()) { 233 } else if (!list_update_response.has_threat_type()) {
167 RecordParseUpdateResult(NO_THREAT_TYPE_ERROR); 234 RecordParseUpdateResult(NO_THREAT_TYPE_ERROR);
168 } else if (!list_update_response.has_new_client_state()) { 235 } else if (!list_update_response.has_new_client_state()) {
169 RecordParseUpdateResult(NO_STATE_ERROR); 236 RecordParseUpdateResult(NO_STATE_ERROR);
170 } else { 237 } else {
171 list_update_responses->push_back(list_update_response); 238 list_update_responses->push_back(list_update_response);
172 } 239 }
173 } 240 }
174 return true; 241 return true;
175 } 242 }
176 243
177 void V4UpdateProtocolManager::GetUpdates( 244 void V4UpdateProtocolManager::IssueUpdateRequest() {
178 const base::hash_set<UpdateListIdentifier>& lists_to_update,
179 const base::hash_map<UpdateListIdentifier, std::string>&
180 current_list_states,
181 UpdateCallback callback) {
182 DCHECK(CalledOnValidThread()); 245 DCHECK(CalledOnValidThread());
183 246
184 // If an update request is already pending, return an empty result. 247 // If an update request is already pending, record and return silently.
185 if (request_) { 248 if (request_.get()) {
186 RecordUpdateResult(V4OperationResult::ALREADY_PENDING_ERROR); 249 RecordUpdateResult(V4OperationResult::ALREADY_PENDING_ERROR);
187 std::vector<ListUpdateResponse> list_update_responses;
188 callback.Run(list_update_responses);
189 return; 250 return;
190 } 251 }
191 252
192 // We need to wait the minimum waiting duration, and if we are in backoff, 253 std::string req_base64 = GetBase64SerializedUpdateRequestProto(
193 // we need to check if we're past the next allowed time. If we are, we can 254 current_list_states_);
194 // proceed with the request. If not, we are required to return empty results.
195 if (Time::Now() <= next_update_time_) {
196 if (update_error_count_) {
197 RecordUpdateResult(V4OperationResult::BACKOFF_ERROR);
198 } else {
199 RecordUpdateResult(V4OperationResult::MIN_WAIT_DURATION_ERROR);
200 }
201 std::vector<ListUpdateResponse> list_update_responses;
202 callback.Run(list_update_responses);
203 return;
204 }
205
206 std::string req_base64 =
207 GetUpdateRequest(lists_to_update, current_list_states);
208 GURL update_url = GetUpdateUrl(req_base64); 255 GURL update_url = GetUpdateUrl(req_base64);
209 256
210 request_.reset(net::URLFetcher::Create(url_fetcher_id_++, update_url, 257 request_.reset(net::URLFetcher::Create(url_fetcher_id_++, update_url,
211 net::URLFetcher::GET, this) 258 net::URLFetcher::GET, this)
212 .release()); 259 .release());
213 callback_ = callback;
214 260
215 request_->SetLoadFlags(net::LOAD_DISABLE_CACHE); 261 request_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
216 request_->SetRequestContext(request_context_getter_.get()); 262 request_->SetRequestContext(request_context_getter_.get());
217 request_->Start(); 263 request_->Start();
218 //TODO(vakh): Handle request timeout. 264 // TODO(vakh): Handle request timeout.
219 } 265 }
220 266
221 // net::URLFetcherDelegate implementation ---------------------------------- 267 // net::URLFetcherDelegate implementation ----------------------------------
222 268
223 // SafeBrowsing request responses are handled here. 269 // SafeBrowsing request responses are handled here.
224 void V4UpdateProtocolManager::OnURLFetchComplete( 270 void V4UpdateProtocolManager::OnURLFetchComplete(
225 const net::URLFetcher* source) { 271 const net::URLFetcher* source) {
226 DCHECK(CalledOnValidThread()); 272 DCHECK(CalledOnValidThread());
227 273
228 int response_code = source->GetResponseCode(); 274 int response_code = source->GetResponseCode();
229 net::URLRequestStatus status = source->GetStatus(); 275 net::URLRequestStatus status = source->GetStatus();
230 V4ProtocolManagerUtil::RecordHttpResponseOrErrorCode( 276 V4ProtocolManagerUtil::RecordHttpResponseOrErrorCode(
231 "SafeBrowsing.V4UpdateHttpResponseOrErrorCode", status, response_code); 277 "SafeBrowsing.V4UpdateHttpResponseOrErrorCode", status, response_code);
232 278
233 std::vector<ListUpdateResponse> list_update_responses; 279 std::vector<ListUpdateResponse> list_update_responses;
280 bool back_off;
234 if (status.is_success() && response_code == net::HTTP_OK) { 281 if (status.is_success() && response_code == net::HTTP_OK) {
282 back_off = false;
235 RecordUpdateResult(V4OperationResult::STATUS_200); 283 RecordUpdateResult(V4OperationResult::STATUS_200);
236 ResetUpdateErrors(); 284 ResetUpdateErrors();
237 std::string data; 285 std::string data;
238 source->GetResponseAsString(&data); 286 source->GetResponseAsString(&data);
239 if (!ParseUpdateResponse(data, &list_update_responses)) { 287 if (!ParseUpdateResponse(data, &list_update_responses)) {
240 list_update_responses.clear(); 288 list_update_responses.clear();
241 RecordUpdateResult(V4OperationResult::PARSE_ERROR); 289 RecordUpdateResult(V4OperationResult::PARSE_ERROR);
242 } 290 }
291 // Invoke the callback with list_update_responses.
292 // The caller should update its state now, based on list_update_responses.
293 callback_.Run(list_update_responses);
243 } else { 294 } else {
244 HandleUpdateError(Time::Now()); 295 back_off = true;
245
246 DVLOG(1) << "SafeBrowsing GetEncodedUpdates request for: " 296 DVLOG(1) << "SafeBrowsing GetEncodedUpdates request for: "
247 << source->GetURL() << " failed with error: " << status.error() 297 << source->GetURL() << " failed with error: " << status.error()
248 << " and response code: " << response_code; 298 << " and response code: " << response_code;
249 299
250 if (status.status() == net::URLRequestStatus::FAILED) { 300 if (status.status() == net::URLRequestStatus::FAILED) {
251 RecordUpdateResult(V4OperationResult::NETWORK_ERROR); 301 RecordUpdateResult(V4OperationResult::NETWORK_ERROR);
252 } else { 302 } else {
253 RecordUpdateResult(V4OperationResult::HTTP_ERROR); 303 RecordUpdateResult(V4OperationResult::HTTP_ERROR);
254 } 304 }
305 // TODO(vakh): Figure out whether it is just a network error vs backoff vs
306 // another condition and RecordUpdateResult more accurately.
255 } 307 }
256
257 // Invoke the callback with list_update_responses, even if there was a parse
258 // error or an error response code (in which case list_update_responses will
259 // be empty). The caller can't be blocked indefinitely.
260 callback_.Run(list_update_responses);
261 request_.reset(); 308 request_.reset();
262 } 309 ScheduleNextUpdate(back_off);
263
264 void V4UpdateProtocolManager::HandleUpdateError(const Time& now) {
265 DCHECK(CalledOnValidThread());
266 base::TimeDelta next = V4ProtocolManagerUtil::GetNextBackOffInterval(
267 &update_error_count_, &update_back_off_mult_);
268 next_update_time_ = now + next;
269 } 310 }
270 311
271 GURL V4UpdateProtocolManager::GetUpdateUrl( 312 GURL V4UpdateProtocolManager::GetUpdateUrl(
272 const std::string& req_base64) const { 313 const std::string& req_base64) const {
273 return V4ProtocolManagerUtil::GetRequestUrl(req_base64, "encodedUpdates", 314 return V4ProtocolManagerUtil::GetRequestUrl(req_base64, "encodedUpdates",
274 config_); 315 config_);
275 } 316 }
276 317
277 } // namespace safe_browsing 318 } // namespace safe_browsing
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698