OLD | NEW |
---|---|
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | 1 // Copyright (c) 2012 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 "net/cert/multi_threaded_cert_verifier.h" | 5 #include "net/cert/multi_threaded_cert_verifier.h" |
6 | 6 |
7 #include <algorithm> | 7 #include <algorithm> |
8 | 8 |
9 #include "base/bind.h" | 9 #include "base/bind.h" |
10 #include "base/bind_helpers.h" | 10 #include "base/bind_helpers.h" |
11 #include "base/callback_helpers.h" | |
11 #include "base/compiler_specific.h" | 12 #include "base/compiler_specific.h" |
13 #include "base/containers/linked_list.h" | |
12 #include "base/message_loop/message_loop.h" | 14 #include "base/message_loop/message_loop.h" |
13 #include "base/metrics/histogram.h" | 15 #include "base/metrics/histogram.h" |
14 #include "base/profiler/scoped_tracker.h" | 16 #include "base/profiler/scoped_tracker.h" |
15 #include "base/sha1.h" | 17 #include "base/sha1.h" |
16 #include "base/stl_util.h" | 18 #include "base/stl_util.h" |
17 #include "base/synchronization/lock.h" | |
18 #include "base/threading/worker_pool.h" | 19 #include "base/threading/worker_pool.h" |
19 #include "base/time/time.h" | 20 #include "base/time/time.h" |
20 #include "base/values.h" | 21 #include "base/values.h" |
21 #include "net/base/hash_value.h" | 22 #include "net/base/hash_value.h" |
22 #include "net/base/net_errors.h" | 23 #include "net/base/net_errors.h" |
23 #include "net/cert/cert_trust_anchor_provider.h" | 24 #include "net/cert/cert_trust_anchor_provider.h" |
24 #include "net/cert/cert_verify_proc.h" | 25 #include "net/cert/cert_verify_proc.h" |
25 #include "net/cert/crl_set.h" | 26 #include "net/cert/crl_set.h" |
26 #include "net/cert/x509_certificate.h" | 27 #include "net/cert/x509_certificate.h" |
27 #include "net/cert/x509_certificate_net_log_param.h" | 28 #include "net/cert/x509_certificate_net_log_param.h" |
28 #include "net/log/net_log.h" | 29 #include "net/log/net_log.h" |
29 | 30 |
30 #if defined(USE_NSS_CERTS) || defined(OS_IOS) | 31 #if defined(USE_NSS_CERTS) || defined(OS_IOS) |
31 #include <private/pprthred.h> // PR_DetachThread | 32 #include <private/pprthred.h> // PR_DetachThread |
32 #endif | 33 #endif |
33 | 34 |
34 namespace net { | 35 namespace net { |
35 | 36 |
36 //////////////////////////////////////////////////////////////////////////// | 37 //////////////////////////////////////////////////////////////////////////// |
37 | 38 |
38 // Life of a request: | |
39 // | |
40 // MultiThreadedCertVerifier CertVerifierJob CertVerifierWorker Request | |
41 // | (origin loop) (worker loop) | |
42 // | | |
43 // Verify() | |
44 // |---->-------------------------------------<creates> | |
45 // | | |
46 // |---->-------------------<creates> | |
47 // | | |
48 // |---->-------------------------------------------------------<creates> | |
49 // | | |
50 // |---->---------------------------------------Start | |
51 // | | | |
52 // | PostTask | |
53 // | | |
54 // | <starts verifying> | |
55 // |---->-------------------AddRequest | | |
56 // | | |
57 // | | |
58 // | | |
59 // Finish | |
60 // | | |
61 // PostTask | |
62 // | |
63 // | | |
64 // DoReply | |
65 // |----<-----------------------------------------| | |
66 // HandleResult | |
67 // | | |
68 // |---->------------------HandleResult | |
69 // | | |
70 // |------>---------------------------Post | |
71 // | |
72 // | |
73 // | |
74 // On a cache hit, MultiThreadedCertVerifier::Verify() returns synchronously | 39 // On a cache hit, MultiThreadedCertVerifier::Verify() returns synchronously |
75 // without posting a task to a worker thread. | 40 // without posting a task to a worker thread. |
76 | 41 |
77 namespace { | 42 namespace { |
78 | 43 |
79 // The default value of max_cache_entries_. | 44 // The maximum number of cache entries to use for the ExpiringCache. |
80 const unsigned kMaxCacheEntries = 256; | 45 const unsigned kMaxCacheEntries = 256; |
81 | 46 |
82 // The number of seconds for which we'll cache a cache entry. | 47 // The number of seconds to cache entries. |
83 const unsigned kTTLSecs = 1800; // 30 minutes. | 48 const unsigned kTTLSecs = 1800; // 30 minutes. |
84 | 49 |
85 base::Value* CertVerifyResultCallback(const CertVerifyResult& verify_result, | 50 base::Value* CertVerifyResultCallback(const CertVerifyResult& verify_result, |
86 NetLogCaptureMode capture_mode) { | 51 NetLogCaptureMode capture_mode) { |
87 base::DictionaryValue* results = new base::DictionaryValue(); | 52 base::DictionaryValue* results = new base::DictionaryValue(); |
88 results->SetBoolean("has_md5", verify_result.has_md5); | 53 results->SetBoolean("has_md5", verify_result.has_md5); |
89 results->SetBoolean("has_md2", verify_result.has_md2); | 54 results->SetBoolean("has_md2", verify_result.has_md2); |
90 results->SetBoolean("has_md4", verify_result.has_md4); | 55 results->SetBoolean("has_md4", verify_result.has_md4); |
91 results->SetBoolean("is_issued_by_known_root", | 56 results->SetBoolean("is_issued_by_known_root", |
92 verify_result.is_issued_by_known_root); | 57 verify_result.is_issued_by_known_root); |
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
158 // This algorithm is only problematic if the user consistently keeps | 123 // This algorithm is only problematic if the user consistently keeps |
159 // adjusting their clock backwards in increments smaller than the expiration | 124 // adjusting their clock backwards in increments smaller than the expiration |
160 // TTL, in which case, cached elements continue to be added. However, | 125 // TTL, in which case, cached elements continue to be added. However, |
161 // because the cache has a fixed upper bound, if no entries are expired, a | 126 // because the cache has a fixed upper bound, if no entries are expired, a |
162 // 'random' entry will be, thus keeping the memory constraints bounded over | 127 // 'random' entry will be, thus keeping the memory constraints bounded over |
163 // time. | 128 // time. |
164 return now.verification_time >= expiration.verification_time && | 129 return now.verification_time >= expiration.verification_time && |
165 now.verification_time < expiration.expiration_time; | 130 now.verification_time < expiration.expiration_time; |
166 }; | 131 }; |
167 | 132 |
168 | 133 // Represents the output and result callback of a request. The |
169 // Represents the output and result callback of a request. | 134 // CertVerifierRequest is owned by the caller that initiated the call to |
170 class CertVerifierRequest { | 135 // CertVerifier::Verify(). |
136 class CertVerifierRequest : public CertVerifier::Request, | |
137 public base::LinkNode<CertVerifierRequest> { | |
171 public: | 138 public: |
172 CertVerifierRequest(const CompletionCallback& callback, | 139 CertVerifierRequest(CertVerifierJob* job, |
140 const CompletionCallback& callback, | |
173 CertVerifyResult* verify_result, | 141 CertVerifyResult* verify_result, |
174 const BoundNetLog& net_log) | 142 const BoundNetLog& net_log) |
175 : callback_(callback), | 143 : job_(job), |
144 callback_(callback), | |
176 verify_result_(verify_result), | 145 verify_result_(verify_result), |
177 net_log_(net_log) { | 146 net_log_(net_log) { |
178 net_log_.BeginEvent(NetLog::TYPE_CERT_VERIFIER_REQUEST); | 147 net_log_.BeginEvent(NetLog::TYPE_CERT_VERIFIER_REQUEST); |
179 } | 148 } |
180 | 149 |
181 ~CertVerifierRequest() { | 150 // Cancels the request. |
182 } | 151 ~CertVerifierRequest() override; |
183 | |
184 // Ensures that the result callback will never be made. | |
185 void Cancel() { | |
186 callback_.Reset(); | |
187 verify_result_ = NULL; | |
188 net_log_.AddEvent(NetLog::TYPE_CANCELLED); | |
189 net_log_.EndEvent(NetLog::TYPE_CERT_VERIFIER_REQUEST); | |
190 } | |
191 | 152 |
192 // Copies the contents of |verify_result| to the caller's | 153 // Copies the contents of |verify_result| to the caller's |
193 // CertVerifyResult and calls the callback. | 154 // CertVerifyResult and calls the callback. |
194 void Post(const MultiThreadedCertVerifier::CachedResult& verify_result) { | 155 void Post(const MultiThreadedCertVerifier::CachedResult& verify_result) { |
195 if (!callback_.is_null()) { | 156 DCHECK(job_); |
196 net_log_.EndEvent(NetLog::TYPE_CERT_VERIFIER_REQUEST); | 157 job_ = nullptr; |
197 *verify_result_ = verify_result.result; | 158 |
198 callback_.Run(verify_result.error); | 159 net_log_.EndEvent(NetLog::TYPE_CERT_VERIFIER_REQUEST); |
199 } | 160 *verify_result_ = verify_result.result; |
200 delete this; | 161 |
162 base::ResetAndReturn(&callback_).Run(verify_result.error); | |
201 } | 163 } |
202 | 164 |
203 bool canceled() const { return callback_.is_null(); } | 165 void OnJobCancelled() { |
166 job_ = nullptr; | |
167 callback_.Reset(); | |
168 } | |
204 | 169 |
205 const BoundNetLog& net_log() const { return net_log_; } | 170 const BoundNetLog& net_log() const { return net_log_; } |
206 | 171 |
207 private: | 172 private: |
173 CertVerifierJob* job_; // Not owned. | |
208 CompletionCallback callback_; | 174 CompletionCallback callback_; |
209 CertVerifyResult* verify_result_; | 175 CertVerifyResult* verify_result_; |
210 const BoundNetLog net_log_; | 176 const BoundNetLog net_log_; |
211 }; | 177 }; |
212 | 178 |
179 // DoVerifyOnWorkerThread runs the verification synchronously on a worker | |
180 // thread. The output parameters (error and result) must remain alive. | |
181 void DoVerifyOnWorkerThread(scoped_refptr<CertVerifyProc> verify_proc, | |
182 scoped_refptr<X509Certificate> cert, | |
183 const std::string& hostname, | |
184 const std::string& ocsp_response, | |
185 int flags, | |
186 scoped_refptr<CRLSet> crl_set, | |
187 const CertificateList& additional_trust_anchors, | |
188 int* error, | |
189 CertVerifyResult* result) { | |
190 *error = verify_proc->Verify(cert.get(), hostname, ocsp_response, flags, | |
191 crl_set.get(), additional_trust_anchors, result); | |
213 | 192 |
214 // CertVerifierWorker runs on a worker thread and takes care of the blocking | |
215 // process of performing the certificate verification. Deletes itself | |
216 // eventually if Start() succeeds. | |
217 class CertVerifierWorker { | |
218 public: | |
219 CertVerifierWorker(CertVerifyProc* verify_proc, | |
220 X509Certificate* cert, | |
221 const std::string& hostname, | |
222 const std::string& ocsp_response, | |
223 int flags, | |
224 CRLSet* crl_set, | |
225 const CertificateList& additional_trust_anchors, | |
226 MultiThreadedCertVerifier* cert_verifier) | |
227 : verify_proc_(verify_proc), | |
228 cert_(cert), | |
229 hostname_(hostname), | |
230 ocsp_response_(ocsp_response), | |
231 flags_(flags), | |
232 crl_set_(crl_set), | |
233 additional_trust_anchors_(additional_trust_anchors), | |
234 origin_loop_(base::MessageLoop::current()), | |
235 cert_verifier_(cert_verifier), | |
236 canceled_(false), | |
237 error_(ERR_FAILED) {} | |
238 | |
239 // Returns the certificate being verified. May only be called /before/ | |
240 // Start() is called. | |
241 X509Certificate* certificate() const { return cert_.get(); } | |
242 | |
243 bool Start() { | |
244 DCHECK_EQ(base::MessageLoop::current(), origin_loop_); | |
245 | |
246 return base::WorkerPool::PostTask( | |
247 FROM_HERE, base::Bind(&CertVerifierWorker::Run, base::Unretained(this)), | |
248 true /* task is slow */); | |
249 } | |
250 | |
251 // Cancel is called from the origin loop when the MultiThreadedCertVerifier is | |
252 // getting deleted. | |
253 void Cancel() { | |
254 DCHECK_EQ(base::MessageLoop::current(), origin_loop_); | |
255 base::AutoLock locked(lock_); | |
256 canceled_ = true; | |
257 } | |
258 | |
259 private: | |
260 void Run() { | |
261 // Runs on a worker thread. | |
262 error_ = verify_proc_->Verify(cert_.get(), hostname_, ocsp_response_, | |
263 flags_, crl_set_.get(), | |
264 additional_trust_anchors_, &verify_result_); | |
265 #if defined(USE_NSS_CERTS) || defined(OS_IOS) | 193 #if defined(USE_NSS_CERTS) || defined(OS_IOS) |
266 // Detach the thread from NSPR. | 194 // Detach the thread from NSPR. |
267 // Calling NSS functions attaches the thread to NSPR, which stores | 195 // Calling NSS functions attaches the thread to NSPR, which stores |
268 // the NSPR thread ID in thread-specific data. | 196 // the NSPR thread ID in thread-specific data. |
269 // The threads in our thread pool terminate after we have called | 197 // The threads in our thread pool terminate after we have called |
270 // PR_Cleanup. Unless we detach them from NSPR, net_unittests gets | 198 // PR_Cleanup. Unless we detach them from NSPR, net_unittests gets |
271 // segfaults on shutdown when the threads' thread-specific data | 199 // segfaults on shutdown when the threads' thread-specific data |
272 // destructors run. | 200 // destructors run. |
273 PR_DetachThread(); | 201 PR_DetachThread(); |
274 #endif | 202 #endif |
275 Finish(); | 203 } |
204 | |
205 // CertVerifierJob lives only on the verifier's origin message loop. | |
206 class CertVerifierJob { | |
207 public: | |
208 CertVerifierJob(const MultiThreadedCertVerifier::RequestParams& key, | |
209 NetLog* net_log, | |
210 X509Certificate* cert, | |
211 MultiThreadedCertVerifier* cert_verifier) | |
212 : key_(key), | |
213 start_time_(base::TimeTicks::Now()), | |
214 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_CERT_VERIFIER_JOB)), | |
215 cert_verifier_(cert_verifier), | |
216 weak_ptr_factory_(this) { | |
217 net_log_.BeginEvent( | |
218 NetLog::TYPE_CERT_VERIFIER_JOB, | |
219 base::Bind(&NetLogX509CertificateCallback, base::Unretained(cert))); | |
276 } | 220 } |
277 | 221 |
278 // DoReply runs on the origin thread. | 222 // Indicates whether this was the first job started by the CertVerifier. This |
279 void DoReply() { | 223 // is only used for logging certain UMA stats. |
280 // TODO(pkasting): Remove ScopedTracker below once crbug.com/477117 is | 224 void set_is_first_job(bool is_first_job) { is_first_job_ = is_first_job; } |
281 // fixed. | |
282 tracked_objects::ScopedTracker tracking_profile( | |
283 FROM_HERE_WITH_EXPLICIT_FUNCTION("477117 CertVerifierWorker::DoReply")); | |
284 DCHECK_EQ(base::MessageLoop::current(), origin_loop_); | |
285 { | |
286 // We lock here because the worker thread could still be in Finished, | |
287 // after the PostTask, but before unlocking |lock_|. If we do not lock in | |
288 // this case, we will end up deleting a locked Lock, which can lead to | |
289 // memory leaks or worse errors. | |
290 base::AutoLock locked(lock_); | |
291 if (!canceled_) { | |
292 cert_verifier_->HandleResult(cert_.get(), hostname_, ocsp_response_, | |
293 flags_, additional_trust_anchors_, error_, | |
294 verify_result_); | |
295 } | |
296 } | |
297 delete this; | |
298 } | |
299 | 225 |
300 void Finish() { | 226 const MultiThreadedCertVerifier::RequestParams& key() const { return key_; } |
301 // Runs on the worker thread. | |
302 // We assume that the origin loop outlives the MultiThreadedCertVerifier. If | |
303 // the MultiThreadedCertVerifier is deleted, it will call Cancel on us. If | |
304 // it does so before the Acquire, we'll delete ourselves and return. If it's | |
305 // trying to do so concurrently, then it'll block on the lock and we'll call | |
306 // PostTask while the MultiThreadedCertVerifier (and therefore the | |
307 // MessageLoop) is still alive. | |
308 // If it does so after this function, we assume that the MessageLoop will | |
309 // process pending tasks. In which case we'll notice the |canceled_| flag | |
310 // in DoReply. | |
311 | 227 |
312 bool canceled; | 228 // Posts a task to the worker pool to do the verification. Once the |
313 { | 229 // verification has completed on the worker thread, it will call |
314 base::AutoLock locked(lock_); | 230 // OnJobCompleted() on the origin thread. |
315 canceled = canceled_; | 231 bool Start(const scoped_refptr<CertVerifyProc>& verify_proc, |
316 if (!canceled) { | 232 const scoped_refptr<X509Certificate>& cert, |
317 origin_loop_->PostTask( | 233 const std::string& hostname, |
318 FROM_HERE, base::Bind( | 234 const std::string& ocsp_response, |
319 &CertVerifierWorker::DoReply, base::Unretained(this))); | 235 int flags, |
320 } | 236 const scoped_refptr<CRLSet>& crl_set, |
321 } | 237 const CertificateList& additional_trust_anchors) { |
238 // Owned by the bound reply callback. | |
239 scoped_ptr<MultiThreadedCertVerifier::CachedResult> result( | |
240 new MultiThreadedCertVerifier::CachedResult()); | |
322 | 241 |
323 if (canceled) | 242 return base::WorkerPool::PostTaskAndReply( |
324 delete this; | 243 FROM_HERE, |
325 } | 244 base::Bind(DoVerifyOnWorkerThread, verify_proc, cert, hostname, |
326 | 245 ocsp_response, flags, crl_set, additional_trust_anchors, |
327 scoped_refptr<CertVerifyProc> verify_proc_; | 246 &result->error, &result->result), |
328 scoped_refptr<X509Certificate> cert_; | 247 base::Bind(&CertVerifierJob::OnJobCompleted, |
329 const std::string hostname_; | 248 weak_ptr_factory_.GetWeakPtr(), base::Passed(&result)), |
330 const std::string ocsp_response_; | 249 true /* task is slow */); |
331 const int flags_; | |
332 scoped_refptr<CRLSet> crl_set_; | |
333 const CertificateList additional_trust_anchors_; | |
334 base::MessageLoop* const origin_loop_; | |
335 MultiThreadedCertVerifier* const cert_verifier_; | |
336 | |
337 // lock_ protects canceled_. | |
338 base::Lock lock_; | |
339 | |
340 // If canceled_ is true, | |
341 // * origin_loop_ cannot be accessed by the worker thread, | |
342 // * cert_verifier_ cannot be accessed by any thread. | |
343 bool canceled_; | |
344 | |
345 int error_; | |
346 CertVerifyResult verify_result_; | |
347 | |
348 DISALLOW_COPY_AND_ASSIGN(CertVerifierWorker); | |
349 }; | |
350 | |
351 // A CertVerifierJob is a one-to-one counterpart of a CertVerifierWorker. It | |
352 // lives only on the CertVerifier's origin message loop. | |
353 class CertVerifierJob { | |
354 public: | |
355 CertVerifierJob(CertVerifierWorker* worker, | |
356 const BoundNetLog& net_log) | |
357 : start_time_(base::TimeTicks::Now()), | |
358 worker_(worker), | |
359 net_log_(net_log) { | |
360 net_log_.BeginEvent( | |
361 NetLog::TYPE_CERT_VERIFIER_JOB, | |
362 base::Bind(&NetLogX509CertificateCallback, | |
363 base::Unretained(worker_->certificate()))); | |
364 } | 250 } |
365 | 251 |
366 ~CertVerifierJob() { | 252 ~CertVerifierJob() { |
367 if (worker_) { | 253 // If the job is in progress, cancel it. |
254 if (cert_verifier_) { | |
255 cert_verifier_ = nullptr; | |
256 | |
368 net_log_.AddEvent(NetLog::TYPE_CANCELLED); | 257 net_log_.AddEvent(NetLog::TYPE_CANCELLED); |
369 net_log_.EndEvent(NetLog::TYPE_CERT_VERIFIER_JOB); | 258 net_log_.EndEvent(NetLog::TYPE_CERT_VERIFIER_JOB); |
370 worker_->Cancel(); | 259 |
371 DeleteAllCanceled(); | 260 // Notify each request of the cancellation. |
261 for (base::LinkNode<CertVerifierRequest>* it = requests_.head(); | |
262 it != requests_.end(); it = it->next()) { | |
263 it->value()->OnJobCancelled(); | |
264 } | |
372 } | 265 } |
373 } | 266 } |
374 | 267 |
375 void AddRequest(CertVerifierRequest* request) { | 268 // Creates and attaches a request to the Job. |
269 scoped_ptr<CertVerifierRequest> CreateRequest( | |
270 const CompletionCallback& callback, | |
271 CertVerifyResult* verify_result, | |
272 const BoundNetLog& net_log) { | |
273 scoped_ptr<CertVerifierRequest> request( | |
274 new CertVerifierRequest(this, callback, verify_result, net_log)); | |
275 | |
376 request->net_log().AddEvent( | 276 request->net_log().AddEvent( |
377 NetLog::TYPE_CERT_VERIFIER_REQUEST_BOUND_TO_JOB, | 277 NetLog::TYPE_CERT_VERIFIER_REQUEST_BOUND_TO_JOB, |
378 net_log_.source().ToEventParametersCallback()); | 278 net_log_.source().ToEventParametersCallback()); |
379 | 279 |
380 requests_.push_back(request); | 280 requests_.Append(request.get()); |
281 return request.Pass(); | |
381 } | 282 } |
382 | 283 |
383 void HandleResult( | 284 private: |
384 const MultiThreadedCertVerifier::CachedResult& verify_result, | 285 using RequestList = base::LinkedList<CertVerifierRequest>; |
385 bool is_first_job) { | 286 |
386 worker_ = NULL; | 287 // Called on completion of the Job to log UMA metrics and NetLog events. |
288 void LogMetrics( | |
289 const MultiThreadedCertVerifier::CachedResult& verify_result) { | |
387 net_log_.EndEvent( | 290 net_log_.EndEvent( |
388 NetLog::TYPE_CERT_VERIFIER_JOB, | 291 NetLog::TYPE_CERT_VERIFIER_JOB, |
389 base::Bind(&CertVerifyResultCallback, verify_result.result)); | 292 base::Bind(&CertVerifyResultCallback, verify_result.result)); |
390 base::TimeDelta latency = base::TimeTicks::Now() - start_time_; | 293 base::TimeDelta latency = base::TimeTicks::Now() - start_time_; |
391 UMA_HISTOGRAM_CUSTOM_TIMES("Net.CertVerifier_Job_Latency", | 294 UMA_HISTOGRAM_CUSTOM_TIMES("Net.CertVerifier_Job_Latency", |
392 latency, | 295 latency, |
393 base::TimeDelta::FromMilliseconds(1), | 296 base::TimeDelta::FromMilliseconds(1), |
394 base::TimeDelta::FromMinutes(10), | 297 base::TimeDelta::FromMinutes(10), |
395 100); | 298 100); |
396 if (is_first_job) { | 299 if (is_first_job_) { |
397 UMA_HISTOGRAM_CUSTOM_TIMES("Net.CertVerifier_First_Job_Latency", | 300 UMA_HISTOGRAM_CUSTOM_TIMES("Net.CertVerifier_First_Job_Latency", |
398 latency, | 301 latency, |
399 base::TimeDelta::FromMilliseconds(1), | 302 base::TimeDelta::FromMilliseconds(1), |
400 base::TimeDelta::FromMinutes(10), | 303 base::TimeDelta::FromMinutes(10), |
401 100); | 304 100); |
402 } | 305 } |
403 PostAll(verify_result); | |
404 } | 306 } |
405 | 307 |
406 private: | 308 void OnJobCompleted( |
407 void PostAll(const MultiThreadedCertVerifier::CachedResult& verify_result) { | 309 scoped_ptr<MultiThreadedCertVerifier::CachedResult> verify_result) { |
408 std::vector<CertVerifierRequest*> requests; | 310 scoped_ptr<CertVerifierJob> keep_alive = cert_verifier_->RemoveJob(this); |
409 requests_.swap(requests); | |
410 | 311 |
411 for (std::vector<CertVerifierRequest*>::iterator | 312 LogMetrics(*verify_result); |
412 i = requests.begin(); i != requests.end(); i++) { | 313 cert_verifier_->SaveResultToCache(key_, *verify_result); |
413 (*i)->Post(verify_result); | 314 cert_verifier_ = nullptr; |
414 // Post() causes the CertVerifierRequest to delete itself. | 315 |
316 // TODO(eroman): If the cert_verifier_ is deleted from within one of the | |
317 // callbacks, any remaining requests for that job should be cancelled. Right | |
318 // now they will be called. | |
319 while (!requests_.empty()) { | |
320 base::LinkNode<CertVerifierRequest>* request = requests_.head(); | |
321 request->RemoveFromList(); | |
322 request->value()->Post(*verify_result); | |
415 } | 323 } |
416 } | 324 } |
417 | 325 |
418 void DeleteAllCanceled() { | 326 const MultiThreadedCertVerifier::RequestParams key_; |
419 for (std::vector<CertVerifierRequest*>::iterator | 327 const base::TimeTicks start_time_; |
420 i = requests_.begin(); i != requests_.end(); i++) { | 328 |
421 if ((*i)->canceled()) { | 329 RequestList requests_; // Non-owned. |
422 delete *i; | 330 |
423 } else { | 331 const BoundNetLog net_log_; |
424 LOG(DFATAL) << "CertVerifierRequest leaked!"; | 332 MultiThreadedCertVerifier* cert_verifier_; // Non-owned. |
425 } | 333 |
426 } | 334 bool is_first_job_ = false; |
335 base::WeakPtrFactory<CertVerifierJob> weak_ptr_factory_; | |
336 }; | |
337 | |
338 CertVerifierRequest::~CertVerifierRequest() { | |
339 if (job_) { | |
340 // Cancel the outstanding request. | |
341 net_log_.AddEvent(NetLog::TYPE_CANCELLED); | |
342 net_log_.EndEvent(NetLog::TYPE_CERT_VERIFIER_REQUEST); | |
343 | |
344 // Remove the request from the Job. No attempt is made to cancel the job | |
345 // even though it may no longer have any requests attached to it. Because it | |
346 // is running on a worker thread aborting it isn't feasible. | |
347 RemoveFromList(); | |
427 } | 348 } |
428 | 349 } |
429 const base::TimeTicks start_time_; | |
430 std::vector<CertVerifierRequest*> requests_; | |
431 CertVerifierWorker* worker_; | |
432 const BoundNetLog net_log_; | |
433 }; | |
434 | 350 |
435 MultiThreadedCertVerifier::MultiThreadedCertVerifier( | 351 MultiThreadedCertVerifier::MultiThreadedCertVerifier( |
436 CertVerifyProc* verify_proc) | 352 CertVerifyProc* verify_proc) |
437 : cache_(kMaxCacheEntries), | 353 : cache_(kMaxCacheEntries), |
438 first_job_(NULL), | |
439 requests_(0), | 354 requests_(0), |
440 cache_hits_(0), | 355 cache_hits_(0), |
441 inflight_joins_(0), | 356 inflight_joins_(0), |
442 verify_proc_(verify_proc), | 357 verify_proc_(verify_proc), |
443 trust_anchor_provider_(NULL) { | 358 trust_anchor_provider_(NULL) { |
444 CertDatabase::GetInstance()->AddObserver(this); | 359 CertDatabase::GetInstance()->AddObserver(this); |
445 } | 360 } |
446 | 361 |
447 MultiThreadedCertVerifier::~MultiThreadedCertVerifier() { | 362 MultiThreadedCertVerifier::~MultiThreadedCertVerifier() { |
448 STLDeleteValues(&inflight_); | 363 STLDeleteElements(&inflight_); |
449 CertDatabase::GetInstance()->RemoveObserver(this); | 364 CertDatabase::GetInstance()->RemoveObserver(this); |
450 } | 365 } |
451 | 366 |
452 void MultiThreadedCertVerifier::SetCertTrustAnchorProvider( | 367 void MultiThreadedCertVerifier::SetCertTrustAnchorProvider( |
453 CertTrustAnchorProvider* trust_anchor_provider) { | 368 CertTrustAnchorProvider* trust_anchor_provider) { |
454 DCHECK(CalledOnValidThread()); | 369 DCHECK(CalledOnValidThread()); |
455 trust_anchor_provider_ = trust_anchor_provider; | 370 trust_anchor_provider_ = trust_anchor_provider; |
456 } | 371 } |
457 | 372 |
458 int MultiThreadedCertVerifier::Verify(X509Certificate* cert, | 373 int MultiThreadedCertVerifier::Verify(X509Certificate* cert, |
Alexander Potapenko
2015/04/30 10:40:52
Can two threads call MultiThreadedCertVerifier::Ve
eroman
2015/04/30 17:56:17
No. A single instance of MultiThreadedCertVerifier
eroman
2015/04/30 17:59:49
Actually let me rephrase that:
An individual inst
| |
459 const std::string& hostname, | 374 const std::string& hostname, |
460 const std::string& ocsp_response, | 375 const std::string& ocsp_response, |
461 int flags, | 376 int flags, |
462 CRLSet* crl_set, | 377 CRLSet* crl_set, |
463 CertVerifyResult* verify_result, | 378 CertVerifyResult* verify_result, |
464 const CompletionCallback& callback, | 379 const CompletionCallback& callback, |
465 RequestHandle* out_req, | 380 scoped_ptr<Request>* out_req, |
466 const BoundNetLog& net_log) { | 381 const BoundNetLog& net_log) { |
382 out_req->reset(); | |
383 | |
467 DCHECK(CalledOnValidThread()); | 384 DCHECK(CalledOnValidThread()); |
468 | 385 |
469 if (callback.is_null() || !verify_result || hostname.empty()) { | 386 if (callback.is_null() || !verify_result || hostname.empty()) |
470 *out_req = NULL; | |
471 return ERR_INVALID_ARGUMENT; | 387 return ERR_INVALID_ARGUMENT; |
472 } | |
473 | 388 |
474 requests_++; | 389 requests_++; |
475 | 390 |
476 const CertificateList empty_cert_list; | 391 const CertificateList empty_cert_list; |
477 const CertificateList& additional_trust_anchors = | 392 const CertificateList& additional_trust_anchors = |
478 trust_anchor_provider_ ? | 393 trust_anchor_provider_ ? |
479 trust_anchor_provider_->GetAdditionalTrustAnchors() : empty_cert_list; | 394 trust_anchor_provider_->GetAdditionalTrustAnchors() : empty_cert_list; |
480 | 395 |
481 const RequestParams key(cert->fingerprint(), cert->ca_fingerprint(), hostname, | 396 const RequestParams key(cert->fingerprint(), cert->ca_fingerprint(), hostname, |
482 ocsp_response, flags, additional_trust_anchors); | 397 ocsp_response, flags, additional_trust_anchors); |
483 const CertVerifierCache::value_type* cached_entry = | 398 const CertVerifierCache::value_type* cached_entry = |
484 cache_.Get(key, CacheValidityPeriod(base::Time::Now())); | 399 cache_.Get(key, CacheValidityPeriod(base::Time::Now())); |
485 if (cached_entry) { | 400 if (cached_entry) { |
486 ++cache_hits_; | 401 ++cache_hits_; |
487 *out_req = NULL; | |
488 *verify_result = cached_entry->result; | 402 *verify_result = cached_entry->result; |
489 return cached_entry->error; | 403 return cached_entry->error; |
490 } | 404 } |
491 | 405 |
492 // No cache hit. See if an identical request is currently in flight. | 406 // No cache hit. See if an identical request is currently in flight. |
493 CertVerifierJob* job; | 407 CertVerifierJob* job = FindJob(key); |
494 std::map<RequestParams, CertVerifierJob*>::const_iterator j; | 408 if (job) { |
495 j = inflight_.find(key); | |
496 if (j != inflight_.end()) { | |
497 // An identical request is in flight already. We'll just attach our | 409 // An identical request is in flight already. We'll just attach our |
498 // callback. | 410 // callback. |
499 inflight_joins_++; | 411 inflight_joins_++; |
500 job = j->second; | |
501 } else { | 412 } else { |
502 // Need to make a new request. | 413 // Need to make a new job. |
503 CertVerifierWorker* worker = new CertVerifierWorker( | 414 scoped_ptr<CertVerifierJob> new_job( |
504 verify_proc_.get(), cert, hostname, ocsp_response, flags, crl_set, | 415 new CertVerifierJob(key, net_log.net_log(), cert, this)); |
505 additional_trust_anchors, this); | 416 |
506 job = new CertVerifierJob( | 417 if (!new_job->Start(verify_proc_, cert, hostname, ocsp_response, flags, |
507 worker, | 418 crl_set, additional_trust_anchors)) { |
508 BoundNetLog::Make(net_log.net_log(), NetLog::SOURCE_CERT_VERIFIER_JOB)); | |
509 if (!worker->Start()) { | |
510 delete job; | |
511 delete worker; | |
512 *out_req = NULL; | |
513 // TODO(wtc): log to the NetLog. | 419 // TODO(wtc): log to the NetLog. |
514 LOG(ERROR) << "CertVerifierWorker couldn't be started."; | 420 LOG(ERROR) << "CertVerifierWorker couldn't be started."; |
515 return ERR_INSUFFICIENT_RESOURCES; // Just a guess. | 421 return ERR_INSUFFICIENT_RESOURCES; // Just a guess. |
516 } | 422 } |
517 inflight_.insert(std::make_pair(key, job)); | 423 |
518 if (requests_ == 1) { | 424 job = new_job.release(); |
519 // Cleared in HandleResult. | 425 inflight_.insert(job); |
520 first_job_ = job; | 426 |
521 } | 427 if (requests_ == 1) |
428 job->set_is_first_job(true); | |
522 } | 429 } |
523 | 430 |
524 CertVerifierRequest* request = | 431 scoped_ptr<CertVerifierRequest> request = |
525 new CertVerifierRequest(callback, verify_result, net_log); | 432 job->CreateRequest(callback, verify_result, net_log); |
526 job->AddRequest(request); | 433 *out_req = request.Pass(); |
527 *out_req = request; | |
528 return ERR_IO_PENDING; | 434 return ERR_IO_PENDING; |
529 } | 435 } |
530 | 436 |
531 void MultiThreadedCertVerifier::CancelRequest(RequestHandle req) { | |
532 DCHECK(CalledOnValidThread()); | |
533 CertVerifierRequest* request = reinterpret_cast<CertVerifierRequest*>(req); | |
534 request->Cancel(); | |
535 } | |
536 | |
537 bool MultiThreadedCertVerifier::SupportsOCSPStapling() { | 437 bool MultiThreadedCertVerifier::SupportsOCSPStapling() { |
538 return verify_proc_->SupportsOCSPStapling(); | 438 return verify_proc_->SupportsOCSPStapling(); |
539 } | 439 } |
540 | 440 |
541 MultiThreadedCertVerifier::RequestParams::RequestParams( | 441 MultiThreadedCertVerifier::RequestParams::RequestParams( |
542 const SHA1HashValue& cert_fingerprint_arg, | 442 const SHA1HashValue& cert_fingerprint_arg, |
543 const SHA1HashValue& ca_fingerprint_arg, | 443 const SHA1HashValue& ca_fingerprint_arg, |
544 const std::string& hostname_arg, | 444 const std::string& hostname_arg, |
545 const std::string& ocsp_response_arg, | 445 const std::string& ocsp_response_arg, |
546 int flags_arg, | 446 int flags_arg, |
(...skipping 20 matching lines...) Expand all Loading... | |
567 // are faster than memory and string comparisons. | 467 // are faster than memory and string comparisons. |
568 if (flags != other.flags) | 468 if (flags != other.flags) |
569 return flags < other.flags; | 469 return flags < other.flags; |
570 if (hostname != other.hostname) | 470 if (hostname != other.hostname) |
571 return hostname < other.hostname; | 471 return hostname < other.hostname; |
572 return std::lexicographical_compare( | 472 return std::lexicographical_compare( |
573 hash_values.begin(), hash_values.end(), other.hash_values.begin(), | 473 hash_values.begin(), hash_values.end(), other.hash_values.begin(), |
574 other.hash_values.end(), SHA1HashValueLessThan()); | 474 other.hash_values.end(), SHA1HashValueLessThan()); |
575 } | 475 } |
576 | 476 |
577 // HandleResult is called by CertVerifierWorker on the origin message loop. | 477 void MultiThreadedCertVerifier::SaveResultToCache(const RequestParams& key, |
578 // It deletes CertVerifierJob. | 478 const CachedResult& result) { |
579 void MultiThreadedCertVerifier::HandleResult( | |
580 X509Certificate* cert, | |
581 const std::string& hostname, | |
582 const std::string& ocsp_response, | |
583 int flags, | |
584 const CertificateList& additional_trust_anchors, | |
585 int error, | |
586 const CertVerifyResult& verify_result) { | |
587 DCHECK(CalledOnValidThread()); | 479 DCHECK(CalledOnValidThread()); |
588 | 480 |
589 const RequestParams key(cert->fingerprint(), cert->ca_fingerprint(), hostname, | |
590 ocsp_response, flags, additional_trust_anchors); | |
591 | |
592 CachedResult cached_result; | |
593 cached_result.error = error; | |
594 cached_result.result = verify_result; | |
595 base::Time now = base::Time::Now(); | 481 base::Time now = base::Time::Now(); |
596 cache_.Put( | 482 cache_.Put( |
597 key, cached_result, CacheValidityPeriod(now), | 483 key, result, CacheValidityPeriod(now), |
598 CacheValidityPeriod(now, now + base::TimeDelta::FromSeconds(kTTLSecs))); | 484 CacheValidityPeriod(now, now + base::TimeDelta::FromSeconds(kTTLSecs))); |
485 } | |
599 | 486 |
600 std::map<RequestParams, CertVerifierJob*>::iterator j; | 487 scoped_ptr<CertVerifierJob> MultiThreadedCertVerifier::RemoveJob( |
601 j = inflight_.find(key); | 488 CertVerifierJob* job) { |
602 if (j == inflight_.end()) { | 489 DCHECK(CalledOnValidThread()); |
603 NOTREACHED(); | 490 bool erased_job = inflight_.erase(job) == 1; |
604 return; | 491 DCHECK(erased_job); |
605 } | 492 return make_scoped_ptr(job); |
606 CertVerifierJob* job = j->second; | |
607 inflight_.erase(j); | |
608 bool is_first_job = false; | |
609 if (first_job_ == job) { | |
610 is_first_job = true; | |
611 first_job_ = NULL; | |
612 } | |
613 | |
614 job->HandleResult(cached_result, is_first_job); | |
615 delete job; | |
616 } | 493 } |
617 | 494 |
618 void MultiThreadedCertVerifier::OnCACertChanged( | 495 void MultiThreadedCertVerifier::OnCACertChanged( |
619 const X509Certificate* cert) { | 496 const X509Certificate* cert) { |
620 DCHECK(CalledOnValidThread()); | 497 DCHECK(CalledOnValidThread()); |
621 | 498 |
622 ClearCache(); | 499 ClearCache(); |
623 } | 500 } |
624 | 501 |
502 struct MultiThreadedCertVerifier::JobToRequestParamsComparator { | |
503 bool operator()(const CertVerifierJob* job, | |
504 const MultiThreadedCertVerifier::RequestParams& value) const { | |
505 return job->key() < value; | |
506 } | |
507 }; | |
508 | |
509 CertVerifierJob* MultiThreadedCertVerifier::FindJob(const RequestParams& key) { | |
510 DCHECK(CalledOnValidThread()); | |
511 | |
512 // The JobSet is kept in sorted order so items can be found using binary | |
513 // search. | |
514 JobSet::iterator it = std::lower_bound(inflight_.begin(), inflight_.end(), | |
515 key, JobToRequestParamsComparator()); | |
516 if (it != inflight_.end() && !(key < (*it)->key())) | |
517 return *it; | |
518 return nullptr; | |
519 } | |
520 | |
625 } // namespace net | 521 } // namespace net |
626 | 522 |
OLD | NEW |