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

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

Issue 1727033003: v4_update_protocol_manager: Basic implementation with TODOs (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Incorporate review feedback. Created 4 years, 9 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
(Empty)
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
3 // found in the LICENSE file.
4
5 #include "components/safe_browsing_db/v4_update_protocol_manager.h"
6
7 #include <utility>
8
9 #include "base/base64.h"
10 #include "base/macros.h"
11 #include "base/metrics/histogram_macros.h"
12 #include "base/timer/timer.h"
13 #include "components/safe_browsing_db/safebrowsing.pb.h"
14 #include "net/base/load_flags.h"
15 #include "net/http/http_response_headers.h"
16 #include "net/http/http_status_code.h"
17 #include "net/url_request/url_fetcher.h"
18 #include "net/url_request/url_request_context_getter.h"
19
20 using base::Time;
21 using base::TimeDelta;
22
23 namespace {
24
25 // Enumerate parsing failures for histogramming purposes. DO NOT CHANGE
26 // THE ORDERING OF THESE VALUES.
27 enum ParseResultType {
28 // Error parsing the protocol buffer from a string.
29 PARSE_FROM_STRING_ERROR = 0,
30
31 // No platform_type set in the response.
32 NO_PLATFORM_TYPE_ERROR = 1,
33
34 // No threat_entry_type set in the response.
35 NO_THREAT_ENTRY_TYPE_ERROR = 2,
36
37 // No threat_type set in the response.
38 NO_THREAT_TYPE_ERROR = 3,
39
40 // No state set in the response for one or more lists.
41 NO_STATE_ERROR = 4,
42
43 // Memory space for histograms is determined by the max. ALWAYS
44 // ADD NEW VALUES BEFORE THIS ONE.
45 PARSE_RESULT_TYPE_MAX = 5
46 };
47
48 // Record parsing errors of an update result.
49 void RecordParseUpdateResult(ParseResultType result_type) {
50 UMA_HISTOGRAM_ENUMERATION("SafeBrowsing.ParseV4UpdateResult", result_type,
51 PARSE_RESULT_TYPE_MAX);
52 }
53
54 void RecordUpdateResult(safe_browsing::V4OperationResult result) {
55 UMA_HISTOGRAM_ENUMERATION(
56 "SafeBrowsing.V4UpdateResult", result,
57 safe_browsing::V4OperationResult::OPERATION_RESULT_MAX);
58 }
59
60 } // namespace
61
62 namespace safe_browsing {
63
64 // The default V4UpdateProtocolManagerFactory.
65 class V4UpdateProtocolManagerFactoryImpl
66 : public V4UpdateProtocolManagerFactory {
67 public:
68 V4UpdateProtocolManagerFactoryImpl() {}
69 ~V4UpdateProtocolManagerFactoryImpl() override {}
70 V4UpdateProtocolManager* CreateProtocolManager(
71 net::URLRequestContextGetter* request_context_getter,
72 const V4ProtocolConfig& config) override {
73 return new V4UpdateProtocolManager(request_context_getter, config);
74 }
75
76 private:
77 DISALLOW_COPY_AND_ASSIGN(V4UpdateProtocolManagerFactoryImpl);
78 };
79
80 // V4UpdateProtocolManager implementation --------------------------------
81
82 // static
83 V4UpdateProtocolManagerFactory* V4UpdateProtocolManager::factory_ = NULL;
84
85 // static
86 V4UpdateProtocolManager* V4UpdateProtocolManager::Create(
87 net::URLRequestContextGetter* request_context_getter,
88 const V4ProtocolConfig& config) {
89 if (!factory_)
90 factory_ = new V4UpdateProtocolManagerFactoryImpl();
91 return factory_->CreateProtocolManager(request_context_getter, config);
92 }
93
94 void V4UpdateProtocolManager::ResetUpdateErrors() {
95 update_error_count_ = 0;
96 update_back_off_mult_ = 1;
97 }
98
99 V4UpdateProtocolManager::V4UpdateProtocolManager(
100 net::URLRequestContextGetter* request_context_getter,
101 const V4ProtocolConfig& config)
102 : update_error_count_(0),
103 update_back_off_mult_(1),
104 next_update_time_(Time::Now()),
105 config_(config),
106 request_context_getter_(request_context_getter),
107 url_fetcher_id_(0) {}
108
109 V4UpdateProtocolManager::~V4UpdateProtocolManager() {
110 }
111
112 std::string V4UpdateProtocolManager::GetUpdateRequest(
113 const base::hash_set<UpdateListIdentifier>& lists_to_update,
114 const base::hash_map<UpdateListIdentifier, std::string>&
115 current_list_states) {
116 // 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.
118 FetchThreatListUpdatesRequest request;
119 for (const auto& list_to_update : lists_to_update) {
120 ListUpdateRequest* list_update_request = request.add_list_update_requests();
121 list_update_request->set_platform_type(list_to_update.platform_type);
122 list_update_request->set_threat_entry_type(
123 list_to_update.threat_entry_type);
124 list_update_request->set_threat_type(list_to_update.threat_type);
125
126 // If the current state of the list is available, add that to the proto.
127 base::hash_map<UpdateListIdentifier, std::string>::const_iterator
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 }
132 }
133
134 // Serialize and Base64 encode.
135 std::string req_data, req_base64;
136 request.SerializeToString(&req_data);
137 base::Base64Encode(req_data, &req_base64);
138
139 return req_base64;
140 }
141
142 bool V4UpdateProtocolManager::ParseUpdateResponse(
143 const std::string& data,
144 std::vector<ListUpdateResponse>* list_update_responses) {
145 FetchThreatListUpdatesResponse response;
146
147 if (!response.ParseFromString(data)) {
148 RecordParseUpdateResult(PARSE_FROM_STRING_ERROR);
149 return false;
150 }
151
152 if (response.has_minimum_wait_duration()) {
153 // Seconds resolution is good enough so we ignore the nanos field.
154 base::TimeDelta next_update_interval = base::TimeDelta::FromSeconds(
155 response.minimum_wait_duration().seconds());
156 next_update_time_ = Time::Now() + next_update_interval;
157 }
158
159 // TODO(vakh): Do something useful with this response.
160 for (const ListUpdateResponse& list_update_response :
161 response.list_update_responses()) {
162 if (!list_update_response.has_platform_type()) {
163 RecordParseUpdateResult(NO_PLATFORM_TYPE_ERROR);
164 } else if (!list_update_response.has_threat_entry_type()) {
165 RecordParseUpdateResult(NO_THREAT_ENTRY_TYPE_ERROR);
166 } else if (!list_update_response.has_threat_type()) {
167 RecordParseUpdateResult(NO_THREAT_TYPE_ERROR);
168 } else if (!list_update_response.has_new_client_state()) {
169 RecordParseUpdateResult(NO_STATE_ERROR);
170 } else {
171 list_update_responses->push_back(list_update_response);
172 }
173 }
174 return true;
175 }
176
177 void V4UpdateProtocolManager::GetUpdates(
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());
183
184 // If an update request is already pending, return an empty result.
185 if (request_) {
186 RecordUpdateResult(V4OperationResult::ALREADY_PENDING_ERROR);
187 std::vector<ListUpdateResponse> list_update_responses;
188 callback.Run(list_update_responses);
189 return;
190 }
191
192 // We need to wait the minimum waiting duration, and if we are in backoff,
193 // we need to check if we're past the next allowed time. If we are, we can
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);
209
210 request_.reset(net::URLFetcher::Create(url_fetcher_id_++, update_url,
211 net::URLFetcher::GET, this)
212 .release());
213 callback_ = callback;
214
215 request_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
216 request_->SetRequestContext(request_context_getter_.get());
217 request_->Start();
218 //TODO(vakh): Handle request timeout.
219 }
220
221 // net::URLFetcherDelegate implementation ----------------------------------
222
223 // SafeBrowsing request responses are handled here.
224 void V4UpdateProtocolManager::OnURLFetchComplete(
225 const net::URLFetcher* source) {
226 DCHECK(CalledOnValidThread());
227
228 int response_code = source->GetResponseCode();
229 net::URLRequestStatus status = source->GetStatus();
230 V4ProtocolManagerUtil::RecordHttpResponseOrErrorCode(
231 "SafeBrowsing.V4UpdateHttpResponseOrErrorCode", status, response_code);
232
233 std::vector<ListUpdateResponse> list_update_responses;
234 if (status.is_success() && response_code == net::HTTP_OK) {
235 RecordUpdateResult(V4OperationResult::STATUS_200);
236 ResetUpdateErrors();
237 std::string data;
238 source->GetResponseAsString(&data);
239 if (!ParseUpdateResponse(data, &list_update_responses)) {
240 list_update_responses.clear();
241 RecordUpdateResult(V4OperationResult::PARSE_ERROR);
242 }
243 } else {
244 HandleUpdateError(Time::Now());
245
246 DVLOG(1) << "SafeBrowsing GetEncodedUpdates request for: "
247 << source->GetURL() << " failed with error: " << status.error()
248 << " and response code: " << response_code;
249
250 if (status.status() == net::URLRequestStatus::FAILED) {
251 RecordUpdateResult(V4OperationResult::NETWORK_ERROR);
252 } else {
253 RecordUpdateResult(V4OperationResult::HTTP_ERROR);
254 }
255 }
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();
262 }
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 }
270
271 GURL V4UpdateProtocolManager::GetUpdateUrl(
272 const std::string& req_base64) const {
273 return V4ProtocolManagerUtil::GetRequestUrl(req_base64, "encodedUpdates",
274 config_);
275 }
276
277 } // namespace safe_browsing
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698