/** @file

  TLSSNISupport implements common methods and members to
  support protocols for Server Name Indication

  @section license License

  Licensed to the Apache Software Foundation (ASF) under one
  or more contributor license agreements.  See the NOTICE file
  distributed with this work for additional information
  regarding copyright ownership.  The ASF licenses this file
  to you under the Apache License, Version 2.0 (the
  "License"); you may not use this file except in compliance
  with the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */
#pragma once

#include "tscore/ink_config.h"
#include "tscore/ink_memory.h"

#include <netinet/in.h>
#include <openssl/ssl.h>

#include <string_view>
#include <memory>
#include <optional>

class TLSSNISupport
{
public:
  virtual ~TLSSNISupport() = default;

  static void           initialize();
  static TLSSNISupport *getInstance(SSL *ssl);
  static void           bind(SSL *ssl, TLSSNISupport *snis);
  static void           unbind(SSL *ssl);

  int perform_sni_action(SSL &ssl);
  // Callback functions for OpenSSL libraries
#if HAVE_SSL_CTX_SET_CLIENT_HELLO_CB
  void on_client_hello(SSL *ssl, int *al, void *arg);
#elif HAVE_SSL_CTX_SET_SELECT_CERTIFICATE_CB
  void on_client_hello(const SSL_CLIENT_HELLO *client_hello);
#endif
  void on_servername(SSL *ssl, int *al, void *arg);

  const char *get_sni_server_name() const;
  bool        would_have_actions_for(const char *servername, IpEndpoint remote, int &enforcement_policy);

  struct HintsFromSNI {
    std::optional<uint32_t>         http2_buffer_water_mark;
    std::optional<uint32_t>         server_max_early_data;
    std::optional<uint32_t>         http2_initial_window_size_in;
    std::optional<int32_t>          http2_max_settings_frames_per_minute;
    std::optional<int32_t>          http2_max_ping_frames_per_minute;
    std::optional<int32_t>          http2_max_priority_frames_per_minute;
    std::optional<int32_t>          http2_max_rst_stream_frames_per_minute;
    std::optional<int32_t>          http2_max_continuation_frames_per_minute;
    std::optional<std::string_view> outbound_sni_policy;
  } hints_from_sni;

protected:
  virtual void _fire_ssl_servername_event() = 0;

  virtual in_port_t _get_local_port() = 0;

  void _clear();

private:
  static int _ex_data_index;

  // Null-terminated string, or nullptr if there is no SNI server name.
  std::unique_ptr<char[]> _sni_server_name;

  void _set_sni_server_name(std::string_view name);
};
