xref: /aosp_15_r20/external/cronet/net/ssl/ssl_client_auth_cache.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2011 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/ssl/ssl_client_auth_cache.h"
6 
7 #include "base/check.h"
8 #include "net/cert/x509_certificate.h"
9 #include "net/ssl/ssl_private_key.h"
10 
11 namespace net {
12 
13 SSLClientAuthCache::SSLClientAuthCache() = default;
14 
15 SSLClientAuthCache::~SSLClientAuthCache() = default;
16 
Lookup(const HostPortPair & server,scoped_refptr<X509Certificate> * certificate,scoped_refptr<SSLPrivateKey> * private_key)17 bool SSLClientAuthCache::Lookup(const HostPortPair& server,
18                                 scoped_refptr<X509Certificate>* certificate,
19                                 scoped_refptr<SSLPrivateKey>* private_key) {
20   DCHECK(certificate);
21 
22   auto iter = cache_.find(server);
23   if (iter == cache_.end())
24     return false;
25 
26   *certificate = iter->second.first;
27   *private_key = iter->second.second;
28   return true;
29 }
30 
Add(const HostPortPair & server,scoped_refptr<X509Certificate> certificate,scoped_refptr<SSLPrivateKey> private_key)31 void SSLClientAuthCache::Add(const HostPortPair& server,
32                              scoped_refptr<X509Certificate> certificate,
33                              scoped_refptr<SSLPrivateKey> private_key) {
34   cache_[server] = std::pair(std::move(certificate), std::move(private_key));
35 
36   // TODO(wtc): enforce a maximum number of entries.
37 }
38 
Remove(const HostPortPair & server)39 bool SSLClientAuthCache::Remove(const HostPortPair& server) {
40   return cache_.erase(server);
41 }
42 
Clear()43 void SSLClientAuthCache::Clear() {
44   cache_.clear();
45 }
46 
GetCachedServers() const47 base::flat_set<HostPortPair> SSLClientAuthCache::GetCachedServers() const {
48   // TODO(mattm): If views become permitted by Chromium style maybe we could
49   // avoid the intermediate vector by using:
50   // auto keys = std::views::keys(m);
51   // base::flat_set<HostPortPair>(base::sorted_unique, keys.begin(),
52   //                              keys.end());
53 
54   // Use the flat_set underlying container type (currently a std::vector), so we
55   // can move the keys into the set instead of copying them.
56   base::flat_set<HostPortPair>::container_type keys;
57   keys.reserve(cache_.size());
58   for (const auto& [key, _] : cache_) {
59     keys.push_back(key);
60   }
61   // `cache_` is a std::map, so the keys are already sorted.
62   return base::flat_set<HostPortPair>(base::sorted_unique, std::move(keys));
63 }
64 
65 }  // namespace net
66