1 /*
2  *  Copyright 2018 The WebRTC Project Authors. All rights reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef RTC_BASE_OPENSSL_SESSION_CACHE_H_
12 #define RTC_BASE_OPENSSL_SESSION_CACHE_H_
13 
14 #include <openssl/ossl_typ.h>
15 
16 #include <map>
17 #include <string>
18 
19 #include "rtc_base/constructor_magic.h"
20 #include "rtc_base/ssl_stream_adapter.h"
21 
22 #ifndef OPENSSL_IS_BORINGSSL
23 typedef struct ssl_session_st SSL_SESSION;
24 #endif
25 
26 namespace rtc {
27 
28 // The OpenSSLSessionCache maps hostnames to SSL_SESSIONS. This cache is
29 // owned by the OpenSSLAdapterFactory and is passed down to each OpenSSLAdapter
30 // created with the factory.
31 class OpenSSLSessionCache final {
32  public:
33   // Creates a new OpenSSLSessionCache using the provided the SSL_CTX and
34   // the ssl_mode. The SSL_CTX will be up_refed. ssl_ctx cannot be nullptr,
35   // the constructor immediately dchecks this.
36   OpenSSLSessionCache(SSLMode ssl_mode, SSL_CTX* ssl_ctx);
37   // Frees the cached SSL_SESSIONS and then frees the SSL_CTX.
38   ~OpenSSLSessionCache();
39   // Looks up a session by hostname. The returned SSL_SESSION is not up_refed.
40   SSL_SESSION* LookupSession(const std::string& hostname) const;
41   // Adds a session to the cache, and up_refs it. Any existing session with the
42   // same hostname is replaced.
43   void AddSession(const std::string& hostname, SSL_SESSION* session);
44   // Returns the true underlying SSL Context that holds these cached sessions.
45   SSL_CTX* GetSSLContext() const;
46   // The SSL Mode tht the OpenSSLSessionCache was constructed with. This cannot
47   // be changed after launch.
48   SSLMode GetSSLMode() const;
49 
50  private:
51   // Holds the SSL Mode that the OpenSSLCache was initialized with. This is
52   // immutable after creation and cannot change.
53   const SSLMode ssl_mode_;
54   /// SSL Context for all shared cached sessions. This SSL_CTX is initialized
55   //  with SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT); Meaning
56   //  all client sessions will be added to the cache internal to the context.
57   SSL_CTX* ssl_ctx_ = nullptr;
58   // Map of hostnames to SSL_SESSIONs; holds references to the SSL_SESSIONs,
59   // which are cleaned up when the factory is destroyed.
60   // TODO(juberti): Add LRU eviction to keep the cache from growing forever.
61   std::map<std::string, SSL_SESSION*> sessions_;
62   // The cache should never be copied or assigned directly.
63   RTC_DISALLOW_COPY_AND_ASSIGN(OpenSSLSessionCache);
64 };
65 
66 }  // namespace rtc
67 
68 #endif  // RTC_BASE_OPENSSL_SESSION_CACHE_H_
69