// SPDX-License-Identifier: GPL-2.0 OR LGPL-2.1 OR CDDL-1.0
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or https://opensource.org/licenses/CDDL-1.0.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */

/* Copyright (c) 2024-2026 Chilledheart  */

#ifndef H_NET_SSL_CLIENT_SESSION_CACHE
#define H_NET_SSL_CLIENT_SESSION_CACHE

#include <stddef.h>
#include <time.h>

#include <memory>
#include <optional>
#include <string>

#ifdef TBB_PREVIEW_CONCURRENT_LRU_CACHE
#include "oneapi/tbb/concurrent_lru_cache.h"
#else
#include "base/containers/lru_cache.h"
#endif
#include "base/memory/raw_ptr.h"
#include "net/asio.hpp"
#include "third_party/boringssl/src/include/openssl/base.h"

namespace net {

class SSLClientSessionCache {
 public:
  struct Config {
    // The maximum number of entries in the cache.
    size_t max_entries = 1024;
    // The number of calls to Lookup before a new check for expired sessions.
    size_t expiration_check_count = 256;
  };

  struct Key {
    Key();
    Key(const Key& other);
    Key(Key&& other);
    ~Key();
    Key& operator=(const Key& other);
    Key& operator=(Key&& other);

    bool operator==(const Key& other) const;
    bool operator<(const Key& other) const;

    std::pair<std::string, int> server;
    std::optional<asio::ip::address> dest_ip_addr;
  };

  explicit SSLClientSessionCache(const Config& config);

  SSLClientSessionCache(const SSLClientSessionCache&) = delete;
  SSLClientSessionCache& operator=(const SSLClientSessionCache&) = delete;

  ~SSLClientSessionCache();

  // Returns true if |entry| is expired as of |now|.
  static bool IsExpired(SSL_SESSION* session, time_t now);

#ifndef TBB_PREVIEW_CONCURRENT_LRU_CACHE
  size_t size() const;
#endif

  // Returns the session associated with |cache_key| and moves it to the front
  // of the MRU list. Returns nullptr if there is none.
  bssl::UniquePtr<SSL_SESSION> Lookup(const Key& cache_key);

  // Inserts |session| into the cache at |cache_key|. If there is an existing
  // one, it is released. Every |expiration_check_count| calls, the cache is
  // checked for stale entries.
  void Insert(const Key& cache_key, bssl::UniquePtr<SSL_SESSION> session);

  // Clears early data support for all current sessions associated with
  // |cache_key|. This may be used after a 0-RTT reject to avoid unnecessarily
  // offering 0-RTT data on retries. See https://crbug.com/1066623.
  void ClearEarlyData(const Key& cache_key);

  // Removes all entries from the cache.
  void Flush();

 private:
  struct Entry {
    Entry();
    Entry(Entry&&);
    Entry& operator=(Entry&&);
    ~Entry();

    // Adds a new session onto this entry, dropping the oldest one if two are
    // already stored.
    void Push(bssl::UniquePtr<SSL_SESSION> session);

    // Retrieves the latest session from the entry, removing it if its
    // single-use.
    bssl::UniquePtr<SSL_SESSION> Pop();

    // Removes any expired sessions, returning true if this entry can be
    // deleted.
    bool ExpireSessions(time_t now);

    bssl::UniquePtr<SSL_SESSION> sessions[2];
  };

#ifndef TBB_PREVIEW_CONCURRENT_LRU_CACHE
  // Removes all expired sessions from the cache.
  void FlushExpiredSessions();
#endif

#ifdef TBB_PREVIEW_CONCURRENT_LRU_CACHE
  static std::shared_ptr<Entry> Construct(Key key);
#endif

#if 0
  // Clear cache on low memory notifications callback.
  void OnMemoryPressure(
      base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level);
#endif

  Config config_;
#ifdef TBB_PREVIEW_CONCURRENT_LRU_CACHE
  typedef tbb::concurrent_lru_cache<Key, std::shared_ptr<Entry>> CacheType;
#else
  typedef gurl_base::LRUCache<Key, Entry> CacheType;
#endif
  CacheType cache_;
#ifndef TBB_PREVIEW_CONCURRENT_LRU_CACHE
  size_t lookups_since_flush_ = 0;
#endif
  // std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_;
};

}  // namespace net

#endif  // H_NET_SSL_CLIENT_SESSION_CACHE
