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
3 // found in the LICENSE file.
5 #include "net/ssl/ssl_client_session_cache_openssl.h"
9 #include "base/time/clock.h"
10 #include "base/time/default_clock.h"
14 SSLClientSessionCacheOpenSSL::SSLClientSessionCacheOpenSSL(const Config
& config
)
15 : clock_(new base::DefaultClock
),
17 cache_(config
.max_entries
),
18 lookups_since_flush_(0) {
21 SSLClientSessionCacheOpenSSL::~SSLClientSessionCacheOpenSSL() {
25 size_t SSLClientSessionCacheOpenSSL::size() const {
29 SSL_SESSION
* SSLClientSessionCacheOpenSSL::Lookup(
30 const std::string
& cache_key
) {
31 base::AutoLock
lock(lock_
);
33 // Expire stale sessions.
34 lookups_since_flush_
++;
35 if (lookups_since_flush_
>= config_
.expiration_check_count
) {
36 lookups_since_flush_
= 0;
37 FlushExpiredSessions();
40 CacheEntryMap::iterator iter
= cache_
.Get(cache_key
);
41 if (iter
== cache_
.end())
43 if (IsExpired(iter
->second
, clock_
->Now())) {
47 return iter
->second
->session
.get();
50 void SSLClientSessionCacheOpenSSL::Insert(const std::string
& cache_key
,
51 SSL_SESSION
* session
) {
52 base::AutoLock
lock(lock_
);
55 CacheEntry
* entry
= new CacheEntry
;
56 entry
->session
.reset(SSL_SESSION_up_ref(session
));
57 entry
->creation_time
= clock_
->Now();
60 cache_
.Put(cache_key
, entry
);
63 void SSLClientSessionCacheOpenSSL::Flush() {
64 base::AutoLock
lock(lock_
);
69 void SSLClientSessionCacheOpenSSL::SetClockForTesting(
70 scoped_ptr
<base::Clock
> clock
) {
71 clock_
= clock
.Pass();
74 SSLClientSessionCacheOpenSSL::CacheEntry::CacheEntry() {
77 SSLClientSessionCacheOpenSSL::CacheEntry::~CacheEntry() {
80 bool SSLClientSessionCacheOpenSSL::IsExpired(
81 SSLClientSessionCacheOpenSSL::CacheEntry
* entry
,
82 const base::Time
& now
) {
83 return now
< entry
->creation_time
||
84 entry
->creation_time
+ config_
.timeout
< now
;
87 void SSLClientSessionCacheOpenSSL::FlushExpiredSessions() {
88 base::Time now
= clock_
->Now();
89 CacheEntryMap::iterator iter
= cache_
.begin();
90 while (iter
!= cache_
.end()) {
91 if (IsExpired(iter
->second
, now
)) {
92 iter
= cache_
.Erase(iter
);