1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef _DNS_DNSTLSSESSIONCACHE_H
18 #define _DNS_DNSTLSSESSIONCACHE_H
19 
20 #include <deque>
21 #include <mutex>
22 
23 #include <openssl/ssl.h>
24 
25 #include <android-base/thread_annotations.h>
26 
27 namespace android {
28 namespace net {
29 
30 // Cache of recently seen SSL_SESSIONs.  This is used to support session tickets.
31 // This class is thread-safe.
32 class DnsTlsSessionCache {
33   public:
34     // Prepare SSL objects to use this session cache.  These methods must be called
35     // before making use of either object.
36     void prepareSslContext(SSL_CTX* _Nonnull ssl_ctx);
37     bool prepareSsl(SSL* _Nonnull ssl);
38 
39     // Get the most recently discovered session.  For TLS 1.3 compatibility and
40     // maximum privacy, each session will only be returned once, so the caller
41     // gains ownership of the session.  (Here and throughout,
42     // bssl::UniquePtr<SSL_SESSION> is actually serving as a reference counted
43     // pointer.)
44     bssl::UniquePtr<SSL_SESSION> getSession() EXCLUDES(mLock);
45 
46   private:
47     static constexpr size_t kMaxSize = 5;
48     static int newSessionCallback(SSL* _Nullable ssl, SSL_SESSION* _Nullable session);
49 
50     std::mutex mLock;
51     void recordSession(SSL_SESSION* _Nullable session) EXCLUDES(mLock);
52 
53     // Queue of sessions, from least recently added to most recently.
54     std::deque<bssl::UniquePtr<SSL_SESSION>> mSessions GUARDED_BY(mLock);
55 };
56 
57 }  // end of namespace net
58 }  // end of namespace android
59 
60 #endif  // _DNS_DNSTLSSESSIONCACHE_H
61