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 // Life of a request: | |
39 // | 38 // |
40 // MultiThreadedCertVerifier CertVerifierJob CertVerifierWorker Request | 39 // MultiThreadedCertVerifier is a thread-unsafe object which lives, dies, and is |
41 // | (origin loop) (worker loop) | 40 // operated on a single thread, henceforth referred to as the "origin" thread. |
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 // | 41 // |
74 // On a cache hit, MultiThreadedCertVerifier::Verify() returns synchronously | 42 // On a cache hit, MultiThreadedCertVerifier::Verify() returns synchronously |
75 // without posting a task to a worker thread. | 43 // without posting a task to a worker thread. |
| 44 // |
| 45 // Otherwise when an incoming Verify() request is received, |
| 46 // MultiThreadedCertVerifier checks if there is an outstanding "job" |
| 47 // (CertVerifierJob) in progress that can service the request. If there is, |
| 48 // the request is attached to that job. Otherwise a new job is started. |
| 49 // |
| 50 // A job (CertVerifierJob) and is a way to de-duplicate requests that are |
| 51 // fundamentally doing the same verification. CertVerifierJob is similarly |
| 52 // thread-unsafe and lives on the origin thread. |
| 53 // |
| 54 // To do the actual work, CertVerifierJob posts a task to WorkerPool |
| 55 // (PostTaskAndReply), and on completion notifies all requests attached to it. |
| 56 // |
| 57 // Cancellation: |
| 58 // |
| 59 // There are two ways for a request to be cancelled. |
| 60 // |
| 61 // (1) When the caller explicitly frees the Request. |
| 62 // |
| 63 // If the request was in-flight (attached to a job), then it is detached. |
| 64 // Note that no effort is made to reap jobs which have no attached requests. |
| 65 // (Because the worker task isn't cancelable). |
| 66 // |
| 67 // (2) When the MultiThreadedCertVerifier is deleted. |
| 68 // |
| 69 // This automatically cancels all outstanding requests. This is accomplished |
| 70 // by deleting each of the jobs owned by the MultiThreadedCertVerifier, |
| 71 // whose destructor in turn marks each attached request as canceled. |
| 72 // |
| 73 // TODO(eroman): If the MultiThreadedCertVerifier is deleted from within a |
| 74 // callback, the remaining requests in the completing job will NOT be cancelled. |
76 | 75 |
77 namespace { | 76 namespace { |
78 | 77 |
79 // The default value of max_cache_entries_. | 78 // The maximum number of cache entries to use for the ExpiringCache. |
80 const unsigned kMaxCacheEntries = 256; | 79 const unsigned kMaxCacheEntries = 256; |
81 | 80 |
82 // The number of seconds for which we'll cache a cache entry. | 81 // The number of seconds to cache entries. |
83 const unsigned kTTLSecs = 1800; // 30 minutes. | 82 const unsigned kTTLSecs = 1800; // 30 minutes. |
84 | 83 |
85 base::Value* CertVerifyResultCallback(const CertVerifyResult& verify_result, | 84 base::Value* CertVerifyResultCallback(const CertVerifyResult& verify_result, |
86 NetLogCaptureMode capture_mode) { | 85 NetLogCaptureMode capture_mode) { |
87 base::DictionaryValue* results = new base::DictionaryValue(); | 86 base::DictionaryValue* results = new base::DictionaryValue(); |
88 results->SetBoolean("has_md5", verify_result.has_md5); | 87 results->SetBoolean("has_md5", verify_result.has_md5); |
89 results->SetBoolean("has_md2", verify_result.has_md2); | 88 results->SetBoolean("has_md2", verify_result.has_md2); |
90 results->SetBoolean("has_md4", verify_result.has_md4); | 89 results->SetBoolean("has_md4", verify_result.has_md4); |
91 results->SetBoolean("is_issued_by_known_root", | 90 results->SetBoolean("is_issued_by_known_root", |
92 verify_result.is_issued_by_known_root); | 91 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 | 157 // This algorithm is only problematic if the user consistently keeps |
159 // adjusting their clock backwards in increments smaller than the expiration | 158 // adjusting their clock backwards in increments smaller than the expiration |
160 // TTL, in which case, cached elements continue to be added. However, | 159 // 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 | 160 // 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 | 161 // 'random' entry will be, thus keeping the memory constraints bounded over |
163 // time. | 162 // time. |
164 return now.verification_time >= expiration.verification_time && | 163 return now.verification_time >= expiration.verification_time && |
165 now.verification_time < expiration.expiration_time; | 164 now.verification_time < expiration.expiration_time; |
166 }; | 165 }; |
167 | 166 |
168 | 167 // Represents the output and result callback of a request. The |
169 // Represents the output and result callback of a request. | 168 // CertVerifierRequest is owned by the caller that initiated the call to |
170 class CertVerifierRequest { | 169 // CertVerifier::Verify(). |
| 170 class CertVerifierRequest : public base::LinkNode<CertVerifierRequest>, |
| 171 public CertVerifier::Request { |
171 public: | 172 public: |
172 CertVerifierRequest(const CompletionCallback& callback, | 173 CertVerifierRequest(CertVerifierJob* job, |
| 174 const CompletionCallback& callback, |
173 CertVerifyResult* verify_result, | 175 CertVerifyResult* verify_result, |
174 const BoundNetLog& net_log) | 176 const BoundNetLog& net_log) |
175 : callback_(callback), | 177 : job_(job), |
| 178 callback_(callback), |
176 verify_result_(verify_result), | 179 verify_result_(verify_result), |
177 net_log_(net_log) { | 180 net_log_(net_log) { |
178 net_log_.BeginEvent(NetLog::TYPE_CERT_VERIFIER_REQUEST); | 181 net_log_.BeginEvent(NetLog::TYPE_CERT_VERIFIER_REQUEST); |
179 } | 182 } |
180 | 183 |
181 ~CertVerifierRequest() { | 184 // Cancels the request. |
182 } | 185 ~CertVerifierRequest() override { |
| 186 if (job_) { |
| 187 // Cancel the outstanding request. |
| 188 net_log_.AddEvent(NetLog::TYPE_CANCELLED); |
| 189 net_log_.EndEvent(NetLog::TYPE_CERT_VERIFIER_REQUEST); |
183 | 190 |
184 // Ensures that the result callback will never be made. | 191 // Remove the request from the Job. No attempt is made to cancel the job |
185 void Cancel() { | 192 // even though it may no longer have any requests attached to it. Because |
186 callback_.Reset(); | 193 // it is running on a worker thread aborting it isn't feasible. |
187 verify_result_ = NULL; | 194 RemoveFromList(); |
188 net_log_.AddEvent(NetLog::TYPE_CANCELLED); | 195 } |
189 net_log_.EndEvent(NetLog::TYPE_CERT_VERIFIER_REQUEST); | |
190 } | 196 } |
191 | 197 |
192 // Copies the contents of |verify_result| to the caller's | 198 // Copies the contents of |verify_result| to the caller's |
193 // CertVerifyResult and calls the callback. | 199 // CertVerifyResult and calls the callback. |
194 void Post(const MultiThreadedCertVerifier::CachedResult& verify_result) { | 200 void Post(const MultiThreadedCertVerifier::CachedResult& verify_result) { |
195 if (!callback_.is_null()) { | 201 DCHECK(job_); |
196 net_log_.EndEvent(NetLog::TYPE_CERT_VERIFIER_REQUEST); | 202 job_ = nullptr; |
197 *verify_result_ = verify_result.result; | 203 |
198 callback_.Run(verify_result.error); | 204 net_log_.EndEvent(NetLog::TYPE_CERT_VERIFIER_REQUEST); |
199 } | 205 *verify_result_ = verify_result.result; |
200 delete this; | 206 |
| 207 base::ResetAndReturn(&callback_).Run(verify_result.error); |
201 } | 208 } |
202 | 209 |
203 bool canceled() const { return callback_.is_null(); } | 210 void OnJobCancelled() { |
| 211 job_ = nullptr; |
| 212 callback_.Reset(); |
| 213 } |
204 | 214 |
205 const BoundNetLog& net_log() const { return net_log_; } | 215 const BoundNetLog& net_log() const { return net_log_; } |
206 | 216 |
207 private: | 217 private: |
| 218 CertVerifierJob* job_; // Not owned. |
208 CompletionCallback callback_; | 219 CompletionCallback callback_; |
209 CertVerifyResult* verify_result_; | 220 CertVerifyResult* verify_result_; |
210 const BoundNetLog net_log_; | 221 const BoundNetLog net_log_; |
211 }; | 222 }; |
212 | 223 |
| 224 // DoVerifyOnWorkerThread runs the verification synchronously on a worker |
| 225 // thread. The output parameters (error and result) must remain alive. |
| 226 void DoVerifyOnWorkerThread(const scoped_refptr<CertVerifyProc>& verify_proc, |
| 227 const scoped_refptr<X509Certificate>& cert, |
| 228 const std::string& hostname, |
| 229 const std::string& ocsp_response, |
| 230 int flags, |
| 231 const scoped_refptr<CRLSet>& crl_set, |
| 232 const CertificateList& additional_trust_anchors, |
| 233 int* error, |
| 234 CertVerifyResult* result) { |
| 235 *error = verify_proc->Verify(cert.get(), hostname, ocsp_response, flags, |
| 236 crl_set.get(), additional_trust_anchors, result); |
213 | 237 |
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) | 238 #if defined(USE_NSS_CERTS) || defined(OS_IOS) |
266 // Detach the thread from NSPR. | 239 // Detach the thread from NSPR. |
267 // Calling NSS functions attaches the thread to NSPR, which stores | 240 // Calling NSS functions attaches the thread to NSPR, which stores |
268 // the NSPR thread ID in thread-specific data. | 241 // the NSPR thread ID in thread-specific data. |
269 // The threads in our thread pool terminate after we have called | 242 // The threads in our thread pool terminate after we have called |
270 // PR_Cleanup. Unless we detach them from NSPR, net_unittests gets | 243 // PR_Cleanup. Unless we detach them from NSPR, net_unittests gets |
271 // segfaults on shutdown when the threads' thread-specific data | 244 // segfaults on shutdown when the threads' thread-specific data |
272 // destructors run. | 245 // destructors run. |
273 PR_DetachThread(); | 246 PR_DetachThread(); |
274 #endif | 247 #endif |
275 Finish(); | 248 } |
| 249 |
| 250 // CertVerifierJob lives only on the verifier's origin message loop. |
| 251 class CertVerifierJob { |
| 252 public: |
| 253 CertVerifierJob(const MultiThreadedCertVerifier::RequestParams& key, |
| 254 NetLog* net_log, |
| 255 X509Certificate* cert, |
| 256 MultiThreadedCertVerifier* cert_verifier) |
| 257 : key_(key), |
| 258 start_time_(base::TimeTicks::Now()), |
| 259 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_CERT_VERIFIER_JOB)), |
| 260 cert_verifier_(cert_verifier), |
| 261 is_first_job_(false), |
| 262 weak_ptr_factory_(this) { |
| 263 net_log_.BeginEvent( |
| 264 NetLog::TYPE_CERT_VERIFIER_JOB, |
| 265 base::Bind(&NetLogX509CertificateCallback, base::Unretained(cert))); |
276 } | 266 } |
277 | 267 |
278 // DoReply runs on the origin thread. | 268 // Indicates whether this was the first job started by the CertVerifier. This |
279 void DoReply() { | 269 // is only used for logging certain UMA stats. |
280 // TODO(pkasting): Remove ScopedTracker below once crbug.com/477117 is | 270 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 | 271 |
300 void Finish() { | 272 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 | 273 |
312 bool canceled; | 274 // Posts a task to the worker pool to do the verification. Once the |
313 { | 275 // verification has completed on the worker thread, it will call |
314 base::AutoLock locked(lock_); | 276 // OnJobCompleted() on the origin thread. |
315 canceled = canceled_; | 277 bool Start(const scoped_refptr<CertVerifyProc>& verify_proc, |
316 if (!canceled) { | 278 const scoped_refptr<X509Certificate>& cert, |
317 origin_loop_->PostTask( | 279 const std::string& hostname, |
318 FROM_HERE, base::Bind( | 280 const std::string& ocsp_response, |
319 &CertVerifierWorker::DoReply, base::Unretained(this))); | 281 int flags, |
320 } | 282 const scoped_refptr<CRLSet>& crl_set, |
321 } | 283 const CertificateList& additional_trust_anchors) { |
| 284 // Owned by the bound reply callback. |
| 285 scoped_ptr<MultiThreadedCertVerifier::CachedResult> owned_result( |
| 286 new MultiThreadedCertVerifier::CachedResult()); |
322 | 287 |
323 if (canceled) | 288 // Parameter evaluation order is undefined in C++. Ensure the pointer value |
324 delete this; | 289 // is gotten before calling base::Passed(). |
325 } | 290 auto result = owned_result.get(); |
326 | 291 |
327 scoped_refptr<CertVerifyProc> verify_proc_; | 292 return base::WorkerPool::PostTaskAndReply( |
328 scoped_refptr<X509Certificate> cert_; | 293 FROM_HERE, |
329 const std::string hostname_; | 294 base::Bind(&DoVerifyOnWorkerThread, verify_proc, cert, hostname, |
330 const std::string ocsp_response_; | 295 ocsp_response, flags, crl_set, additional_trust_anchors, |
331 const int flags_; | 296 &result->error, &result->result), |
332 scoped_refptr<CRLSet> crl_set_; | 297 base::Bind(&CertVerifierJob::OnJobCompleted, |
333 const CertificateList additional_trust_anchors_; | 298 weak_ptr_factory_.GetWeakPtr(), base::Passed(&owned_result)), |
334 base::MessageLoop* const origin_loop_; | 299 true /* task is slow */); |
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 } | 300 } |
365 | 301 |
366 ~CertVerifierJob() { | 302 ~CertVerifierJob() { |
367 if (worker_) { | 303 // If the job is in progress, cancel it. |
| 304 if (cert_verifier_) { |
| 305 cert_verifier_ = nullptr; |
| 306 |
368 net_log_.AddEvent(NetLog::TYPE_CANCELLED); | 307 net_log_.AddEvent(NetLog::TYPE_CANCELLED); |
369 net_log_.EndEvent(NetLog::TYPE_CERT_VERIFIER_JOB); | 308 net_log_.EndEvent(NetLog::TYPE_CERT_VERIFIER_JOB); |
370 worker_->Cancel(); | 309 |
371 DeleteAllCanceled(); | 310 // Notify each request of the cancellation. |
| 311 for (base::LinkNode<CertVerifierRequest>* it = requests_.head(); |
| 312 it != requests_.end(); it = it->next()) { |
| 313 it->value()->OnJobCancelled(); |
| 314 } |
372 } | 315 } |
373 } | 316 } |
374 | 317 |
375 void AddRequest(CertVerifierRequest* request) { | 318 // Creates and attaches a request to the Job. |
| 319 scoped_ptr<CertVerifierRequest> CreateRequest( |
| 320 const CompletionCallback& callback, |
| 321 CertVerifyResult* verify_result, |
| 322 const BoundNetLog& net_log) { |
| 323 scoped_ptr<CertVerifierRequest> request( |
| 324 new CertVerifierRequest(this, callback, verify_result, net_log)); |
| 325 |
376 request->net_log().AddEvent( | 326 request->net_log().AddEvent( |
377 NetLog::TYPE_CERT_VERIFIER_REQUEST_BOUND_TO_JOB, | 327 NetLog::TYPE_CERT_VERIFIER_REQUEST_BOUND_TO_JOB, |
378 net_log_.source().ToEventParametersCallback()); | 328 net_log_.source().ToEventParametersCallback()); |
379 | 329 |
380 requests_.push_back(request); | 330 requests_.Append(request.get()); |
| 331 return request.Pass(); |
381 } | 332 } |
382 | 333 |
383 void HandleResult( | 334 private: |
384 const MultiThreadedCertVerifier::CachedResult& verify_result, | 335 using RequestList = base::LinkedList<CertVerifierRequest>; |
385 bool is_first_job) { | 336 |
386 worker_ = NULL; | 337 // Called on completion of the Job to log UMA metrics and NetLog events. |
| 338 void LogMetrics( |
| 339 const MultiThreadedCertVerifier::CachedResult& verify_result) { |
387 net_log_.EndEvent( | 340 net_log_.EndEvent( |
388 NetLog::TYPE_CERT_VERIFIER_JOB, | 341 NetLog::TYPE_CERT_VERIFIER_JOB, |
389 base::Bind(&CertVerifyResultCallback, verify_result.result)); | 342 base::Bind(&CertVerifyResultCallback, verify_result.result)); |
390 base::TimeDelta latency = base::TimeTicks::Now() - start_time_; | 343 base::TimeDelta latency = base::TimeTicks::Now() - start_time_; |
391 UMA_HISTOGRAM_CUSTOM_TIMES("Net.CertVerifier_Job_Latency", | 344 UMA_HISTOGRAM_CUSTOM_TIMES("Net.CertVerifier_Job_Latency", |
392 latency, | 345 latency, |
393 base::TimeDelta::FromMilliseconds(1), | 346 base::TimeDelta::FromMilliseconds(1), |
394 base::TimeDelta::FromMinutes(10), | 347 base::TimeDelta::FromMinutes(10), |
395 100); | 348 100); |
396 if (is_first_job) { | 349 if (is_first_job_) { |
397 UMA_HISTOGRAM_CUSTOM_TIMES("Net.CertVerifier_First_Job_Latency", | 350 UMA_HISTOGRAM_CUSTOM_TIMES("Net.CertVerifier_First_Job_Latency", |
398 latency, | 351 latency, |
399 base::TimeDelta::FromMilliseconds(1), | 352 base::TimeDelta::FromMilliseconds(1), |
400 base::TimeDelta::FromMinutes(10), | 353 base::TimeDelta::FromMinutes(10), |
401 100); | 354 100); |
402 } | 355 } |
403 PostAll(verify_result); | |
404 } | 356 } |
405 | 357 |
406 private: | 358 void OnJobCompleted( |
407 void PostAll(const MultiThreadedCertVerifier::CachedResult& verify_result) { | 359 scoped_ptr<MultiThreadedCertVerifier::CachedResult> verify_result) { |
408 std::vector<CertVerifierRequest*> requests; | 360 scoped_ptr<CertVerifierJob> keep_alive = cert_verifier_->RemoveJob(this); |
409 requests_.swap(requests); | |
410 | 361 |
411 for (std::vector<CertVerifierRequest*>::iterator | 362 LogMetrics(*verify_result); |
412 i = requests.begin(); i != requests.end(); i++) { | 363 cert_verifier_->SaveResultToCache(key_, *verify_result); |
413 (*i)->Post(verify_result); | 364 cert_verifier_ = nullptr; |
414 // Post() causes the CertVerifierRequest to delete itself. | 365 |
| 366 // TODO(eroman): If the cert_verifier_ is deleted from within one of the |
| 367 // callbacks, any remaining requests for that job should be cancelled. Right |
| 368 // now they will be called. |
| 369 while (!requests_.empty()) { |
| 370 base::LinkNode<CertVerifierRequest>* request = requests_.head(); |
| 371 request->RemoveFromList(); |
| 372 request->value()->Post(*verify_result); |
415 } | 373 } |
416 } | 374 } |
417 | 375 |
418 void DeleteAllCanceled() { | 376 const MultiThreadedCertVerifier::RequestParams key_; |
419 for (std::vector<CertVerifierRequest*>::iterator | 377 const base::TimeTicks start_time_; |
420 i = requests_.begin(); i != requests_.end(); i++) { | |
421 if ((*i)->canceled()) { | |
422 delete *i; | |
423 } else { | |
424 LOG(DFATAL) << "CertVerifierRequest leaked!"; | |
425 } | |
426 } | |
427 } | |
428 | 378 |
429 const base::TimeTicks start_time_; | 379 RequestList requests_; // Non-owned. |
430 std::vector<CertVerifierRequest*> requests_; | 380 |
431 CertVerifierWorker* worker_; | |
432 const BoundNetLog net_log_; | 381 const BoundNetLog net_log_; |
| 382 MultiThreadedCertVerifier* cert_verifier_; // Non-owned. |
| 383 |
| 384 bool is_first_job_; |
| 385 base::WeakPtrFactory<CertVerifierJob> weak_ptr_factory_; |
433 }; | 386 }; |
434 | 387 |
435 MultiThreadedCertVerifier::MultiThreadedCertVerifier( | 388 MultiThreadedCertVerifier::MultiThreadedCertVerifier( |
436 CertVerifyProc* verify_proc) | 389 CertVerifyProc* verify_proc) |
437 : cache_(kMaxCacheEntries), | 390 : cache_(kMaxCacheEntries), |
438 first_job_(NULL), | |
439 requests_(0), | 391 requests_(0), |
440 cache_hits_(0), | 392 cache_hits_(0), |
441 inflight_joins_(0), | 393 inflight_joins_(0), |
442 verify_proc_(verify_proc), | 394 verify_proc_(verify_proc), |
443 trust_anchor_provider_(NULL) { | 395 trust_anchor_provider_(NULL) { |
444 CertDatabase::GetInstance()->AddObserver(this); | 396 CertDatabase::GetInstance()->AddObserver(this); |
445 } | 397 } |
446 | 398 |
447 MultiThreadedCertVerifier::~MultiThreadedCertVerifier() { | 399 MultiThreadedCertVerifier::~MultiThreadedCertVerifier() { |
448 STLDeleteValues(&inflight_); | 400 STLDeleteElements(&inflight_); |
449 CertDatabase::GetInstance()->RemoveObserver(this); | 401 CertDatabase::GetInstance()->RemoveObserver(this); |
450 } | 402 } |
451 | 403 |
452 void MultiThreadedCertVerifier::SetCertTrustAnchorProvider( | 404 void MultiThreadedCertVerifier::SetCertTrustAnchorProvider( |
453 CertTrustAnchorProvider* trust_anchor_provider) { | 405 CertTrustAnchorProvider* trust_anchor_provider) { |
454 DCHECK(CalledOnValidThread()); | 406 DCHECK(CalledOnValidThread()); |
455 trust_anchor_provider_ = trust_anchor_provider; | 407 trust_anchor_provider_ = trust_anchor_provider; |
456 } | 408 } |
457 | 409 |
458 int MultiThreadedCertVerifier::Verify(X509Certificate* cert, | 410 int MultiThreadedCertVerifier::Verify(X509Certificate* cert, |
459 const std::string& hostname, | 411 const std::string& hostname, |
460 const std::string& ocsp_response, | 412 const std::string& ocsp_response, |
461 int flags, | 413 int flags, |
462 CRLSet* crl_set, | 414 CRLSet* crl_set, |
463 CertVerifyResult* verify_result, | 415 CertVerifyResult* verify_result, |
464 const CompletionCallback& callback, | 416 const CompletionCallback& callback, |
465 RequestHandle* out_req, | 417 scoped_ptr<Request>* out_req, |
466 const BoundNetLog& net_log) { | 418 const BoundNetLog& net_log) { |
| 419 out_req->reset(); |
| 420 |
467 DCHECK(CalledOnValidThread()); | 421 DCHECK(CalledOnValidThread()); |
468 | 422 |
469 if (callback.is_null() || !verify_result || hostname.empty()) { | 423 if (callback.is_null() || !verify_result || hostname.empty()) |
470 *out_req = NULL; | |
471 return ERR_INVALID_ARGUMENT; | 424 return ERR_INVALID_ARGUMENT; |
472 } | |
473 | 425 |
474 requests_++; | 426 requests_++; |
475 | 427 |
476 const CertificateList empty_cert_list; | 428 const CertificateList empty_cert_list; |
477 const CertificateList& additional_trust_anchors = | 429 const CertificateList& additional_trust_anchors = |
478 trust_anchor_provider_ ? | 430 trust_anchor_provider_ ? |
479 trust_anchor_provider_->GetAdditionalTrustAnchors() : empty_cert_list; | 431 trust_anchor_provider_->GetAdditionalTrustAnchors() : empty_cert_list; |
480 | 432 |
481 const RequestParams key(cert->fingerprint(), cert->ca_fingerprint(), hostname, | 433 const RequestParams key(cert->fingerprint(), cert->ca_fingerprint(), hostname, |
482 ocsp_response, flags, additional_trust_anchors); | 434 ocsp_response, flags, additional_trust_anchors); |
483 const CertVerifierCache::value_type* cached_entry = | 435 const CertVerifierCache::value_type* cached_entry = |
484 cache_.Get(key, CacheValidityPeriod(base::Time::Now())); | 436 cache_.Get(key, CacheValidityPeriod(base::Time::Now())); |
485 if (cached_entry) { | 437 if (cached_entry) { |
486 ++cache_hits_; | 438 ++cache_hits_; |
487 *out_req = NULL; | |
488 *verify_result = cached_entry->result; | 439 *verify_result = cached_entry->result; |
489 return cached_entry->error; | 440 return cached_entry->error; |
490 } | 441 } |
491 | 442 |
492 // No cache hit. See if an identical request is currently in flight. | 443 // No cache hit. See if an identical request is currently in flight. |
493 CertVerifierJob* job; | 444 CertVerifierJob* job = FindJob(key); |
494 std::map<RequestParams, CertVerifierJob*>::const_iterator j; | 445 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 | 446 // An identical request is in flight already. We'll just attach our |
498 // callback. | 447 // callback. |
499 inflight_joins_++; | 448 inflight_joins_++; |
500 job = j->second; | |
501 } else { | 449 } else { |
502 // Need to make a new request. | 450 // Need to make a new job. |
503 CertVerifierWorker* worker = new CertVerifierWorker( | 451 scoped_ptr<CertVerifierJob> new_job( |
504 verify_proc_.get(), cert, hostname, ocsp_response, flags, crl_set, | 452 new CertVerifierJob(key, net_log.net_log(), cert, this)); |
505 additional_trust_anchors, this); | 453 |
506 job = new CertVerifierJob( | 454 if (!new_job->Start(verify_proc_, cert, hostname, ocsp_response, flags, |
507 worker, | 455 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. | 456 // TODO(wtc): log to the NetLog. |
514 LOG(ERROR) << "CertVerifierWorker couldn't be started."; | 457 LOG(ERROR) << "CertVerifierWorker couldn't be started."; |
515 return ERR_INSUFFICIENT_RESOURCES; // Just a guess. | 458 return ERR_INSUFFICIENT_RESOURCES; // Just a guess. |
516 } | 459 } |
517 inflight_.insert(std::make_pair(key, job)); | 460 |
518 if (requests_ == 1) { | 461 job = new_job.release(); |
519 // Cleared in HandleResult. | 462 inflight_.insert(job); |
520 first_job_ = job; | 463 |
521 } | 464 if (requests_ == 1) |
| 465 job->set_is_first_job(true); |
522 } | 466 } |
523 | 467 |
524 CertVerifierRequest* request = | 468 scoped_ptr<CertVerifierRequest> request = |
525 new CertVerifierRequest(callback, verify_result, net_log); | 469 job->CreateRequest(callback, verify_result, net_log); |
526 job->AddRequest(request); | 470 *out_req = request.Pass(); |
527 *out_req = request; | |
528 return ERR_IO_PENDING; | 471 return ERR_IO_PENDING; |
529 } | 472 } |
530 | 473 |
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() { | 474 bool MultiThreadedCertVerifier::SupportsOCSPStapling() { |
538 return verify_proc_->SupportsOCSPStapling(); | 475 return verify_proc_->SupportsOCSPStapling(); |
539 } | 476 } |
540 | 477 |
541 MultiThreadedCertVerifier::RequestParams::RequestParams( | 478 MultiThreadedCertVerifier::RequestParams::RequestParams( |
542 const SHA1HashValue& cert_fingerprint_arg, | 479 const SHA1HashValue& cert_fingerprint_arg, |
543 const SHA1HashValue& ca_fingerprint_arg, | 480 const SHA1HashValue& ca_fingerprint_arg, |
544 const std::string& hostname_arg, | 481 const std::string& hostname_arg, |
545 const std::string& ocsp_response_arg, | 482 const std::string& ocsp_response_arg, |
546 int flags_arg, | 483 int flags_arg, |
(...skipping 20 matching lines...) Expand all Loading... |
567 // are faster than memory and string comparisons. | 504 // are faster than memory and string comparisons. |
568 if (flags != other.flags) | 505 if (flags != other.flags) |
569 return flags < other.flags; | 506 return flags < other.flags; |
570 if (hostname != other.hostname) | 507 if (hostname != other.hostname) |
571 return hostname < other.hostname; | 508 return hostname < other.hostname; |
572 return std::lexicographical_compare( | 509 return std::lexicographical_compare( |
573 hash_values.begin(), hash_values.end(), other.hash_values.begin(), | 510 hash_values.begin(), hash_values.end(), other.hash_values.begin(), |
574 other.hash_values.end(), SHA1HashValueLessThan()); | 511 other.hash_values.end(), SHA1HashValueLessThan()); |
575 } | 512 } |
576 | 513 |
577 // HandleResult is called by CertVerifierWorker on the origin message loop. | 514 bool MultiThreadedCertVerifier::JobComparator::operator()( |
578 // It deletes CertVerifierJob. | 515 const CertVerifierJob* job1, |
579 void MultiThreadedCertVerifier::HandleResult( | 516 const CertVerifierJob* job2) const { |
580 X509Certificate* cert, | 517 return job1->key() < job2->key(); |
581 const std::string& hostname, | 518 } |
582 const std::string& ocsp_response, | 519 |
583 int flags, | 520 void MultiThreadedCertVerifier::SaveResultToCache(const RequestParams& key, |
584 const CertificateList& additional_trust_anchors, | 521 const CachedResult& result) { |
585 int error, | |
586 const CertVerifyResult& verify_result) { | |
587 DCHECK(CalledOnValidThread()); | 522 DCHECK(CalledOnValidThread()); |
588 | 523 |
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(); | 524 base::Time now = base::Time::Now(); |
596 cache_.Put( | 525 cache_.Put( |
597 key, cached_result, CacheValidityPeriod(now), | 526 key, result, CacheValidityPeriod(now), |
598 CacheValidityPeriod(now, now + base::TimeDelta::FromSeconds(kTTLSecs))); | 527 CacheValidityPeriod(now, now + base::TimeDelta::FromSeconds(kTTLSecs))); |
| 528 } |
599 | 529 |
600 std::map<RequestParams, CertVerifierJob*>::iterator j; | 530 scoped_ptr<CertVerifierJob> MultiThreadedCertVerifier::RemoveJob( |
601 j = inflight_.find(key); | 531 CertVerifierJob* job) { |
602 if (j == inflight_.end()) { | 532 DCHECK(CalledOnValidThread()); |
603 NOTREACHED(); | 533 bool erased_job = inflight_.erase(job) == 1; |
604 return; | 534 DCHECK(erased_job); |
605 } | 535 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 } | 536 } |
617 | 537 |
618 void MultiThreadedCertVerifier::OnCACertChanged( | 538 void MultiThreadedCertVerifier::OnCACertChanged( |
619 const X509Certificate* cert) { | 539 const X509Certificate* cert) { |
620 DCHECK(CalledOnValidThread()); | 540 DCHECK(CalledOnValidThread()); |
621 | 541 |
622 ClearCache(); | 542 ClearCache(); |
623 } | 543 } |
624 | 544 |
| 545 struct MultiThreadedCertVerifier::JobToRequestParamsComparator { |
| 546 bool operator()(const CertVerifierJob* job, |
| 547 const MultiThreadedCertVerifier::RequestParams& value) const { |
| 548 return job->key() < value; |
| 549 } |
| 550 }; |
| 551 |
| 552 CertVerifierJob* MultiThreadedCertVerifier::FindJob(const RequestParams& key) { |
| 553 DCHECK(CalledOnValidThread()); |
| 554 |
| 555 // The JobSet is kept in sorted order so items can be found using binary |
| 556 // search. |
| 557 auto it = std::lower_bound(inflight_.begin(), inflight_.end(), key, |
| 558 JobToRequestParamsComparator()); |
| 559 if (it != inflight_.end() && !(key < (*it)->key())) |
| 560 return *it; |
| 561 return nullptr; |
| 562 } |
| 563 |
625 } // namespace net | 564 } // namespace net |
626 | 565 |
OLD | NEW |