/* Provide SSL/TLS functions to ESP32 with Arduino IDE
 * by Evandro Copercini - 2017 - Apache 2.0 License
 */

#ifndef ARD_SSL_H
#define ARD_SSL_H
#include "mbedtls/platform.h"
#include "mbedtls/net_sockets.h"
#include "mbedtls/debug.h"
#include "mbedtls/ssl.h"
#include "mbedtls/error.h"
#include "mbedtls/version.h"

#if MBEDTLS_VERSION_MAJOR < 4
#include "mbedtls/entropy.h"
#include "mbedtls/ctr_drbg.h"
#endif

typedef esp_err_t (*crt_bundle_attach_cb)(void *conf);

typedef struct sslclient_context {
  int socket;
  mbedtls_ssl_context ssl_ctx;
  mbedtls_ssl_config ssl_conf;

#if MBEDTLS_VERSION_MAJOR < 4
  mbedtls_ctr_drbg_context drbg_ctx;
  mbedtls_entropy_context entropy_ctx;
#endif

  mbedtls_x509_crt ca_cert;
  mbedtls_x509_crt client_cert;
  mbedtls_pk_context client_key;

  crt_bundle_attach_cb bundle_attach_cb;

  unsigned long socket_timeout;
  unsigned long handshake_timeout;

  int last_error;
  int peek_buf;

} sslclient_context;

void ssl_init(sslclient_context *ssl_client);
int start_ssl_client(
  sslclient_context *ssl_client, const IPAddress &ip, uint32_t port, const char *hostname, int timeout, const char *rootCABuff, bool useRootCABundle,
  const char *cli_cert, const char *cli_key, const char *pskIdent, const char *psKey, bool insecure, const char **alpn_protos
);
void attach_ssl_certificate_bundle(sslclient_context *ssl_client, bool att);
int ssl_starttls_handshake(sslclient_context *ssl_client);
void stop_ssl_socket(sslclient_context *ssl_client);
int data_to_read(sslclient_context *ssl_client);
int send_ssl_data(sslclient_context *ssl_client, const uint8_t *data, size_t len);
int get_ssl_receive(sslclient_context *ssl_client, uint8_t *data, int length);
int send_net_data(sslclient_context *ssl_client, const uint8_t *data, size_t len);
int get_net_receive(sslclient_context *ssl_client, uint8_t *data, int length);
int peek_net_receive(sslclient_context *ssl_client, int timeout);
bool verify_ssl_fingerprint(sslclient_context *ssl_client, const char *fp, const char *domain_name);
bool verify_ssl_dn(sslclient_context *ssl_client, const char *domain_name);
bool get_peer_fingerprint(sslclient_context *ssl_client, uint8_t sha256[32]);
#endif
