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

Side by Side Diff: components/certificate_transparency/log_proof_fetcher.cc

Issue 1405293009: Certificate Transparency: Fetching consistency proofs. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Addressing comments Created 5 years 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 2015 The Chromium Authors. All rights reserved. 1 // Copyright 2015 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/certificate_transparency/log_proof_fetcher.h" 5 #include "components/certificate_transparency/log_proof_fetcher.h"
6 6
7 #include <iterator> 7 #include <iterator>
8 8
9 #include "base/callback_helpers.h"
10 #include "base/format_macros.h"
9 #include "base/logging.h" 11 #include "base/logging.h"
10 #include "base/memory/ref_counted.h" 12 #include "base/memory/ref_counted.h"
13 #include "base/numerics/safe_conversions.h"
11 #include "base/stl_util.h" 14 #include "base/stl_util.h"
15 #include "base/strings/stringprintf.h"
12 #include "base/values.h" 16 #include "base/values.h"
13 #include "components/safe_json/safe_json_parser.h" 17 #include "components/safe_json/safe_json_parser.h"
14 #include "net/base/io_buffer.h" 18 #include "net/base/io_buffer.h"
15 #include "net/base/load_flags.h" 19 #include "net/base/load_flags.h"
16 #include "net/base/net_errors.h" 20 #include "net/base/net_errors.h"
17 #include "net/base/request_priority.h" 21 #include "net/base/request_priority.h"
18 #include "net/cert/ct_log_response_parser.h" 22 #include "net/cert/ct_log_response_parser.h"
19 #include "net/cert/signed_tree_head.h" 23 #include "net/cert/signed_tree_head.h"
20 #include "net/http/http_status_code.h" 24 #include "net/http/http_status_code.h"
25 #include "net/url_request/url_request.h"
21 #include "net/url_request/url_request_context.h" 26 #include "net/url_request/url_request_context.h"
22 #include "url/gurl.h" 27 #include "url/gurl.h"
23 28
24 namespace certificate_transparency { 29 namespace certificate_transparency {
25 30
26 namespace { 31 namespace {
27 32
28 // Shamelessly copied from domain_reliability/util.cc 33 // Shamelessly copied from domain_reliability/util.cc
29 int GetNetErrorFromURLRequestStatus(const net::URLRequestStatus& status) { 34 int GetNetErrorFromURLRequestStatus(const net::URLRequestStatus& status) {
30 switch (status.status()) { 35 switch (status.status()) {
31 case net::URLRequestStatus::SUCCESS: 36 case net::URLRequestStatus::SUCCESS:
32 return net::OK; 37 return net::OK;
33 case net::URLRequestStatus::CANCELED: 38 case net::URLRequestStatus::CANCELED:
34 return net::ERR_ABORTED; 39 return net::ERR_ABORTED;
mmenke 2016/01/12 22:43:20 This is fine, but it's probably overkill. The onl
Eran Messeri 2016/01/18 15:50:55 Done.
35 case net::URLRequestStatus::FAILED: 40 case net::URLRequestStatus::FAILED:
36 return status.error(); 41 return status.error();
37 default: 42 default:
38 NOTREACHED(); 43 NOTREACHED();
39 return net::ERR_FAILED; 44 return net::ERR_FAILED;
40 } 45 }
41 } 46 }
42 47
43 } // namespace 48 } // namespace
44 49
45 struct LogProofFetcher::FetchState { 50 // Class for issuing a particular request from a CT log and assembling the
46 FetchState(const std::string& log_id, 51 // response.
47 const SignedTreeHeadFetchedCallback& fetched_callback, 52 // Creates the URLRequest instance for fetching the URL from the log
48 const FetchFailedCallback& failed_callback); 53 // (supplied as |request_url| in the c'tor) and implements the
49 ~FetchState(); 54 // URLRequest::Delegate interface for assembling the response.
50 55 class LogProofFetcher::LogFetcher : public net::URLRequest::Delegate {
51 std::string log_id; 56 public:
52 SignedTreeHeadFetchedCallback fetched_callback; 57 using FailureCallback = base::Callback<void(int, int)>;
53 FetchFailedCallback failed_callback; 58 LogFetcher(net::URLRequestContext* request_context,
Ryan Sleevi 2016/01/12 22:15:01 nit: newline between 57 & 58
Eran Messeri 2016/01/18 15:50:56 Done.
54 scoped_refptr<net::IOBufferWithSize> response_buffer; 59 const GURL& request_url,
55 std::string assembled_response; 60 const base::Closure& success_callback,
61 const FailureCallback& failure_callback);
62 ~LogFetcher() override {}
63
64 // net::URLRequest::Delegate
65 void OnResponseStarted(net::URLRequest* request) override;
66 void OnReadCompleted(net::URLRequest* request, int bytes_read) override;
67
68 const std::string& assembled_response() const { return assembled_response_; }
69
70 private:
71 // Handles the final result of a URLRequest::Read call on the request.
72 // Returns true if another read should be started, false if the read
73 // failed completely or we have to wait for OnResponseStarted to
74 // be called.
75 bool HandleReadResult(int bytes_read);
76
77 // Calls URLRequest::Read on |request| repeatedly, until HandleReadResult
78 // indicates it should no longer be called. Usually this would be when there
79 // is pending IO that requires waiting for OnResponseStarted to be called.
80 void StartNextRead();
81
82 // Invokes the success callback.
83 void RequestComplete();
84 // Invokes the failure callback with the supplied error information.
Ryan Sleevi 2016/01/12 22:15:01 nit: newline between 83 and 84?
Eran Messeri 2016/01/18 15:50:56 Done.
85 // After this method the LogFetcher instance may be deleted and |this|
Ryan Sleevi 2016/01/12 22:15:01 After this method what? (I believe you mean "Afte
Eran Messeri 2016/01/18 15:50:56 Done - the LogFetcher instance is deleted either b
86 // no longer valid.
87 void InvokeFailureCallback(int net_error, int http_response_code);
88
89 scoped_ptr<net::URLRequest> url_request_;
90 const GURL request_url_;
91 base::Closure success_callback_;
92 FailureCallback failure_callback_;
93 scoped_refptr<net::IOBufferWithSize> response_buffer_;
94 std::string assembled_response_;
95
96 DISALLOW_COPY_AND_ASSIGN(LogFetcher);
56 }; 97 };
57 98
58 LogProofFetcher::FetchState::FetchState( 99 LogProofFetcher::LogFetcher::LogFetcher(net::URLRequestContext* request_context,
100 const GURL& request_url,
101 const base::Closure& success_callback,
102 const FailureCallback& failure_callback)
103 : request_url_(request_url),
104 success_callback_(success_callback),
105 failure_callback_(failure_callback),
106 response_buffer_(new net::IOBufferWithSize(
107 LogProofFetcher::kMaxLogResponseSizeInBytes)) {
mmenke 2016/01/12 22:43:20 Optional: Could initialize this only once we rece
Eran Messeri 2016/01/18 15:50:55 Done - I've moved it to OnResponseStarted, please
108 DCHECK(request_url_.SchemeIsHTTPOrHTTPS());
109 url_request_ =
110 request_context->CreateRequest(request_url_, net::DEFAULT_PRIORITY, this);
111 // This request should not send any cookies or otherwise identifying data
Ryan Sleevi 2016/01/12 22:15:01 grammar: s/data/data, /
Eran Messeri 2016/01/18 15:50:56 Done.
112 // as CT logs are expected to be publicly-accessible and connections to them
113 // stateless.
114 url_request_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
115 net::LOAD_DO_NOT_SAVE_COOKIES |
116 net::LOAD_DO_NOT_SEND_AUTH_DATA);
117
118 url_request_->Start();
119 }
120
121 void LogProofFetcher::LogFetcher::OnResponseStarted(net::URLRequest* request) {
122 DCHECK_EQ(url_request_.get(), request);
123 net::URLRequestStatus status(request->status());
Ryan Sleevi 2016/01/12 22:15:01 Do you actually need to clone status? It seems lik
Eran Messeri 2016/01/18 15:50:55 I've simplified the code a bit to always calculate
124
125 if (!status.is_success() || request->GetResponseCode() != net::HTTP_OK) {
126 int net_error = net::OK;
127 int http_response_code = request->GetResponseCode();
128
129 if (!status.is_success())
130 net_error = GetNetErrorFromURLRequestStatus(status);
mmenke 2016/01/12 22:43:20 Get rid of this, and use GetNetErrorFromURLRequest
Eran Messeri 2016/01/18 15:50:55 Done.
131
132 InvokeFailureCallback(net_error, http_response_code);
133 return;
134 }
135
136 StartNextRead();
137 }
138
139 void LogProofFetcher::LogFetcher::OnReadCompleted(net::URLRequest* request,
140 int bytes_read) {
141 DCHECK_EQ(url_request_.get(), request);
142
143 if (HandleReadResult(bytes_read))
144 StartNextRead();
145 }
146
147 bool LogProofFetcher::LogFetcher::HandleReadResult(int bytes_read) {
148 // Start by checking for an error condition.
149 // If there are errors, invoke the failure callback and clean up the
150 // request.
151 if (bytes_read < 0 || !url_request_->status().is_success()) {
152 net::URLRequestStatus status(url_request_->status());
Ryan Sleevi 2016/01/12 22:15:01 This seems unnecessarily verbose - do you really n
Eran Messeri 2016/01/18 15:50:56 Done - removed temporary.
153 InvokeFailureCallback(GetNetErrorFromURLRequestStatus(status), net::OK);
154
155 return false;
156 }
157
158 // Not an error, but no data available, so wait for OnReadCompleted
159 // callback.
160 if (url_request_->status().is_io_pending())
161 return false;
162
163 // Nothing more to read from the stream - finish handling the response.
164 if (bytes_read == 0) {
165 RequestComplete();
166 return false;
167 }
168
169 // We have data, collect it and indicate another read is needed.
170 DCHECK_GE(bytes_read, 0);
Ryan Sleevi 2016/01/12 22:15:01 Why DCHECK here, given line 173?
Eran Messeri 2016/01/18 15:50:56 The checks later are to make sure we haven't read
171 // |bytes_read| is non-negative at this point, casting to size_t should be
172 // safe.
173 if (base::checked_cast<size_t>(bytes_read) >
174 LogProofFetcher::kMaxLogResponseSizeInBytes ||
175 LogProofFetcher::kMaxLogResponseSizeInBytes <
176 (assembled_response_.size() + bytes_read)) {
177 // Log response is too big, invoke the failure callback.
178 InvokeFailureCallback(net::ERR_FILE_TOO_BIG, net::HTTP_OK);
179 return false;
180 }
181
182 assembled_response_.append(response_buffer_->data(), bytes_read);
183 return true;
184 }
185
186 void LogProofFetcher::LogFetcher::StartNextRead() {
mmenke 2016/01/12 22:43:20 ReadLoop(), maybe?
Eran Messeri 2016/01/18 15:50:55 Done.
187 bool continue_reading = true;
188 while (continue_reading) {
189 int read_bytes = 0;
190 url_request_->Read(response_buffer_.get(), response_buffer_->size(),
191 &read_bytes);
192 continue_reading = HandleReadResult(read_bytes);
193 }
194 }
195
196 void LogProofFetcher::LogFetcher::RequestComplete() {
197 // Get rid of the buffer as it really isn't necessary.
198 response_buffer_ = nullptr;
199 base::ResetAndReturn(&success_callback_).Run();
200 }
201
202 void LogProofFetcher::LogFetcher::InvokeFailureCallback(
203 int net_error,
204 int http_response_code) {
205 base::ResetAndReturn(&failure_callback_).Run(net_error, http_response_code);
206 // NOTE: |this| not valid after this callback as the LogFetcher instance
207 // invoking the callback will be deleted by the callback.
208 }
209
210 // Interface for handling the response from a CT log for particular
211 // requests.
212 // All log responses are JSON and should be parsed; however the response
213 // to each request should be parsed and validated diffenetly.
214 class LogProofFetcher::LogResponseHandler {
215 public:
216 using DoneCallback =
217 base::Callback<void(LogProofFetcher::LogResponseHandler*)>;
218
219 // |log_id| will be passed to the callback to indicate which log
220 // this failure pretains to.
221 // All requests could fail so the |failure_callback| is shared to all
222 // request types.
223 LogResponseHandler(
224 const std::string& log_id,
225 const LogProofFetcher::FetchFailedCallback& failure_callback);
226 virtual ~LogResponseHandler();
227
228 void StartFetch(net::URLRequestContext* request_context,
229 const GURL& request_url,
230 const DoneCallback& done_callback);
231
232 // Handle successful fetch by the LogFetcher.
233 void HandleFetchCompletion();
234
235 // Handle network failure to complete the request to the log.
236 virtual void HandleNetFailure(int net_error, int http_response_code);
237
238 protected:
239 void OnJsonParseSuccess(scoped_ptr<base::Value> parsed_json);
240 void OnJsonParseError(const std::string& error);
241
242 // Handle respones JSON that parsed successfully, usually by
243 // invoking the success callback.
244 virtual void HandleParsedJson(const base::Value& parsed_json) = 0;
245
246 // Handle failure to parse response JSON, usually by invoking the failure
247 // callback with a request-specific net error code.
248 virtual void HandleJsonParseFailure(const std::string& json_error) = 0;
249
250 const std::string log_id_;
251 LogProofFetcher::FetchFailedCallback failure_callback_;
252 scoped_ptr<LogFetcher> fetcher_;
253 DoneCallback done_callback_;
254
255 base::WeakPtrFactory<LogProofFetcher::LogResponseHandler> weak_factory_;
256 };
257
258 LogProofFetcher::LogResponseHandler::LogResponseHandler(
59 const std::string& log_id, 259 const std::string& log_id,
60 const SignedTreeHeadFetchedCallback& fetched_callback, 260 const LogProofFetcher::FetchFailedCallback& failure_callback)
61 const FetchFailedCallback& failed_callback) 261 : log_id_(log_id),
62 : log_id(log_id), 262 failure_callback_(failure_callback),
63 fetched_callback(fetched_callback), 263 fetcher_(nullptr),
64 failed_callback(failed_callback), 264 weak_factory_(this) {
65 response_buffer(new net::IOBufferWithSize(kMaxLogResponseSizeInBytes)) {} 265 DCHECK(!failure_callback_.is_null());
66 266 }
67 LogProofFetcher::FetchState::~FetchState() {} 267
268 LogProofFetcher::LogResponseHandler::~LogResponseHandler() {}
269
270 void LogProofFetcher::LogResponseHandler::StartFetch(
271 net::URLRequestContext* request_context,
272 const GURL& request_url,
273 const DoneCallback& done_callback) {
274 base::Closure success_callback =
275 base::Bind(&LogProofFetcher::LogResponseHandler::HandleFetchCompletion,
276 weak_factory_.GetWeakPtr());
277 LogFetcher::FailureCallback failure_callback =
278 base::Bind(&LogProofFetcher::LogResponseHandler::HandleNetFailure,
279 weak_factory_.GetWeakPtr());
280
281 done_callback_ = done_callback;
282 fetcher_.reset(new LogFetcher(request_context, request_url, success_callback,
283 failure_callback));
284 }
285
286 void LogProofFetcher::LogResponseHandler::HandleFetchCompletion() {
287 safe_json::SafeJsonParser::Parse(
288 fetcher_->assembled_response(),
289 base::Bind(&LogProofFetcher::LogResponseHandler::OnJsonParseSuccess,
290 weak_factory_.GetWeakPtr()),
291 base::Bind(&LogProofFetcher::LogResponseHandler::OnJsonParseError,
292 weak_factory_.GetWeakPtr()));
293 }
294
295 void LogProofFetcher::LogResponseHandler::HandleNetFailure(
296 int net_error,
297 int http_response_code) {
298 base::ResetAndReturn(&failure_callback_)
299 .Run(log_id_, net_error, http_response_code);
300 base::ResetAndReturn(&done_callback_).Run(this);
Ryan Sleevi 2016/01/12 22:15:01 DESIGN: This strikes me weird that we would invoke
Eran Messeri 2016/01/18 15:50:56 Per your suggestion I now have one callback being
301 }
302
303 void LogProofFetcher::LogResponseHandler::OnJsonParseSuccess(
304 scoped_ptr<base::Value> parsed_json) {
305 HandleParsedJson(*parsed_json);
306 base::ResetAndReturn(&done_callback_).Run(this);
307 }
308
309 void LogProofFetcher::LogResponseHandler::OnJsonParseError(
310 const std::string& error) {
311 HandleJsonParseFailure(error);
312 base::ResetAndReturn(&done_callback_).Run(this);
Ryan Sleevi 2016/01/12 22:15:01 Both of these methods also seem to suffer from the
Eran Messeri 2016/01/18 15:50:55 See design changes I've highlighted above.
313 }
314
315 class LogProofFetcher::GetSTHLogResponseHandler
316 : public LogProofFetcher::LogResponseHandler {
317 public:
318 GetSTHLogResponseHandler(
319 const std::string& log_id,
320 const LogProofFetcher::SignedTreeHeadFetchedCallback& sth_fetch_callback,
321 const LogProofFetcher::FetchFailedCallback& failure_callback)
322 : LogResponseHandler(log_id, failure_callback),
323 sth_fetched_(sth_fetch_callback) {}
324
325 // Fill a net::ct::SignedTreeHead instance from the parsed JSON and, if
326 // successful, invoke the success callback with this STH.
327 // Otherwise, invoke the failure callback.
328 void HandleParsedJson(const base::Value& parsed_json) override {
329 net::ct::SignedTreeHead signed_tree_head;
330 if (!net::ct::FillSignedTreeHead(parsed_json, &signed_tree_head)) {
331 base::ResetAndReturn(&failure_callback_)
332 .Run(log_id_, net::ERR_CT_STH_INCOMPLETE, net::HTTP_OK);
333 return;
334 }
335
336 base::ResetAndReturn(&sth_fetched_).Run(log_id_, signed_tree_head);
337 }
338
339 // Invoke the error callback indicating that STH parsing failed.
340 void HandleJsonParseFailure(const std::string& json_error) override {
341 base::ResetAndReturn(&failure_callback_)
342 .Run(log_id_, net::ERR_CT_STH_PARSING_FAILED, net::HTTP_OK);
343 }
344
345 private:
346 LogProofFetcher::SignedTreeHeadFetchedCallback sth_fetched_;
347 };
348
349 class LogProofFetcher::GetConsistencyProofLogResponseHandler
350 : public LogProofFetcher::LogResponseHandler {
351 public:
352 GetConsistencyProofLogResponseHandler(
353 const std::string& log_id,
354 const LogProofFetcher::ConsistencyProofFetchedCallback&
355 proof_fetch_callback,
356 const LogProofFetcher::FetchFailedCallback& failure_callback)
357 : LogResponseHandler(log_id, failure_callback),
358 proof_fetched_(proof_fetch_callback) {}
359
360 // Fill a vector of strings with nodes from the received consistency proof
361 // and, if successful, invoke the success callback with this vector.
362 // Otherwise, invoke the failure callback indicating proof parsing has failed.
363 void HandleParsedJson(const base::Value& parsed_json) override {
364 std::vector<std::string> consistency_proof;
365 if (!net::ct::FillConsistencyProof(parsed_json, &consistency_proof)) {
366 base::ResetAndReturn(&failure_callback_)
367 .Run(log_id_, net::ERR_CT_CONSISTENCY_PROOF_PARSING_FAILED,
368 net::HTTP_OK);
369 return;
370 }
371
372 base::ResetAndReturn(&proof_fetched_).Run(log_id_, consistency_proof);
373 }
374
375 // Invoke the error callback indicating proof fetching failed.
376 void HandleJsonParseFailure(const std::string& json_error) override {
377 base::ResetAndReturn(&failure_callback_)
378 .Run(log_id_, net::ERR_CT_CONSISTENCY_PROOF_PARSING_FAILED,
379 net::HTTP_OK);
380 }
381
382 private:
383 LogProofFetcher::ConsistencyProofFetchedCallback proof_fetched_;
384 };
68 385
69 LogProofFetcher::LogProofFetcher(net::URLRequestContext* request_context) 386 LogProofFetcher::LogProofFetcher(net::URLRequestContext* request_context)
70 : request_context_(request_context), weak_factory_(this) { 387 : request_context_(request_context), weak_factory_(this) {
71 DCHECK(request_context); 388 DCHECK(request_context);
72 } 389 }
73 390
74 LogProofFetcher::~LogProofFetcher() { 391 LogProofFetcher::~LogProofFetcher() {
75 STLDeleteContainerPairPointers(inflight_requests_.begin(), 392 STLDeleteContainerPointers(inflight_fetches_.begin(),
76 inflight_requests_.end()); 393 inflight_fetches_.end());
77 } 394 }
78 395
79 void LogProofFetcher::FetchSignedTreeHead( 396 void LogProofFetcher::FetchSignedTreeHead(
80 const GURL& base_log_url, 397 const GURL& base_log_url,
81 const std::string& log_id, 398 const std::string& log_id,
82 const SignedTreeHeadFetchedCallback& fetched_callback, 399 const SignedTreeHeadFetchedCallback& fetched_callback,
83 const FetchFailedCallback& failed_callback) { 400 const FetchFailedCallback& failed_callback) {
84 DCHECK(base_log_url.SchemeIsHTTPOrHTTPS()); 401 GURL request_url = base_log_url.Resolve("ct/v1/get-sth");
85 GURL fetch_url(base_log_url.Resolve("ct/v1/get-sth")); 402 StartFetch(request_url, new GetSTHLogResponseHandler(log_id, fetched_callback,
86 scoped_ptr<net::URLRequest> request = 403 failed_callback));
87 request_context_->CreateRequest(fetch_url, net::DEFAULT_PRIORITY, this); 404 }
88 request->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES | 405
89 net::LOAD_DO_NOT_SAVE_COOKIES | 406 void LogProofFetcher::FetchConsistencyProof(
90 net::LOAD_DO_NOT_SEND_AUTH_DATA); 407 const GURL& base_log_url,
91 408 const std::string& log_id,
92 FetchState* fetch_state = 409 uint64_t old_tree_size,
93 new FetchState(log_id, fetched_callback, failed_callback); 410 uint64_t new_tree_size,
94 request->Start(); 411 const ConsistencyProofFetchedCallback& fetched_callback,
95 inflight_requests_.insert(std::make_pair(request.release(), fetch_state)); 412 const FetchFailedCallback& failed_callback) {
96 } 413 GURL request_url = base_log_url.Resolve(base::StringPrintf(
97 414 "ct/v1/get-sth-consistency?first=%" PRIu64 "&second=%" PRIu64,
98 void LogProofFetcher::OnResponseStarted(net::URLRequest* request) { 415 old_tree_size, new_tree_size));
99 net::URLRequestStatus status(request->status()); 416 StartFetch(request_url, new GetConsistencyProofLogResponseHandler(
100 DCHECK(inflight_requests_.count(request)); 417 log_id, fetched_callback, failed_callback));
101 FetchState* fetch_state = inflight_requests_.find(request)->second; 418 }
102 419
103 if (!status.is_success() || request->GetResponseCode() != net::HTTP_OK) { 420 void LogProofFetcher::StartFetch(const GURL& request_url,
104 int net_error = net::OK; 421 LogResponseHandler* log_request) {
105 int http_response_code = request->GetResponseCode(); 422 LogResponseHandler::DoneCallback done_callback =
106 423 base::Bind(&LogProofFetcher::OnFetchDone, weak_factory_.GetWeakPtr());
107 DVLOG(1) << "Fetching STH from " << request->original_url() 424
108 << " failed. status:" << status.status() 425 log_request->StartFetch(request_context_, request_url, done_callback);
109 << " error:" << status.error() 426 inflight_fetches_.insert(log_request);
110 << " http response code: " << http_response_code; 427 }
111 if (!status.is_success()) 428
112 net_error = GetNetErrorFromURLRequestStatus(status); 429 void LogProofFetcher::OnFetchDone(LogResponseHandler* log_handler) {
113 430 auto it = inflight_fetches_.find(log_handler);
114 InvokeFailureCallback(request, net_error, http_response_code); 431 DCHECK(it != inflight_fetches_.end());
115 return; 432
116 } 433 auto next = it;
117 434 std::advance(next, 1);
118 StartNextRead(request, fetch_state); 435
119 } 436 STLDeleteContainerPointers(it, next);
Ryan Sleevi 2016/01/12 22:15:01 This (line 433-436) just seems... needlessly compl
Eran Messeri 2016/01/18 15:50:55 Done.
120 437 inflight_fetches_.erase(it);
121 void LogProofFetcher::OnReadCompleted(net::URLRequest* request,
122 int bytes_read) {
123 DCHECK(inflight_requests_.count(request));
124 FetchState* fetch_state = inflight_requests_.find(request)->second;
125
126 if (HandleReadResult(request, fetch_state, bytes_read))
127 StartNextRead(request, fetch_state);
128 }
129
130 bool LogProofFetcher::HandleReadResult(net::URLRequest* request,
131 FetchState* fetch_state,
132 int bytes_read) {
133 // Start by checking for an error condition.
134 // If there are errors, invoke the failure callback and clean up the
135 // request.
136 if (bytes_read == -1 || !request->status().is_success()) {
137 net::URLRequestStatus status(request->status());
138 DVLOG(1) << "Read error: " << status.status() << " " << status.error();
139 InvokeFailureCallback(request, GetNetErrorFromURLRequestStatus(status),
140 net::OK);
141
142 return false;
143 }
144
145 // Not an error, but no data available, so wait for OnReadCompleted
146 // callback.
147 if (request->status().is_io_pending())
148 return false;
149
150 // Nothing more to read from the stream - finish handling the response.
151 if (bytes_read == 0) {
152 RequestComplete(request);
153 return false;
154 }
155
156 // We have data, collect it and indicate another read is needed.
157 DVLOG(1) << "Have " << bytes_read << " bytes to assemble.";
158 DCHECK_GE(bytes_read, 0);
159 fetch_state->assembled_response.append(fetch_state->response_buffer->data(),
160 bytes_read);
161 if (fetch_state->assembled_response.size() > kMaxLogResponseSizeInBytes) {
162 // Log response is too big, invoke the failure callback.
163 InvokeFailureCallback(request, net::ERR_FILE_TOO_BIG, net::HTTP_OK);
164 return false;
165 }
166
167 return true;
168 }
169
170 void LogProofFetcher::StartNextRead(net::URLRequest* request,
171 FetchState* fetch_state) {
172 bool continue_reading = true;
173 while (continue_reading) {
174 int read_bytes = 0;
175 request->Read(fetch_state->response_buffer.get(),
176 fetch_state->response_buffer->size(), &read_bytes);
177 continue_reading = HandleReadResult(request, fetch_state, read_bytes);
178 }
179 }
180
181 void LogProofFetcher::RequestComplete(net::URLRequest* request) {
182 DCHECK(inflight_requests_.count(request));
183
184 FetchState* fetch_state = inflight_requests_.find(request)->second;
185
186 // Get rid of the buffer as it really isn't necessary.
187 fetch_state->response_buffer = nullptr;
188 safe_json::SafeJsonParser::Parse(
189 fetch_state->assembled_response,
190 base::Bind(&LogProofFetcher::OnSTHJsonParseSuccess,
191 weak_factory_.GetWeakPtr(), request),
192 base::Bind(&LogProofFetcher::OnSTHJsonParseError,
193 weak_factory_.GetWeakPtr(), request));
194 }
195
196 void LogProofFetcher::CleanupRequest(net::URLRequest* request) {
197 DVLOG(1) << "Cleaning up request to " << request->original_url();
198 auto it = inflight_requests_.find(request);
199 DCHECK(it != inflight_requests_.end());
200 auto next_it = it;
201 std::advance(next_it, 1);
202
203 // Delete FetchState and URLRequest, then the entry from inflight_requests_.
204 STLDeleteContainerPairPointers(it, next_it);
205 inflight_requests_.erase(it);
206 }
207
208 void LogProofFetcher::InvokeFailureCallback(net::URLRequest* request,
209 int net_error,
210 int http_response_code) {
211 DCHECK(inflight_requests_.count(request));
212 auto it = inflight_requests_.find(request);
213 FetchState* fetch_state = it->second;
214
215 fetch_state->failed_callback.Run(fetch_state->log_id, net_error,
216 http_response_code);
217 CleanupRequest(request);
218 }
219
220 void LogProofFetcher::OnSTHJsonParseSuccess(
221 net::URLRequest* request,
222 scoped_ptr<base::Value> parsed_json) {
223 DCHECK(inflight_requests_.count(request));
224
225 FetchState* fetch_state = inflight_requests_.find(request)->second;
226 net::ct::SignedTreeHead signed_tree_head;
227 if (net::ct::FillSignedTreeHead(*parsed_json.get(), &signed_tree_head)) {
228 fetch_state->fetched_callback.Run(fetch_state->log_id, signed_tree_head);
229 } else {
230 fetch_state->failed_callback.Run(fetch_state->log_id,
231 net::ERR_CT_STH_INCOMPLETE, net::HTTP_OK);
232 }
233
234 CleanupRequest(request);
235 }
236
237 void LogProofFetcher::OnSTHJsonParseError(net::URLRequest* request,
238 const std::string& error) {
239 InvokeFailureCallback(request, net::ERR_CT_STH_PARSING_FAILED, net::HTTP_OK);
240 } 438 }
241 439
242 } // namespace certificate_transparency 440 } // namespace certificate_transparency
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698