# ESP-TLS

[中文]

## Overview

The ESP-TLS component provides a simplified API interface for accessing the commonly used TLS functions. It supports common scenarios like CA certification validation, SNI, ALPN negotiation, and non-blocking connection among others. All the configurations can be specified in the `esp_tls_cfg_t` data structure. Once done, TLS communication can be conducted using the following APIs:

> - `esp_tls_init()`: for initializing the TLS connection handle.

> - `esp_tls_conn_new_sync()`: for opening a new blocking TLS connection.

> - `esp_tls_conn_new_async()`: for opening a new non-blocking TLS connection.

> - `esp_tls_conn_read()`: for reading from the connection.

> - `esp_tls_conn_write()`: for writing into the connection.

> - `esp_tls_conn_destroy()`: for freeing up the connection.

Any application layer protocol like HTTP1, HTTP2, etc can be executed on top of this layer.

## Application Example

Simple HTTPS example that uses ESP-TLS to establish a secure socket connection: protocols/https_request.

## Tree Structure for ESP-TLS Component

    ├── esp_tls.c
    ├── esp_tls.h
    ├── esp_tls_mbedtls.c
    ├── esp_tls_custom_stack.c
    └── private_include
        ├── esp_tls_mbedtls.h
        └── esp_tls_custom_stack.h

The ESP-TLS component has a file esp-tls/esp_tls.h which contains the public API headers for the component. Internally, the ESP-TLS component operates using MbedTLS as the default SSL/TLS library, or a custom TLS stack registered via the `esp_tls_register_stack()` API. APIs specific to MbedTLS are present in esp-tls/private_include/esp_tls_mbedtls.h and APIs for custom stack registration are present in esp-tls/esp_tls_custom_stack.h.

## TLS Server Verification

ESP-TLS provides multiple options for TLS server verification on the client side. The ESP-TLS client can verify the server by validating the peer's server certificate or with the help of pre-shared keys. The user should select only one of the following options in the `esp_tls_cfg_t` structure for TLS server verification. If no option is selected, the client will return a fatal error by default during the TLS connection setup.

> - cacert_buf and cacert_bytes: The CA certificate can be provided in a buffer to the `esp_tls_cfg_t` structure. The ESP-TLS uses the CA certificate present in the buffer to verify the server. The following variables in the `esp_tls_cfg_t` structure must be set.

>   > - `cacert_buf` - pointer to the buffer which contains the CA certification.

>   > - `cacert_bytes` - the size of the CA certificate in bytes.

> - use_global_ca_store: The `global_ca_store` can be initialized and set at once. Then it can be used to verify the server for all the ESP-TLS connections which have set `use_global_ca_store = true` in their respective `esp_tls_cfg_t` structure. See the API Reference section below for information regarding different APIs used for initializing and setting up the `global_ca_store`.

> - crt_bundle_attach: The ESP x509 Certificate Bundle API provides an easy way to include a bundle of custom x509 root certificates for TLS server verification. More details can be found at ESP x509 Certificate Bundle.

> - psk_hint_key: To use pre-shared keys for server verification, CONFIG_ESP_TLS_PSK_VERIFICATION should be enabled in the ESP-TLS menuconfig. Then the pointer to the PSK hint and key should be provided to the `esp_tls_cfg_t` structure. The ESP-TLS will use the PSK for server verification only when no other option regarding server verification is selected.

> - skip server verification: This is an insecure option provided in the ESP-TLS for testing purposes. The option can be set by enabling CONFIG_ESP_TLS_INSECURE and CONFIG_ESP_TLS_SKIP_SERVER_CERT_VERIFY in the ESP-TLS menuconfig. When this option is enabled the ESP-TLS will skip server verification by default when no other options for server verification are selected in the `esp_tls_cfg_t` structure.

>   Warning

>   If this option is enabled, there is a risk of establishing a TLS connection with a server that has a fake identity, unless the server certificate is provided through the API or other mechanisms like `ca_store`.

## SNI (Server Name Indication)

SNI is an extension to the TLS protocol that allows the client to specify the hostname it is connecting to during the TLS handshake. This is required when connecting to servers that host multiple domains on the same IP address.

How to ensure SNI works properly:

- SNI is enabled by default in ESP-TLS when using HTTPS connections.

- To explicitly set the SNI hostname, use the `common_name` field in `esp_tls_cfg_t`. This ensures that the correct hostname is sent to the server during the handshake.

- The value of `common_name` must match the server certificate's CN (Common Name).

- The `skip_common_name` field should be set to `false` to ensure the server certificate is properly validated against the hostname. This is required for SNI to function correctly.

Example:

    esp_tls_cfg_t cfg = {
        .cacert_buf = ...,
        .cacert_bytes = ...,
        .common_name = "example.com", // SNI hostname
        .skip_common_name = false,    // Ensure certificate is validated
    };

## ESP-TLS Server Cert Selection Hook

The ESP-TLS component provides an option to set the server certification selection hook when using the MbedTLS stack. This provides an ability to configure and use a certificate selection callback during server handshake. The callback helps to select a certificate to present to the client based on the TLS extensions supplied in the client hello message, such as ALPN and SNI. To enable this feature, please enable CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK in the ESP-TLS menuconfig.

The certificate selection callback can be configured in the `esp_tls_cfg_t` structure as follows:

    int cert_selection_callback(mbedtls_ssl_context *ssl)
    {
        /* Code that the callback should execute */
        return 0;
    }

    esp_tls_cfg_t cfg = {
        cert_select_cb = cert_section_callback,
    };

## Custom TLS Stack Support

The ESP-TLS component supports registering custom TLS stack implementations via the `esp_tls_register_stack()` API. This allows external components to provide their own TLS stack implementation by implementing the `esp_tls_stack_ops_t` interface. Once registered, all TLS connections created after the registration will use the custom stack.

Note

As the custom stack implementation is internal to ESP-TLS, switching to a custom stack will not change ESP-TLS specific code for a project.

## How to Use Custom TLS Stack with ESP-IDF

To use a custom TLS stack in your project, follow these steps:

1. Enable the custom stack option `CONFIG_ESP_TLS_CUSTOM_STACK` (Component config > ESP-TLS > SSL/TLS Library > Custom TLS stack) in menuconfig.

2. Implement all required functions defined in the `esp_tls_stack_ops_t` structure. The required functions are:

   - `create_ssl_handle` - Initialize TLS/SSL context for a new connection

   - `handshake` - Perform TLS handshake

   - `read` - Read decrypted data from TLS connection

   - `write` - Write and encrypt data to TLS connection

   - `conn_delete` - Clean up TLS connection and free resources

   - `net_init` - Initialize network context

   - `get_ssl_context` - Get stack-specific SSL context

   - `get_bytes_avail` - Get bytes available for reading

   - `init_global_ca_store` - Initialize global CA store

   - `set_global_ca_store` - Load CA certificates into global store

   - `get_global_ca_store` - Get global CA store

   - `free_global_ca_store` - Free global CA store

   - `get_ciphersuites_list` - Get list of supported ciphersuites

   Optional functions (can be NULL if not supported):

   - `get_client_session` - Get client session ticket (if CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS enabled)

   - `free_client_session` - Free client session (if CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS enabled)

   - `server_session_ticket_ctx_init` - Initialize server session ticket context (if CONFIG_ESP_TLS_SERVER_SESSION_TICKETS enabled)

   - `server_session_ticket_ctx_free` - Free server session ticket context (if CONFIG_ESP_TLS_SERVER_SESSION_TICKETS enabled)

   - `server_session_create` - Create server session (server-side, can be NULL if server_session_init is provided)

   - `server_session_init` - Initialize server session (server-side, can be NULL if server_session_create is provided)

   - `server_session_continue_async` - Continue async server handshake (server-side, can be NULL if server_session_create is provided)

   - `server_session_delete` - Delete server session (server-side, can be NULL, conn_delete will be used)

3. Create a static/global structure containing your function implementations:

       #include "esp_tls_custom_stack.h"

       static const esp_tls_stack_ops_t my_tls_ops = {
           .version = ESP_TLS_STACK_OPS_VERSION,
           .create_ssl_handle = my_create_ssl_handle,
           .handshake = my_handshake,
           .read = my_read,
           .write = my_write,
           .conn_delete = my_conn_delete,
           .net_init = my_net_init,
           .get_ssl_context = my_get_ssl_context,
           .get_bytes_avail = my_get_bytes_avail,
           .init_global_ca_store = my_init_global_ca_store,
           .set_global_ca_store = my_set_global_ca_store,
           .get_global_ca_store = my_get_global_ca_store,
           .free_global_ca_store = my_free_global_ca_store,
           .get_ciphersuites_list = my_get_ciphersuites_list,
           // Optional functions can be NULL if not supported
           .get_client_session = NULL,
           .free_client_session = NULL,
           .server_session_ticket_ctx_init = NULL,
           .server_session_ticket_ctx_free = NULL,
           .server_session_create = NULL,
           .server_session_init = NULL,
           .server_session_continue_async = NULL,
           .server_session_delete = NULL,
       };

4. Register your custom stack before creating any TLS connections:

       void app_main(void) {
           // The second parameter is user context passed to global callbacks
           // (init_global_ca_store, set_global_ca_store, etc.)
           // Use NULL if not needed, or pass a pointer for C++ implementations
           esp_err_t ret = esp_tls_register_stack(&my_tls_ops, NULL);
           if (ret != ESP_OK) {
               ESP_LOGE("APP", "Failed to register TLS stack: %s", esp_err_to_name(ret));
               return;
           }

           // Now all TLS connections will use your custom stack
           // ... create TLS connections as usual using esp_tls_conn_new(), etc. ...
       }

Important

- The custom stack must be registered before creating any TLS connections. Calling `esp_tls_register_stack()` after TLS connections have been created will not affect existing connections.

- The `esp_tls_stack_ops_t` structure must point to a static/global structure (not on the stack) as it's stored by reference.

- Your implementation should store stack-specific context data in the `priv_ctx` and `priv_ssl` fields of the `esp_tls_t` structure.

- All required function pointers must be non-NULL. Optional functions can be NULL if not supported.

- The registration function can only be called once. Subsequent calls will return `ESP_ERR_INVALID_STATE`.

- For detailed function signatures and requirements, see esp-tls/esp_tls_custom_stack.h.

## ATECC608A (Secure Element) with ESP-TLS

ESP-TLS provides support for using ATECC608A cryptoauth chip with ESP32 series of SoCs. The use of ATECC608A is supported only when ESP-TLS is used with MbedTLS as its underlying SSL/TLS stack. ESP-TLS uses MbedTLS as its underlying TLS/SSL stack by default unless changed manually.

Note

ATECC608A chip interfaced to ESP32 series must be already configured. For details, please refer to esp_cryptoauth_utility.

To enable the secure element support, and use it in your project for TLS connection, you have to follow the below steps:

1. Add esp-cryptoauthlib in your project, for details please refer how to use esp-cryptoauthlib with ESP-IDF.

2. Enable the menuconfig option CONFIG_ESP_TLS_USE_SECURE_ELEMENT:

       menuconfig > Component config > ESP-TLS > Use Secure Element (ATECC608A) with ESP-TLS

3. Select type of ATECC608A chip with following option:

       menuconfig > Component config > esp-cryptoauthlib > Choose Type of ATECC608A chip

   To know more about different types of ATECC608A chips and how to obtain the type of ATECC608A connected to your ESP module, please visit ATECC608A chip type.

4. Enable the use of ATECC608A in ESP-TLS by providing the following config option in `esp_tls_cfg_t`:

       esp_tls_cfg_t cfg = {
           /* other configurations options */
           .use_secure_element = true,
       };

## Digital Signature with ESP-TLS

ESP-TLS provides support for using the Digital Signature (DS) with ESP32-C6. Use of the DS for TLS is supported only when ESP-TLS is used with MbedTLS (default stack) as its underlying SSL/TLS stack. For more details on Digital Signature, please refer to the Digital Signature (DS). The technical details of Digital Signature such as how to calculate private key parameters can be found in ESP32-C6 Technical Reference Manual > Digital Signature (DS) [PDF]. The DS peripheral must be configured before it can be used to perform Digital Signature, see Configure the DS Peripheral for a TLS Connection.

The DS peripheral must be initialized with the required encrypted private key parameters, which are obtained when the DS peripheral is configured. ESP-TLS internally initializes the DS peripheral when provided with the required DS context, i.e., DS parameters. Please see the below code snippet for passing the DS context to the ESP-TLS context. The DS context passed to the ESP-TLS context should not be freed till the TLS connection is deleted.

    #include "esp_tls.h"
    esp_ds_data_ctx_t *ds_ctx;
    /* initialize ds_ctx with encrypted private key parameters, which can be read from the nvs or provided through the application code */
    esp_tls_cfg_t cfg = {
        .clientcert_buf = /* the client certification */,
        .clientcert_bytes = /* length of the client certification */,
        /* other configurations options */
        .ds_data = (void *)ds_ctx,
    };

Note

When using Digital Signature for the TLS connection, along with the other required params, only the client certification (clientcert_buf) and the DS params (ds_data) are required and the client key (clientkey_buf) can be set to NULL.

- A mutual-authentication example that utilizes the DS peripheral is shipped with the standalone espressif/mqtt component and internally relies on ESP-TLS for the TLS connection. Follow the component documentation to fetch and build that example.

## Client Session Tickets

ESP-TLS supports client-side session resumption, which can significantly reduce the time and resources spent on full TLS handshakes for subsequent connections to the same server. This feature is available when ESP-TLS uses MbedTLS as its underlying SSL/TLS stack.

The mechanism for session resumption differs slightly between TLS versions:

- TLS 1.2: Session resumption can be achieved using session IDs (managed internally by the TLS stack) or session tickets (as per RFC 5077). ESP-TLS focuses on the session ticket mechanism for explicit application control.

- TLS 1.3: Session resumption is accomplished exclusively through session tickets, which are sent by the server via a "NewSessionTicket" message after the main handshake is complete. Unlike TLS 1.2, these tickets can be sent at any time during the session, not just immediately after the handshake.

To enable and use client session tickets:

1. Enable the Kconfig option CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS.

2. After a successful TLS connection (and handshake completion), retrieve the session ticket using `esp_tls_get_client_session()`.

   > - For TLS 1.3: Since session tickets can arrive from the server at any point after the handshake, an application might need to call `esp_tls_get_client_session()` periodically or after specific application-level exchanges if it wants to ensure it has the most recent ticket. Each new ticket received and processed by the TLS stack supersedes the previous one for future resumption attempts.

3. Store this session ticket securely.

4. For subsequent connections to the same server, provide the stored session ticket in the `esp_tls_cfg_t::client_session` field.

5. Remember to free the client session context using `esp_tls_free_client_session()` when it's no longer needed or before obtaining a new one.

    #include "esp_tls.h"

    // Global or persistent storage for the client session
    esp_tls_client_session_t *saved_session = NULL;

    void connect_to_server(bool use_saved_session_arg) {
        esp_tls_cfg_t cfg = {0}; // Initialize other config parameters as needed
        // ... set other cfg members like cacert_buf, common_name etc. ...

        if (use_saved_session_arg && saved_session) {
            cfg.client_session = saved_session;
            // ESP_LOGI(TAG, "Attempting connection with saved session ticket.");
        } else {
            // ESP_LOGI(TAG, "Attempting connection without a saved session ticket (full handshake).");
        }

        esp_tls_t *tls = esp_tls_init();
        if (!tls) {
            // ESP_LOGE(TAG, "Failed to initialize ESP-TLS handle.");
            return;
        }

        if (esp_tls_conn_http_new_sync("https://your-server.com", &cfg, tls) == 1) {
            // ESP_LOGI(TAG, "Connection successful.");

            // Always try to get/update the session ticket to have the latest one.
            // This is beneficial whether the connection was a new handshake or a resumption,
            // especially for TLS 1.3 where new tickets can arrive post-handshake.
            if (saved_session) {
                esp_tls_free_client_session(saved_session); // Free previous session if any
                saved_session = NULL;
            }
            saved_session = esp_tls_get_client_session(tls);
            if (saved_session) {
                // ESP_LOGI(TAG, "Successfully retrieved/updated client session ticket.");
            } else {
                // ESP_LOGW(TAG, "Failed to get client session ticket even after a successful connection.");
            }

            // ... do TLS communication ...

        }
        esp_tls_conn_destroy(tls);
    }

Note

- The session ticket obtained from a server is typically valid for a limited time. The server dictates this lifetime.

- When attempting a connection using a stored session ticket, if the ticket is found to be invalid by the server (e.g., it has expired or is otherwise rejected), ESP-TLS will automatically attempt to perform a full TLS handshake to establish the connection. The application does not need to implement separate logic to retry the connection without the ticket in this scenario. A connection failure will only be reported if both the session resumption and the subsequent internal attempt at a full handshake are unsuccessful.

- The `esp_tls_client_session_t` context should be freed using `esp_tls_free_client_session()` when it is no longer needed, or before a new session is obtained and stored in the same pointer.

- For TLS 1.3, be mindful that the server can send multiple NewSessionTicket messages during a connection. Each successful call to `esp_tls_get_client_session()` will provide the context of the latest ticket processed by the underlying TLS stack. It is the application's responsibility to manage and update its stored session if it wishes to use the newest tickets for resumption.

## TLS Ciphersuites

ESP-TLS provides the ability to set a ciphersuites list in client mode. The TLS ciphersuites list informs the server about the supported ciphersuites for the specific TLS connection regardless of the TLS stack configuration. If the server supports any ciphersuite from this list, then the TLS connection will succeed; otherwise, it will fail.

You can set `ciphersuites_list` in the `esp_tls_cfg_t` structure during client connection as follows:

    /* ciphersuites_list must end with 0 and must be available in the memory scope active during the entire TLS connection */
    static const int ciphersuites_list[] = {MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, 0};
    esp_tls_cfg_t cfg = {
        .ciphersuites_list = ciphersuites_list,
    };

ESP-TLS will not check the validity of `ciphersuites_list` that was set, you should call `esp_tls_get_ciphersuites_list()` to get ciphersuites list supported in the TLS stack and cross-check it against the supplied list.

Note

This feature is supported only in the MbedTLS stack.

## TLS Protocol Version

ESP-TLS provides the ability to set the TLS protocol version for the respective TLS connection. Once the version is specified, it should be exclusively used to establish the TLS connection. This provides an ability to route different TLS connections to different protocol versions like TLS 1.2 and TLS 1.3 at runtime.

Note

At the moment, the feature is supported only when ESP-TLS is used with MbedTLS as its underlying SSL/TLS stack.

To set TLS protocol version with ESP-TLS, set `esp_tls_cfg_t::tls_version` to the required protocol version from `esp_tls_proto_ver_t`. If the protocol version field is not set, then the default policy is to allow TLS connection based on the server requirement.

The ESP-TLS connection can be configured to use the specified protocol version as follows:

    #include "esp_tls.h"
    esp_tls_cfg_t cfg = {
        .tls_version = ESP_TLS_VER_TLS_1_2,
    };

## API Reference

### Header File

- components/esp-tls/esp_tls.h

- This header file can be included with:

  >     #include "esp_tls.h"

- This header file is a part of the API provided by the `esp-tls` component. To declare that your component depends on `esp-tls`, add the following to your CMakeLists.txt:

  >     REQUIRES esp-tls

  > or

  >     PRIV_REQUIRES esp-tls

### Functions

esp_err_t esp_tls_cfg_server_session_tickets_init(esp_tls_cfg_server_t *cfg)

  Initialize the server side TLS session ticket context.

  This function initializes the server side tls session ticket context which holds all necessary data structures to enable tls session tickets according to RFC5077. Use esp_tls_cfg_server_session_tickets_free to free the data.

  Parameters:

    cfg -- [in] server configuration as esp_tls_cfg_server_t

  Returns:

    ESP_OK if setup succeeded ESP_ERR_INVALID_ARG if context is already initialized ESP_ERR_NO_MEM if memory allocation failed ESP_ERR_NOT_SUPPORTED if session tickets are not available due to build configuration ESP_FAIL if setup failed

void esp_tls_cfg_server_session_tickets_free(esp_tls_cfg_server_t *cfg)

  Free the server side TLS session ticket context.

  Parameters:

    cfg -- server configuration as esp_tls_cfg_server_t

esp_tls_t *esp_tls_init(void)

  Create TLS connection.

  This function allocates and initializes esp-tls structure handle.

  Returns:

    tls Pointer to esp-tls as esp-tls handle if successfully initialized, NULL if allocation error

int esp_tls_conn_new_sync(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls)

  Create a new blocking TLS/SSL connection.

  This function establishes a TLS/SSL connection with the specified host in blocking manner.

  Parameters:

    - hostname -- [in] Hostname of the host.

    - hostlen -- [in] Length of hostname.

    - port -- [in] Port number of the host.

    - cfg -- [in] TLS configuration as esp_tls_cfg_t. For a TLS connection, pass a pointer to a esp_tls_cfg_t. For a plain TCP connection, pass a pointer to a esp_tls_cfg_t with is_plain_tcp set to true. At a minimum, this pointer should be not NULL and the structure should be zero-initialized

    - tls -- [in] Pointer to esp-tls as esp-tls handle.

  Returns:

    - -1 If connection establishment fails.

    - 1 If connection establishment is successful.

    - 0 If connection state is in progress.

int esp_tls_conn_http_new_sync(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls)

  Create a new blocking TLS/SSL connection with a given "HTTP" url.

  The behaviour is same as esp_tls_conn_new_sync() API. However this API accepts host's url.

  Parameters:

    - url -- [in] url of host.

    - cfg -- [in] TLS configuration as esp_tls_cfg_t. If you wish to open non-TLS connection, keep this NULL. For TLS connection, a pass pointer to 'esp_tls_cfg_t'. At a minimum, this structure should be zero-initialized.

    - tls -- [in] Pointer to esp-tls as esp-tls handle.

  Returns:

    - -1 If connection establishment fails.

    - 1 If connection establishment is successful.

    - 0 If connection state is in progress.

int esp_tls_conn_new_async(const char *hostname, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_t *tls)

  Create a new non-blocking TLS/SSL connection.

  This function initiates a non-blocking TLS/SSL connection with the specified host, but due to its non-blocking nature, it doesn't wait for the connection to get established.

  Parameters:

    - hostname -- [in] Hostname of the host.

    - hostlen -- [in] Length of hostname.

    - port -- [in] Port number of the host.

    - cfg -- [in] TLS configuration as esp_tls_cfg_t. `non_block` member of this structure should be set to be true.

    - tls -- [in] pointer to esp-tls as esp-tls handle.

  Returns:

    - -1 If connection establishment fails.

    - 0 If connection establishment is in progress.

    - 1 If connection establishment is successful.

int esp_tls_conn_http_new_async(const char *url, const esp_tls_cfg_t *cfg, esp_tls_t *tls)

  Create a new non-blocking TLS/SSL connection with a given "HTTP" url.

  The behaviour is same as esp_tls_conn_new_async() API. However this API accepts host's url.

  Parameters:

    - url -- [in] url of host.

    - cfg -- [in] TLS configuration as esp_tls_cfg_t.

    - tls -- [in] pointer to esp-tls as esp-tls handle.

  Returns:

    - -1 If connection establishment fails.

    - 0 If connection establishment is in progress.

    - 1 If connection establishment is successful.

ssize_t esp_tls_conn_write(esp_tls_t *tls, const void *data, size_t datalen)

  Write from buffer 'data' into specified tls connection.

  Parameters:

    - tls -- [in] pointer to esp-tls as esp-tls handle.

    - data -- [in] Buffer from which data will be written.

    - datalen -- [in] Length of data buffer.

  Returns:

    - >=0 if write operation was successful, the return value is the number of bytes actually written to the TLS/SSL connection.

    - <0 if write operation was not successful, because either an error occurred or an action must be taken by the calling process.

    - ESP_TLS_ERR_SSL_WANT_READ/ ESP_TLS_ERR_SSL_WANT_WRITE. if the handshake is incomplete and waiting for data to be available for reading. In this case this functions needs to be called again when the underlying transport is ready for operation.

ssize_t esp_tls_conn_read(esp_tls_t *tls, void *data, size_t datalen)

  Read from specified tls connection into the buffer 'data'.

  Parameters:

    - tls -- [in] pointer to esp-tls as esp-tls handle.

    - data -- [in] Buffer to hold read data.

    - datalen -- [in] Length of data buffer.

  Returns:

    - >0 if read operation was successful, the return value is the number of bytes actually read from the TLS/SSL connection.

    - 0 if read operation was not successful. The underlying connection was closed.

    - <0 if read operation was not successful, because either an error occurred or an action must be taken by the calling process.

int esp_tls_conn_destroy(esp_tls_t *tls)

  Close the TLS/SSL connection and free any allocated resources.

  This function should be called to close each tls connection opened with esp_tls_conn_new_sync() (or esp_tls_conn_http_new_sync()) and esp_tls_conn_new_async() (or esp_tls_conn_http_new_async()) APIs.

  Parameters:

    tls -- [in] pointer to esp-tls as esp-tls handle.

  Returns:

    - 0 on success

    - -1 if socket error or an invalid argument

ssize_t esp_tls_get_bytes_avail(esp_tls_t *tls)

  Return the number of application data bytes remaining to be read from the current record.

  This API is a wrapper over mbedtls's mbedtls_ssl_get_bytes_avail() API.

  Parameters:

    tls -- [in] pointer to esp-tls as esp-tls handle.

  Returns:

    - -1 in case of invalid arg

    - bytes available in the application data record read buffer

esp_err_t esp_tls_get_conn_sockfd(esp_tls_t *tls, int *sockfd)

  Returns the connection socket file descriptor from esp_tls session.

  Parameters:

    - tls -- [in] handle to esp_tls context

    - sockfd -- [out] int pointer to sockfd value.

  Returns:

    - ESP_OK on success and value of sockfd will be updated with socket file descriptor for connection

    - ESP_ERR_INVALID_ARG if (tls == NULL || sockfd == NULL)

esp_err_t esp_tls_set_conn_sockfd(esp_tls_t *tls, int sockfd)

  Sets the connection socket file descriptor for the esp_tls session.

  Parameters:

    - tls -- [in] handle to esp_tls context

    - sockfd -- [in] sockfd value to set.

  Returns:

    - ESP_OK on success and value of sockfd for the tls connection shall updated with the provided value

    - ESP_ERR_INVALID_ARG if (tls == NULL || sockfd < 0)

esp_err_t esp_tls_get_conn_state(esp_tls_t *tls, esp_tls_conn_state_t *conn_state)

  Gets the connection state for the esp_tls session.

  Parameters:

    - tls -- [in] handle to esp_tls context

    - conn_state -- [out] pointer to the connection state value.

  Returns:

    - ESP_OK on success and value of sockfd for the tls connection shall updated with the provided value

    - ESP_ERR_INVALID_ARG (Invalid arguments)

esp_err_t esp_tls_set_conn_state(esp_tls_t *tls, esp_tls_conn_state_t conn_state)

  Sets the connection state for the esp_tls session.

  Parameters:

    - tls -- [in] handle to esp_tls context

    - conn_state -- [in] connection state value to set.

  Returns:

    - ESP_OK on success and value of sockfd for the tls connection shall updated with the provided value

    - ESP_ERR_INVALID_ARG (Invalid arguments)

void *esp_tls_get_ssl_context(esp_tls_t *tls)

  Returns the ssl context.

  Parameters:

    tls -- [in] handle to esp_tls context

  Returns:

    - ssl_ctx pointer to ssl context of underlying TLS layer on success

    - NULL in case of error

esp_err_t esp_tls_init_global_ca_store(void)

  Create a global CA store, initially empty.

  This function should be called if the application wants to use the same CA store for multiple connections. This function initialises the global CA store which can be then set by calling esp_tls_set_global_ca_store(). To be effective, this function must be called before any call to esp_tls_set_global_ca_store().

  Returns:

    - ESP_OK if creating global CA store was successful.

    - ESP_ERR_NO_MEM if an error occurred when allocating the mbedTLS resources.

esp_err_t esp_tls_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes)

  Set the global CA store with the buffer provided in pem format.

  This function should be called if the application wants to set the global CA store for multiple connections i.e. to add the certificates in the provided buffer to the certificate chain. This function implicitly calls esp_tls_init_global_ca_store() if it has not already been called. The application must call this function before calling esp_tls_conn_new().

  Parameters:

    - cacert_pem_buf -- [in] Buffer which has certificates in pem format. This buffer is used for creating a global CA store, which can be used by other tls connections.

    - cacert_pem_bytes -- [in] Length of the buffer.

  Returns:

    - ESP_OK if adding certificates was successful.

    - Other if an error occurred or an action must be taken by the calling process.

void esp_tls_free_global_ca_store(void)

  Free the global CA store currently being used.

  The memory being used by the global CA store to store all the parsed certificates is freed up. The application can call this API if it no longer needs the global CA store.

esp_err_t esp_tls_get_and_clear_last_error(esp_tls_error_handle_t h, int *esp_tls_code, int *esp_tls_flags)

  Returns last error in esp_tls with detailed mbedtls related error codes. The error information is cleared internally upon return.

  Parameters:

    - h -- [in] esp-tls error handle.

    - esp_tls_code -- [out] last error code returned from mbedtls api (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code

    - esp_tls_flags -- [out] last certification verification flags (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code

  Returns:

    - ESP_ERR_INVALID_STATE if invalid parameters

    - ESP_OK (0) if no error occurred

    - specific error code (based on ESP_ERR_ESP_TLS_BASE) otherwise

esp_err_t esp_tls_get_and_clear_error_type(esp_tls_error_handle_t h, esp_tls_error_type_t err_type, int *error_code)

  Returns the last error captured in esp_tls of a specific type The error information is cleared internally upon return.

  Parameters:

    - h -- [in] esp-tls error handle.

    - err_type -- [in] specific error type

    - error_code -- [out] last error code returned from mbedtls api (set to zero if none) This pointer could be NULL if caller does not care about esp_tls_code

  Returns:

    - ESP_ERR_INVALID_STATE if invalid parameters

    - ESP_OK if a valid error returned and was cleared

esp_err_t esp_tls_get_error_handle(esp_tls_t *tls, esp_tls_error_handle_t *error_handle)

  Returns the ESP-TLS error_handle.

  Parameters:

    - tls -- [in] handle to esp_tls context

    - error_handle -- [out] pointer to the error handle.

  Returns:

    - ESP_OK on success and error_handle will be updated with the ESP-TLS error handle.

    - ESP_ERR_INVALID_ARG if (tls == NULL || error_handle == NULL)

mbedtls_x509_crt *esp_tls_get_global_ca_store(void)

  Get the pointer to the global CA store currently being used.

  The application must first call esp_tls_set_global_ca_store(). Then the same CA store could be used by the application for APIs other than esp_tls.

  Note

  Modifying the pointer might cause a failure in verifying the certificates.

  Returns:

    - Pointer to the global CA store currently being used if successful.

    - NULL if there is no global CA store set.

const int *esp_tls_get_ciphersuites_list(void)

  Get supported TLS ciphersuites list.

  See https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-4 for the list of ciphersuites

  Returns:

    Pointer to a zero-terminated array of IANA identifiers of TLS ciphersuites.

esp_err_t esp_tls_server_session_init(esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls)

  Initialize server side TLS/SSL connection.

  This function should be used to initialize the server side TLS/SSL connection when the application wants to handle the TLS/SSL connection asynchronously with the help of esp_tls_server_session_continue_async() function.

  Parameters:

    - cfg -- [in] Pointer to esp_tls_cfg_server_t

    - sockfd -- [in] FD of accepted connection

    - tls -- [out] Pointer to allocated esp_tls_t

  Returns:

    - ESP_OK if successful

    - ESP_ERR_INVALID_ARG if invalid arguments

    - ESP_FAIL if server session setup failed

int esp_tls_server_session_continue_async(esp_tls_t *tls)

  Asynchronous continue of esp_tls_server_session_init.

  This function should be called in a loop by the user until it returns 0. If this functions returns something other than 0, ESP_TLS_ERR_SSL_WANT_READ or ESP_TLS_ERR_SSL_WANT_WRITE, the esp-tls context must not be used and should be freed using esp_tls_conn_destroy();

  Parameters:

    tls -- [in] pointer to esp_tls_t

  Returns:

    - 0 if successful

    - <0 in case of error

    - ESP_TLS_ERR_SSL_WANT_READ/ESP_TLS_ERR_SSL_WANT_WRITE if the handshake is incomplete and waiting for data to be available for reading.

int esp_tls_server_session_create(esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls)

  Create TLS/SSL server session.

  This function creates a TLS/SSL server context for already accepted client connection and performs TLS/SSL handshake with the client

  Parameters:

    - cfg -- [in] Pointer to esp_tls_cfg_server_t

    - sockfd -- [in] FD of accepted connection

    - tls -- [out] Pointer to allocated esp_tls_t

  Returns:

    - 0 if successful

    - <0 in case of error

void esp_tls_server_session_delete(esp_tls_t *tls)

  Close the server side TLS/SSL connection and free any allocated resources.

  This function should be called to close each tls connection opened with esp_tls_server_session_create()

  Parameters:

    tls -- [in] pointer to esp_tls_t

esp_err_t esp_tls_plain_tcp_connect(const char *host, int hostlen, int port, const esp_tls_cfg_t *cfg, esp_tls_error_handle_t error_handle, int *sockfd)

  Creates a plain TCP connection, returning a valid socket fd on success or an error handle.

  Parameters:

    - host -- [in] Hostname of the host.

    - hostlen -- [in] Length of hostname.

    - port -- [in] Port number of the host.

    - cfg -- [in] ESP-TLS configuration as esp_tls_cfg_t.

    - error_handle -- [out] ESP-TLS error handle holding potential errors occurred during connection

    - sockfd -- [out] Socket descriptor if successfully connected on TCP layer

  Returns:

    ESP_OK on success ESP_ERR_INVALID_ARG if invalid output parameters ESP-TLS based error codes on failure

### Structures

struct psk_key_hint

  ESP-TLS preshared key and hint structure.

  Public Members

  const uint8_t *key

    key in PSK authentication mode in binary format

  size_t key_size

    length of the key

  const char *hint

    hint in PSK authentication mode in string format

struct tls_keep_alive_cfg

  esp-tls client session ticket ctx

  Keep alive parameters structure

  Public Members

  bool keep_alive_enable

    Enable keep-alive timeout

  int keep_alive_idle

    Keep-alive idle time (second)

  int keep_alive_interval

    Keep-alive interval time (second)

  int keep_alive_count

    Keep-alive packet retry send count

struct esp_tls_cfg

  ESP-TLS configuration parameters.

  Note

  Note about format of certificates:

  - This structure includes certificates of a Certificate Authority, of client or server as well as private keys, which may be of PEM or DER format. In case of PEM format, the buffer must be NULL terminated (with NULL character included in certificate size).

  - Certificate Authority's certificate may be a chain of certificates in case of PEM format, but could be only one certificate in case of DER format

  - Variables names of certificates and private key buffers and sizes are defined as unions providing backward compatibility for legacy *_pem_buf and *_pem_bytes names which suggested only PEM format was supported. It is encouraged to use generic names such as cacert_buf and cacert_bytes.

  Public Members

  const char **alpn_protos

    Application protocols required for HTTP2. If HTTP2/ALPN support is required, a list of protocols that should be negotiated. The format is length followed by protocol name. For the most common cases the following is ok: const char **alpn_protos = { "h2", NULL };

    - where 'h2' is the protocol name

  const unsigned char *cacert_buf

    Certificate Authority's certificate in a buffer. Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM

  const unsigned char *cacert_pem_buf

    CA certificate buffer legacy name

  unsigned int cacert_bytes

    Size of Certificate Authority certificate pointed to by cacert_buf (including NULL-terminator in case of PEM format)

  unsigned int cacert_pem_bytes

    Size of Certificate Authority certificate legacy name

  const unsigned char *clientcert_buf

    Client certificate in a buffer Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM

  const unsigned char *clientcert_pem_buf

    Client certificate legacy name

  unsigned int clientcert_bytes

    Size of client certificate pointed to by clientcert_pem_buf (including NULL-terminator in case of PEM format)

  unsigned int clientcert_pem_bytes

    Size of client certificate legacy name

  const unsigned char *clientkey_buf

    Client key in a buffer Format may be PEM or DER, depending on mbedtls-support This buffer should be NULL terminated in case of PEM

  const unsigned char *clientkey_pem_buf

    Client key legacy name

  unsigned int clientkey_bytes

    Size of client key pointed to by clientkey_pem_buf (including NULL-terminator in case of PEM format)

  unsigned int clientkey_pem_bytes

    Size of client key legacy name

  const unsigned char *clientkey_password

    Client key decryption password string

  unsigned int clientkey_password_len

    String length of the password pointed to by clientkey_password

  bool use_ecdsa_peripheral

    Use the ECDSA peripheral for the private key operations

  uint8_t ecdsa_key_efuse_blk

    The efuse block where ECDSA key is stored. For SECP384R1 curve, if two blocks are used, set this to the low block and use ecdsa_key_efuse_blk_high for the high block.

  uint8_t ecdsa_key_efuse_blk_high

    The high efuse block for ECDSA key (used only for SECP384R1 curve). If not set (0), only ecdsa_key_efuse_blk is used.

  esp_tls_ecdsa_curve_t ecdsa_curve

    ECDSA curve to use (SECP256R1 or SECP384R1)

  bool non_block

    Configure non-blocking mode. If set to true the underneath socket will be configured in non blocking mode after tls session is established

  bool use_secure_element

    Enable this option to use secure element or atecc608a chip

  int timeout_ms

    Network timeout in milliseconds. Note: If this value is not set, by default the timeout is set to 10 seconds. If you wish that the session should wait indefinitely then please use a larger value e.g., INT32_MAX

  bool use_global_ca_store

    Use a global ca_store for all the connections in which this bool is set.

  const char *common_name

    If non-NULL, server certificate CN must match this name. If NULL, server certificate CN must match hostname.

  bool skip_common_name

    Skip any validation of server certificate CN field. This field should be set to false for SNI to function correctly.

  tls_keep_alive_cfg_t *keep_alive_cfg

    Enable TCP keep-alive timeout for SSL connection

  esp_err_t (*crt_bundle_attach)(void *conf)

    Function pointer to esp_crt_bundle_attach. Enables the use of certification bundle for server verification, must be enabled in menuconfig

  void *ds_data

    Pointer for digital signature peripheral context

  bool is_plain_tcp

    Use non-TLS connection: When set to true, the esp-tls uses plain TCP transport rather then TLS/SSL connection. Note, that it is possible to connect using a plain tcp transport directly with esp_tls_plain_tcp_connect() API

  struct ifreq *if_name

    The name of interface for data to go through. Use the default interface without setting

  esp_tls_addr_family_t addr_family

    The address family to use when connecting to a host.

  const int *ciphersuites_list

    Pointer to a zero-terminated array of IANA identifiers of TLS ciphersuites. Please check the list validity by esp_tls_get_ciphersuites_list() API

  esp_tls_proto_ver_t tls_version

    TLS protocol version of the connection, e.g., TLS 1.2, TLS 1.3 (default - no preference)

struct esp_tls_cfg_server

  ESP-TLS Server configuration parameters.

  Public Members

  const char **alpn_protos

    Application protocols required for HTTP2. If HTTP2/ALPN support is required, a list of protocols that should be negotiated. The format is length followed by protocol name. For the most common cases the following is ok: const char **alpn_protos = { "h2", NULL };

    - where 'h2' is the protocol name

  const unsigned char *cacert_buf

    Client CA certificate in a buffer. This buffer should be NULL terminated

  const unsigned char *cacert_pem_buf

    Client CA certificate legacy name

  unsigned int cacert_bytes

    Size of client CA certificate pointed to by cacert_pem_buf

  unsigned int cacert_pem_bytes

    Size of client CA certificate legacy name

  const unsigned char *servercert_buf

    Server certificate in a buffer This buffer should be NULL terminated

  const unsigned char *servercert_pem_buf

    Server certificate legacy name

  unsigned int servercert_bytes

    Size of server certificate pointed to by servercert_pem_buf

  unsigned int servercert_pem_bytes

    Size of server certificate legacy name

  const unsigned char *serverkey_buf

    Server key in a buffer This buffer should be NULL terminated

  const unsigned char *serverkey_pem_buf

    Server key legacy name

  unsigned int serverkey_bytes

    Size of server key pointed to by serverkey_pem_buf

  unsigned int serverkey_pem_bytes

    Size of server key legacy name

  const unsigned char *serverkey_password

    Server key decryption password string

  unsigned int serverkey_password_len

    String length of the password pointed to by serverkey_password

  bool use_ecdsa_peripheral

    Use ECDSA peripheral to use private key

  uint8_t ecdsa_key_efuse_blk

    The efuse block where ECDSA key is stored. For SECP384R1 curve, if two blocks are used, set this to the low block and use ecdsa_key_efuse_blk_high for the high block.

  uint8_t ecdsa_key_efuse_blk_high

    The high efuse block for ECDSA key (used only for SECP384R1 curve). If not set (0), only ecdsa_key_efuse_blk is used.

  esp_tls_ecdsa_curve_t ecdsa_curve

    ECDSA curve to use (SECP256R1 or SECP384R1)

  bool use_secure_element

    Enable this option to use secure element or atecc608a chip

  uint32_t tls_handshake_timeout_ms

    TLS handshake timeout in milliseconds. Note: If this value is not set, by default the timeout is set to 10 seconds. If you wish that the session should wait indefinitely then please use a larger value e.g., INT32_MAX

  void *userdata

    User data to be added to the ssl context. Can be retrieved by callbacks

  esp_tls_proto_ver_t tls_version

    TLS protocol version for this server, e.g., TLS 1.2, TLS 1.3 (default - no preference). Enables TLS version control per server instance.

  const int *ciphersuites_list

    Pointer to a zero-terminated array of IANA identifiers of TLS ciphersuites. Please check the list validity by esp_tls_get_ciphersuites_list() API. This allows per-server cipher suite configuration.

### Type Definitions

typedef enum esp_tls_conn_state esp_tls_conn_state_t

  ESP-TLS Connection State.

typedef enum esp_tls_role esp_tls_role_t

typedef struct psk_key_hint psk_hint_key_t

  ESP-TLS preshared key and hint structure.

typedef struct tls_keep_alive_cfg tls_keep_alive_cfg_t

  esp-tls client session ticket ctx

  Keep alive parameters structure

typedef enum esp_tls_addr_family esp_tls_addr_family_t

typedef struct esp_tls_cfg esp_tls_cfg_t

  ESP-TLS configuration parameters.

  Note

  Note about format of certificates:

  - This structure includes certificates of a Certificate Authority, of client or server as well as private keys, which may be of PEM or DER format. In case of PEM format, the buffer must be NULL terminated (with NULL character included in certificate size).

  - Certificate Authority's certificate may be a chain of certificates in case of PEM format, but could be only one certificate in case of DER format

  - Variables names of certificates and private key buffers and sizes are defined as unions providing backward compatibility for legacy *_pem_buf and *_pem_bytes names which suggested only PEM format was supported. It is encouraged to use generic names such as cacert_buf and cacert_bytes.

typedef void *esp_tls_handshake_callback

typedef struct esp_tls_cfg_server esp_tls_cfg_server_t

  ESP-TLS Server configuration parameters.

typedef struct esp_tls esp_tls_t

### Enumerations

enum esp_tls_conn_state

  ESP-TLS Connection State.

  Values:

  enumerator ESP_TLS_INIT
  enumerator ESP_TLS_CONNECTING
  enumerator ESP_TLS_HANDSHAKE
  enumerator ESP_TLS_FAIL
  enumerator ESP_TLS_DONE

enum esp_tls_role

  Values:

  enumerator ESP_TLS_CLIENT
  enumerator ESP_TLS_SERVER

enum esp_tls_addr_family

  Values:

  enumerator ESP_TLS_AF_UNSPEC

    Unspecified address family.

  enumerator ESP_TLS_AF_INET

    IPv4 address family.

  enumerator ESP_TLS_AF_INET6

    IPv6 address family.

enum esp_tls_proto_ver_t

  Values:

  enumerator ESP_TLS_VER_ANY
  enumerator ESP_TLS_VER_TLS_1_2
  enumerator ESP_TLS_VER_TLS_1_3
  enumerator ESP_TLS_VER_TLS_MAX

enum esp_tls_dyn_buf_strategy_t

  Values:

  enumerator ESP_TLS_DYN_BUF_RX_STATIC

    Strategy to disable dynamic RX buffer allocations and convert to static allocation post-handshake, reducing memory fragmentation

  enumerator ESP_TLS_DYN_BUF_STRATEGY_MAX

    to indicate max

enum esp_tls_ecdsa_curve_t

  ECDSA curve options for TLS connections.

  Values:

  enumerator ESP_TLS_ECDSA_CURVE_SECP256R1

    Use SECP256R1 curve

  enumerator ESP_TLS_ECDSA_CURVE_MAX

    to indicate max

### Header File

- components/esp-tls/esp_tls_errors.h

- This header file can be included with:

  >     #include "esp_tls_errors.h"

- This header file is a part of the API provided by the `esp-tls` component. To declare that your component depends on `esp-tls`, add the following to your CMakeLists.txt:

  >     REQUIRES esp-tls

  > or

  >     PRIV_REQUIRES esp-tls

### Structures

struct esp_tls_last_error

  Error structure containing relevant errors in case tls error occurred.

  Public Members

  esp_err_t last_error

    error code (based on ESP_ERR_ESP_TLS_BASE) of the last occurred error

  int esp_tls_error_code

    esp_tls error code from last esp_tls failed api

  int esp_tls_flags

    last certification verification flags

### Macros

ESP_ERR_ESP_TLS_BASE

  Starting number of ESP-TLS error codes

ESP_ERR_ESP_TLS_CANNOT_RESOLVE_HOSTNAME

  Error if hostname couldn't be resolved upon tls connection

ESP_ERR_ESP_TLS_CANNOT_CREATE_SOCKET

  Failed to create socket

ESP_ERR_ESP_TLS_UNSUPPORTED_PROTOCOL_FAMILY

  Unsupported protocol family

ESP_ERR_ESP_TLS_FAILED_CONNECT_TO_HOST

  Failed to connect to host

ESP_ERR_ESP_TLS_SOCKET_SETOPT_FAILED

  failed to set/get socket option

ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT

  new connection in esp_tls_low_level_conn connection timeouted

ESP_ERR_ESP_TLS_SE_FAILED

ESP_ERR_ESP_TLS_TCP_CLOSED_FIN

ESP_ERR_ESP_TLS_SERVER_HANDSHAKE_TIMEOUT

  TLS handshake timeout

ESP_ERR_MBEDTLS_CERT_PARTLY_OK

  mbedtls parse certificates was partly successful

ESP_ERR_MBEDTLS_CTR_DRBG_SEED_FAILED

  mbedtls api returned error

ESP_ERR_MBEDTLS_SSL_SET_HOSTNAME_FAILED

  mbedtls api returned error

ESP_ERR_MBEDTLS_SSL_CONFIG_DEFAULTS_FAILED

  mbedtls api returned error

ESP_ERR_MBEDTLS_SSL_CONF_ALPN_PROTOCOLS_FAILED

  mbedtls api returned error

ESP_ERR_MBEDTLS_X509_CRT_PARSE_FAILED

  mbedtls api returned error

ESP_ERR_MBEDTLS_SSL_CONF_OWN_CERT_FAILED

  mbedtls api returned error

ESP_ERR_MBEDTLS_SSL_SETUP_FAILED

  mbedtls api returned error

ESP_ERR_MBEDTLS_SSL_WRITE_FAILED

  mbedtls api returned error

ESP_ERR_MBEDTLS_PK_PARSE_KEY_FAILED

  mbedtls api returned failed

ESP_ERR_MBEDTLS_SSL_HANDSHAKE_FAILED

  mbedtls api returned failed

ESP_ERR_MBEDTLS_SSL_CONF_PSK_FAILED

  mbedtls api returned failed

ESP_ERR_MBEDTLS_SSL_TICKET_SETUP_FAILED

  mbedtls api returned failed

ESP_ERR_MBEDTLS_SSL_READ_FAILED

  mbedtls api returned failed

ESP_TLS_ERR_SSL_WANT_READ

  Definition of errors reported from IO API (potentially non-blocking) in case of error:

  - esp_tls_conn_read()

  - esp_tls_conn_write()

ESP_TLS_ERR_SSL_WANT_WRITE

ESP_TLS_ERR_SSL_TIMEOUT

### Type Definitions

typedef struct esp_tls_last_error *esp_tls_error_handle_t

typedef struct esp_tls_last_error esp_tls_last_error_t

  Error structure containing relevant errors in case tls error occurred.

### Enumerations

enum esp_tls_error_type_t

  Definition of different types/sources of error codes reported from different components

  Values:

  enumerator ESP_TLS_ERR_TYPE_UNKNOWN
  enumerator ESP_TLS_ERR_TYPE_SYSTEM

    System error – errno

  enumerator ESP_TLS_ERR_TYPE_MBEDTLS

    Error code from mbedTLS library

  enumerator ESP_TLS_ERR_TYPE_MBEDTLS_CERT_FLAGS

    Certificate flags defined in mbedTLS

  enumerator ESP_TLS_ERR_TYPE_ESP

    ESP-IDF error type – esp_err_t

  enumerator ESP_TLS_ERR_TYPE_CUSTOM_STACK

    Error code from custom TLS stack

  enumerator ESP_TLS_ERR_TYPE_CUSTOM_STACK_CERT_FLAGS

    Certificate flags from custom TLS stack

  enumerator ESP_TLS_ERR_TYPE_MAX

    Last err type – invalid entry

### Header File

- components/esp-tls/esp_tls_custom_stack.h

- This header file can be included with:

  >     #include "esp_tls_custom_stack.h"

- This header file is a part of the API provided by the `esp-tls` component. To declare that your component depends on `esp-tls`, add the following to your CMakeLists.txt:

  >     REQUIRES esp-tls

  > or

  >     PRIV_REQUIRES esp-tls

### Functions

esp_err_t esp_tls_custom_stack_create_ssl_handle(const char *hostname, size_t hostlen, const void *cfg, esp_tls_t *tls, void *server_params)

  Internal wrapper functions that call through the registered stack's vtable.

  These functions provide a uniform interface to the registered TLS stack implementation. They forward calls to the appropriate function pointer in the registered esp_tls_stack_ops_t structure.

  Create SSL handle for a TLS connection

  Note

  These are internal functions used by ESP-TLS and should not be called directly by applications.

int esp_tls_custom_stack_handshake(esp_tls_t *tls, const esp_tls_cfg_t *cfg)

  Perform TLS handshake.

ssize_t esp_tls_custom_stack_read(esp_tls_t *tls, char *data, size_t datalen)

  Read data from TLS connection.

ssize_t esp_tls_custom_stack_write(esp_tls_t *tls, const char *data, size_t datalen)

  Write data to TLS connection.

void esp_tls_custom_stack_conn_delete(esp_tls_t *tls)

  Delete TLS connection and free resources.

void esp_tls_custom_stack_net_init(esp_tls_t *tls)

  Initialize network context for TLS connection.

void *esp_tls_custom_stack_get_ssl_context(esp_tls_t *tls)

  Get SSL context (stack-specific)

ssize_t esp_tls_custom_stack_get_bytes_avail(esp_tls_t *tls)

  Get number of bytes available for reading.

esp_err_t esp_tls_custom_stack_init_global_ca_store(void)

  Initialize global CA certificate store.

esp_err_t esp_tls_custom_stack_set_global_ca_store(const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes)

  Set global CA certificate store.

void *esp_tls_custom_stack_get_global_ca_store(void)

  Get global CA certificate store (stack-specific)

void esp_tls_custom_stack_free_global_ca_store(void)

  Free global CA certificate store.

const int *esp_tls_custom_stack_get_ciphersuites_list(void)

  Get list of supported ciphersuites.

void *esp_tls_custom_stack_get_client_session(esp_tls_t *tls)

  Get client session ticket for reuse.

void esp_tls_custom_stack_free_client_session(void *client_session)

  Free client session ticket.

esp_err_t esp_tls_custom_stack_server_session_ticket_ctx_init(void *cfg)

  Initialize server session ticket context.

void esp_tls_custom_stack_server_session_ticket_ctx_free(void *cfg)

  Free server session ticket context.

int esp_tls_custom_stack_server_session_create(esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls)

  Create server session (blocking)

esp_err_t esp_tls_custom_stack_server_session_init(esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls)

  Initialize server session (non-blocking)

int esp_tls_custom_stack_server_session_continue_async(esp_tls_t *tls)

  Continue async server session handshake.

void esp_tls_custom_stack_server_session_delete(esp_tls_t *tls)

  Delete server session.

int esp_tls_custom_stack_crypto_sha1(const unsigned char *input, size_t ilen, unsigned char output[20])

  Calculate SHA1 hash using registered stack's implementation.

int esp_tls_custom_stack_crypto_base64_encode(unsigned char *dst, size_t dlen, size_t *olen, const unsigned char *src, size_t slen)

  Base64 encode using registered stack's implementation.

esp_err_t esp_tls_register_stack(const esp_tls_stack_ops_t *ops, void *user_ctx)

  Register a custom TLS stack implementation.

  This function allows an external component to register its TLS stack implementation. Once registered, all TLS connections created after this call will use the registered stack.

      // Example usage:
      static const esp_tls_stack_ops_t my_tls_ops = {
          .version = ESP_TLS_STACK_OPS_VERSION,
          .create_ssl_handle = my_create_ssl_handle,
          .handshake = my_handshake,
          .read = my_read,
          .write = my_write,
          .conn_delete = my_conn_delete,
          .net_init = my_net_init,
          .get_ssl_context = my_get_ssl_context,
          .get_bytes_avail = my_get_bytes_avail,
          .init_global_ca_store = my_init_global_ca_store,
          .set_global_ca_store = my_set_global_ca_store,
          .get_global_ca_store = my_get_global_ca_store,
          .free_global_ca_store = my_free_global_ca_store,
          .get_ciphersuites_list = my_get_ciphersuites_list,
      // Optional functions...
      };

      void app_main(void) {
          esp_err_t ret = esp_tls_register_stack(&my_tls_ops, NULL);
      if (ret != ESP_OK) {
              ESP_LOGE("APP", "Failed to register TLS stack: %s", esp_err_to_name(ret));
      return;
          }
      // ... create TLS connections as usual ...
      }

  Note

  This function must be called before creating any TLS connections (esp_tls_conn_new(), etc.).

  Note

  This function can only be called once. Subsequent calls will return ESP_ERR_INVALID_STATE.

  Note

  If CONFIG_ESP_TLS_CUSTOM_STACK is not enabled, this function will return ESP_ERR_NOT_SUPPORTED.

  Note

  All required function pointers in ops must be non-NULL. Optional functions can be NULL.

  Note

  The ops structure pointer is stored by reference, not copied. The structure must remain valid in memory for the entire duration of TLS operations (typically the lifetime of the application). Use a static or global variable, not a stack-allocated or dynamically allocated structure that may be freed. Using a `const` static structure allows the compiler to place it in flash (.rodata), saving ~80 bytes of RAM.

  Parameters:

    - ops -- Pointer to TLS stack operations vtable containing your implementation. Must point to a static/global structure (not on stack) as it's stored by reference. Required fields:

      - version (must be set to ESP_TLS_STACK_OPS_VERSION)

      - create_ssl_handle

      - handshake

      - read

      - write

      - conn_delete

      - net_init

      - get_ssl_context

      - get_bytes_avail

      - init_global_ca_store

      - set_global_ca_store

      - get_global_ca_store

      - free_global_ca_store

      - get_ciphersuites_list Optional functions (can be NULL if not supported):

      - get_client_session (for CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS)

      - free_client_session (for CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS)

      - server_session_ticket_ctx_init (for CONFIG_ESP_TLS_SERVER_SESSION_TICKETS)

      - server_session_ticket_ctx_free (for CONFIG_ESP_TLS_SERVER_SESSION_TICKETS)

      - server_session_create (server-side, can be NULL if server_session_init is provided)

      - server_session_init (server-side, can be NULL if server_session_create is provided)

      - server_session_continue_async (server-side, can be NULL if server_session_create is provided)

      - server_session_delete (server-side, can be NULL, conn_delete will be used)

    - user_ctx -- User context pointer that will be passed to all callbacks as the first parameter. This allows C++ implementations to avoid singletons by passing instance pointers. Can be NULL if not needed.

  Returns:

    - ESP_OK: Stack registered successfully

    - ESP_ERR_INVALID_ARG: ops is NULL or any required function pointer is NULL

    - ESP_ERR_INVALID_VERSION: ops->version does not match ESP_TLS_STACK_OPS_VERSION

    - ESP_ERR_INVALID_STATE: A stack is already registered

    - ESP_ERR_NOT_SUPPORTED: CONFIG_ESP_TLS_CUSTOM_STACK is not enabled

esp_err_t esp_tls_unregister_stack(void)

  Unregister the custom TLS stack implementation.

  This function removes the registered TLS stack, allowing a new stack to be registered. This is primarily useful for testing scenarios where you need to switch between different TLS stack implementations.

  Note

  This function should NOT be called while any TLS connections are active. Ensure all TLS connections are closed before calling this function.

  Note

  If CONFIG_ESP_TLS_CUSTOM_STACK is not enabled, this function will return ESP_ERR_NOT_SUPPORTED.

  Returns:

    - ESP_OK: Stack unregistered successfully

    - ESP_ERR_INVALID_STATE: No stack was registered

    - ESP_ERR_NOT_SUPPORTED: CONFIG_ESP_TLS_CUSTOM_STACK is not enabled

const esp_tls_stack_ops_t *esp_tls_get_registered_stack(void)

  Get the registered TLS stack operations.

  Returns:

    Pointer to registered TLS stack operations, or NULL if no stack is registered or CONFIG_ESP_TLS_CUSTOM_STACK is not enabled

### Structures

struct esp_tls_stack_ops

  TLS stack operations vtable.

  This structure defines the interface that external TLS stack implementations must provide. All function pointers must be non-NULL.

  Note

  To register a custom TLS stack:

  1. Enable CONFIG_ESP_TLS_CUSTOM_STACK in menuconfig

  2. Implement all required functions in this structure

  3. Call esp_tls_register_stack() with your implementation before creating any TLS connections

  Note

  The TLS context (esp_tls_t) is managed by ESP-TLS. Your implementation should store stack-specific data in the appropriate fields of esp_tls_t (e.g., priv_ctx, priv_ssl) or allocate additional memory and store a pointer to it.

  Note

  For client connections: hostname and cfg (esp_tls_cfg_t) are provided

  Note

  For server connections: hostname is NULL, cfg is esp_tls_cfg_server_t, server_params is provided

  Public Members

  uint32_t version

    Structure version for compatibility checking.

    Must be set to ESP_TLS_STACK_OPS_VERSION. This field allows ESP-TLS to detect version mismatches between the ESP-IDF version and the custom TLS stack implementation.

  esp_err_t (*create_ssl_handle)(void *user_ctx, const char *hostname, size_t hostlen, const void *cfg, esp_tls_t *tls, void *server_params)

    Create SSL handle for a TLS connection.

    This function initializes the TLS stack for a new connection. It should:

    - Initialize the TLS/SSL context for the given connection

    - Configure certificates, keys, and other TLS parameters from cfg

    - Set up the underlying socket (tls->sockfd is already set)

    - For client: configure SNI using hostname

    - For server: use server_params if provided

    - Store stack-specific context in tls->priv_ctx or tls->priv_ssl

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param hostname:

      Hostname for the connection (client only, NULL for server)

    Param hostlen:

      Length of hostname (0 for server)

    Param cfg:

      TLS configuration:

      - For client: pointer to esp_tls_cfg_t

      - For server: pointer to esp_tls_cfg_server_t

    Param tls:

      TLS context (already allocated, sockfd is set)

    Param server_params:

      Server-specific parameters (NULL for client, non-NULL for server) Contains server configuration callbacks

    Return:

      - ESP_OK: SSL handle created successfully

      - ESP_ERR_NO_MEM: Memory allocation failed

      - ESP_ERR_INVALID_ARG: Invalid configuration

      - Other error codes: Stack-specific errors

  int (*handshake)(void *user_ctx, esp_tls_t *tls, const esp_tls_cfg_t *cfg)

    Perform TLS handshake.

    This function performs the TLS handshake. It should:

    - Execute the TLS handshake protocol

    - Handle handshake state (may need multiple calls)

    - Verify certificates if configured

    - Update tls->conn_state appropriately

    Note

    This function may be called multiple times until it returns 1 or a negative error. The ESP-TLS layer handles retries based on the return value.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param tls:

      TLS context (created by create_ssl_handle)

    Param cfg:

      TLS configuration (esp_tls_cfg_t for client, can be used for timeout checks)

    Return:

      - 1: Handshake completed successfully

      - 0: Handshake in progress, call again later

      - ESP_TLS_ERR_SSL_WANT_READ: Need to read more data from socket

      - ESP_TLS_ERR_SSL_WANT_WRITE: Need to write more data to socket

      - Negative value: Handshake failed (error code)

  ssize_t (*read)(void *user_ctx, esp_tls_t *tls, char *data, size_t datalen)

    Read data from TLS connection.

    This function reads decrypted application data from the TLS connection. It should:

    - Read encrypted data from tls->sockfd

    - Decrypt using the TLS stack

    - Return decrypted application data

    - Handle partial reads and blocking/non-blocking behavior

    Note

    This function is called by tls->read() callback, which is set during handshake.

    Note

    The function should handle TLS record boundaries and may need multiple socket reads to decrypt a single application data record.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param tls:

      TLS context (handshake must be completed)

    Param data:

      Buffer to store decrypted data

    Param datalen:

      Maximum number of bytes to read (size of data buffer)

    Return:

      - Positive value: Number of bytes read (0 < return <= datalen)

      - 0: Connection closed by peer

      - ESP_TLS_ERR_SSL_WANT_READ: Need to read more encrypted data from socket

      - ESP_TLS_ERR_SSL_WANT_WRITE: Need to write data (renegotiation)

      - Negative value: Error occurred

  ssize_t (*write)(void *user_ctx, esp_tls_t *tls, const char *data, size_t datalen)

    Write data to TLS connection.

    This function encrypts and writes application data to the TLS connection. It should:

    - Encrypt application data using the TLS stack

    - Write encrypted data to tls->sockfd

    - Handle partial writes and blocking/non-blocking behavior

    Note

    This function is called by tls->write() callback, which is set during handshake.

    Note

    The function may write less than datalen if the socket buffer is full (non-blocking mode). The caller should retry with remaining data.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param tls:

      TLS context (handshake must be completed)

    Param data:

      Application data to encrypt and send

    Param datalen:

      Number of bytes to write

    Return:

      - Positive value: Number of bytes written (should equal datalen if successful)

      - ESP_TLS_ERR_SSL_WANT_READ: Need to read data (renegotiation)

      - ESP_TLS_ERR_SSL_WANT_WRITE: Socket buffer full, try again later

      - Negative value: Error occurred

  void (*conn_delete)(void *user_ctx, esp_tls_t *tls)

    Delete TLS connection and free resources.

    This function cleans up the TLS connection and frees all resources. It should:

    - Close the TLS/SSL session

    - Free any stack-specific context stored in tls->priv_ctx or tls->priv_ssl

    - Free any allocated memory

    - Note: tls->sockfd is closed separately by ESP-TLS, don't close it here

    Note

    This function should be idempotent (safe to call multiple times).

    Note

    After this call, the tls context may be freed, so don't access it afterwards.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param tls:

      TLS context to clean up

  void (*net_init)(void *user_ctx, esp_tls_t *tls)

    Initialize network context.

    This function initializes any network-related structures needed by the TLS stack. It should:

    - Initialize socket wrappers or network context structures

    - Set up any network-related state

    - This is typically called once per TLS context before create_ssl_handle

    Note

    For some stacks, this may be a no-op if network initialization is handled elsewhere.

    Note

    This is called early in the connection setup, before create_ssl_handle.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param tls:

      TLS context (sockfd is already set)

  void *(*get_ssl_context)(void *user_ctx, esp_tls_t *tls)

    Get SSL context (stack-specific)

    This function returns the underlying SSL/TLS context object from the stack. This allows users to access stack-specific APIs directly if needed.

    Note

    The returned pointer is stack-specific and should be cast to the appropriate type by users who know which stack is registered.

    Note

    This is optional but recommended for advanced users who need stack-specific features.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param tls:

      TLS context

    Return:

      Pointer to stack-specific SSL context (e.g., mbedtls_ssl_context*, SSL_CTX*, etc.) or NULL if not available

  ssize_t (*get_bytes_avail)(void *user_ctx, esp_tls_t *tls)

    Get bytes available for reading.

    This function returns the number of decrypted application data bytes available to read without blocking.

    Note

    This checks the TLS stack's internal buffer, not the socket buffer.

    Note

    Useful for non-blocking I/O to check if data is ready before calling read().

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param tls:

      TLS context

    Return:

      - Positive value: Number of bytes available to read

      - 0: No data available

      - Negative value: Error occurred

  esp_err_t (*init_global_ca_store)(void *user_ctx)

    Initialize global CA store.

    This function initializes a global certificate authority (CA) store that can be used by all TLS connections. This is useful for applications that want to use the same CA certificates for multiple connections.

    Note

    This is called once at application startup if esp_tls_init_global_ca_store() is used.

    Note

    The global CA store is optional - individual connections can use their own CA certificates.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Return:

      - ESP_OK: CA store initialized successfully

      - ESP_ERR_NO_MEM: Memory allocation failed

      - Other error codes: Stack-specific errors

  esp_err_t (*set_global_ca_store)(void *user_ctx, const unsigned char *cacert_pem_buf, const unsigned int cacert_pem_bytes)

    Set global CA store.

    This function loads CA certificates into the global CA store. The certificates are used for server certificate verification in client connections.

    Note

    The buffer should contain one or more PEM-formatted CA certificates.

    Note

    For PEM format, the buffer must be NULL-terminated.

    Note

    This can be called multiple times to add more certificates.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param cacert_pem_buf:

      CA certificate buffer in PEM format (NULL-terminated)

    Param cacert_pem_bytes:

      Size of CA certificate buffer (including NULL terminator for PEM)

    Return:

      - ESP_OK: CA certificates loaded successfully

      - ESP_ERR_INVALID_ARG: Invalid certificate format

      - ESP_ERR_NO_MEM: Memory allocation failed

      - Other error codes: Stack-specific errors

  void *(*get_global_ca_store)(void *user_ctx)

    Get global CA store (stack-specific)

    This function returns the underlying CA store object from the stack. This allows users to access stack-specific CA store APIs directly if needed.

    Note

    The returned pointer is stack-specific and should be cast to the appropriate type.

    Note

    This is optional but useful for advanced users who need stack-specific features.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Return:

      Pointer to stack-specific CA store (e.g., mbedtls_x509_crt*, X509_STORE*, etc.) or NULL if not initialized

  void (*free_global_ca_store)(void *user_ctx)

    Free global CA store.

    This function frees all resources associated with the global CA store.

    Note

    This should free all certificates and memory allocated for the CA store.

    Note

    After this call, the global CA store is no longer usable until reinitialized.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

  const int *(*get_ciphersuites_list)(void *user_ctx)

    Get list of supported ciphersuites.

    This function returns a list of IANA ciphersuite identifiers supported by the stack. This is used by esp_tls_get_ciphersuites_list() API.

    Note

    The returned pointer should point to static/const data (not dynamically allocated).

    Note

    Ciphersuite identifiers are IANA standard values (e.g., 0x0035 for TLS_RSA_WITH_AES_256_CBC_SHA).

    Note

    This list is used for validation when users specify custom ciphersuite lists.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Return:

      Pointer to zero-terminated array of IANA ciphersuite identifiers (integers) The array must be terminated with 0.

  void *(*get_client_session)(void *user_ctx, esp_tls_t *tls)

    Get client session (optional, for session ticket support)

    This function retrieves the client session ticket/session data that can be reused for subsequent connections to the same server (RFC 5077).

    Note

    The returned session can be stored and reused in future connections to the same server.

    Note

    This is only used if CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is enabled.

    Note

    The session data is stack-specific and opaque to ESP-TLS.

    Note

    Can be NULL if session tickets are not supported by the stack.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param tls:

      TLS context (handshake must be completed)

    Return:

      Pointer to client session data (stack-specific type), or NULL if:

      - Session tickets are not supported

      - No session ticket was received

      - Error occurred

  void (*free_client_session)(void *user_ctx, void *client_session)

    Free client session (optional, for session ticket support)

    This function frees resources associated with a client session retrieved by get_client_session().

    Note

    This should free all memory associated with the session.

    Note

    This is only used if CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is enabled.

    Note

    Can be NULL if session tickets are not supported by the stack.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param client_session:

      Client session to free (returned by get_client_session())

  esp_err_t (*server_session_ticket_ctx_init)(void *user_ctx, void *cfg)

    Initialize server session ticket context (optional, for server session ticket support)

    This function initializes the server-side session ticket context for issuing and validating session tickets (RFC 5077).

    Note

    This is called when setting up server session tickets.

    Note

    The context should store encryption keys and other ticket-related state.

    Note

    This is only used if CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is enabled.

    Note

    Can be NULL if server session tickets are not supported by the stack.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param cfg:

      Pointer to esp_tls_server_session_ticket_ctx_t structure Contains ticket encryption keys and configuration

    Return:

      - ESP_OK: Session ticket context initialized successfully

      - ESP_ERR_INVALID_ARG: Invalid configuration

      - ESP_ERR_NO_MEM: Memory allocation failed

      - Other error codes: Stack-specific errors

  void (*server_session_ticket_ctx_free)(void *user_ctx, void *cfg)

    Free server session ticket context (optional, for server session ticket support)

    This function frees resources associated with the server session ticket context.

    Note

    This should free all memory and clear sensitive data (encryption keys).

    Note

    This is only used if CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is enabled.

    Note

    Can be NULL if server session tickets are not supported by the stack.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param cfg:

      Pointer to esp_tls_server_session_ticket_ctx_t structure to free

  int (*server_session_create)(void *user_ctx, esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls)

    Create server session (optional, server-side only)

    This function creates a complete TLS server session, performing initialization and handshake in a blocking manner. This is a convenience function that combines server_session_init() and server_session_continue_async().

    Note

    This function should handle the complete handshake internally.

    Note

    For non-blocking operation, use server_session_init() + server_session_continue_async() instead.

    Note

    This is optional - if NULL, ESP-TLS will use server_session_init() + server_session_continue_async().

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param cfg:

      Server configuration (esp_tls_cfg_server_t)

    Param sockfd:

      Socket file descriptor (already connected)

    Param tls:

      TLS context (already allocated)

    Return:

      - 1: Server session created successfully, handshake completed

      - 0: Should not happen (this is a blocking function)

      - ESP_TLS_ERR_SSL_WANT_READ: Need to read more data (should retry)

      - ESP_TLS_ERR_SSL_WANT_WRITE: Need to write more data (should retry)

      - Negative value: Error occurred

  esp_err_t (*server_session_init)(void *user_ctx, esp_tls_cfg_server_t *cfg, int sockfd, esp_tls_t *tls)

    Initialize server session (optional, server-side only)

    This function initializes a TLS server session. It should:

    - Set up the TLS context for server mode

    - Configure server certificates and keys from cfg

    - Prepare for handshake (but don't perform it yet)

    - Set tls->read and tls->write callbacks

    Note

    After this, call server_session_continue_async() to perform the handshake.

    Note

    This is optional - if NULL, server_session_create() must be implemented.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param cfg:

      Server configuration (esp_tls_cfg_server_t)

    Param sockfd:

      Socket file descriptor (already connected)

    Param tls:

      TLS context (already allocated)

    Return:

      - ESP_OK: Server session initialized successfully

      - ESP_ERR_INVALID_ARG: Invalid configuration

      - ESP_ERR_NO_MEM: Memory allocation failed

      - Other error codes: Stack-specific errors

  int (*server_session_continue_async)(void *user_ctx, esp_tls_t *tls)

    Continue async server session handshake (optional, server-side only)

    This function continues the TLS handshake for a server session initialized with server_session_init(). It should be called repeatedly until it returns 0.

    Note

    This should be called in a loop until it returns 0 or a negative error.

    Note

    The ESP-TLS layer handles the looping and timeout management.

    Note

    This is optional - if NULL, server_session_create() must be implemented.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param tls:

      TLS context (initialized by server_session_init)

    Return:

      - 0: Handshake completed successfully

      - ESP_TLS_ERR_SSL_WANT_READ: Need to read more data from client, call again later

      - ESP_TLS_ERR_SSL_WANT_WRITE: Need to write data to client, call again later

      - Negative value: Handshake failed (error code)

  void (*server_session_delete)(void *user_ctx, esp_tls_t *tls)

    Delete server session (optional, server-side only)

    This function cleans up a server TLS session. It should:

    - Close the TLS session

    - Free any server-specific resources

    - Note: tls->sockfd is closed separately, don't close it here

    Note

    This is similar to conn_delete() but may have server-specific cleanup.

    Note

    If NULL, conn_delete() will be used instead.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param tls:

      TLS context to clean up

  int (*crypto_sha1)(void *user_ctx, const unsigned char *input, size_t ilen, unsigned char output[20])

    Calculate SHA1 hash (optional, for esp_crypto_sha1 API)

    This function calculates the SHA1 hash of the input data. It is used by esp_crypto_sha1() API which is needed by components like esp_http_server for WebSocket key calculation.

    Note

    If NULL, esp_crypto_sha1() API calls will fail. This callback must be implemented if your application or any dependent component (e.g., esp_http_server for WebSocket) uses the esp_crypto_sha1() API.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param input:

      Input data buffer

    Param ilen:

      Length of input data

    Param output:

      Output buffer for SHA1 hash (must be at least 20 bytes)

    Return:

      - 0: Success

      - Negative value: Error occurred

  int (*crypto_base64_encode)(void *user_ctx, unsigned char *dst, size_t dlen, size_t *olen, const unsigned char *src, size_t slen)

    Base64 encode data (optional, for esp_crypto_base64_encode API)

    This function performs Base64 encoding of the source data. It is used by esp_crypto_base64_encode() API which is needed by components like esp_http_server for WebSocket key encoding.

    Note

    If NULL, esp_crypto_base64_encode() API calls will fail. This callback must be implemented if your application or any dependent component (e.g., esp_http_server for WebSocket) uses the esp_crypto_base64_encode() API.

    Param user_ctx:

      User context pointer passed to esp_tls_register_stack()

    Param dst:

      Destination buffer for encoded data

    Param dlen:

      Size of destination buffer

    Param olen:

      Pointer to store the number of bytes written

    Param src:

      Source data buffer

    Param slen:

      Length of source data

    Return:

      - 0: Success

      - -0x002A: Buffer too small

      - Other negative value: Error occurred

### Macros

ESP_TLS_STACK_OPS_VERSION

  Version of the TLS stack operations structure.

  This version number must be set in the `version` field of esp_tls_stack_ops_t when registering a custom TLS stack. It allows ESP-TLS to detect incompatible interface changes between ESP-IDF versions and custom stack implementations.

### Type Definitions

typedef struct esp_tls_stack_ops esp_tls_stack_ops_t

  TLS stack operations vtable.

  This structure defines the interface that external TLS stack implementations must provide. All function pointers must be non-NULL.

  Note

  To register a custom TLS stack:

  1. Enable CONFIG_ESP_TLS_CUSTOM_STACK in menuconfig

  2. Implement all required functions in this structure

  3. Call esp_tls_register_stack() with your implementation before creating any TLS connections

  Note

  The TLS context (esp_tls_t) is managed by ESP-TLS. Your implementation should store stack-specific data in the appropriate fields of esp_tls_t (e.g., priv_ctx, priv_ssl) or allocate additional memory and store a pointer to it.

  Note

  For client connections: hostname and cfg (esp_tls_cfg_t) are provided

  Note

  For server connections: hostname is NULL, cfg is esp_tls_cfg_server_t, server_params is provided

Was this page helpful?

- Thank you! We received your feedback.
- If you have any comments, fill in Espressif Documentation Feedback Form.

- We value your feedback.
- Let us know how we can improve this page by filling in Espressif Documentation Feedback Form.