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 <mutex>
21#include <deque>
22
23#include <openssl/ssl.h>
24
25#include <android-base/thread_annotations.h>
26#include <android-base/unique_fd.h>
27
28#include "dns/DnsTlsServer.h"
29
30namespace android {
31namespace net {
32
33// Cache of recently seen SSL_SESSIONs.  This is used to support session tickets.
34// This class is thread-safe.
35class DnsTlsSessionCache {
36public:
37    // Prepare SSL objects to use this session cache.  These methods must be called
38    // before making use of either object.
39    void prepareSslContext(SSL_CTX* _Nonnull ssl_ctx);
40    bool prepareSsl(SSL* _Nonnull ssl);
41
42    // Get the most recently discovered session.  For TLS 1.3 compatibility and
43    // maximum privacy, each session will only be returned once, so the caller
44    // gains ownership of the session.  (Here and throughout,
45    // bssl::UniquePtr<SSL_SESSION> is actually serving as a reference counted
46    // pointer.)
47    bssl::UniquePtr<SSL_SESSION> getSession() EXCLUDES(mLock);
48
49private:
50    static constexpr size_t kMaxSize = 5;
51    static int newSessionCallback(SSL* _Nullable ssl, SSL_SESSION* _Nullable session);
52
53    std::mutex mLock;
54    void recordSession(SSL_SESSION* _Nullable session) EXCLUDES(mLock);
55
56    // Queue of sessions, from least recently added to most recently.
57    std::deque<bssl::UniquePtr<SSL_SESSION>> mSessions GUARDED_BY(mLock);
58};
59
60}  // end of namespace net
61}  // end of namespace android
62
63#endif  // _DNS_DNSTLSSESSIONCACHE_H
64