# ESP-TLS

[English]

## 概述

ESP-TLS 组件提供简化 API 接口，用于访问常用 TLS 功能，支持如 CA 认证验证、SNI、ALPN 协商和非阻塞连接等常见场景，相关配置可在数据结构体 `esp_tls_cfg_t` 中指定。配置完成后，使用以下 API 进行 TLS 通信：

> - `esp_tls_init()`：初始化 TLS 连接句柄。

> - `esp_tls_conn_new_sync()`：开启新的阻塞式 TLS 连接。

> - `esp_tls_conn_new_async()`：开启新的非阻塞式 TLS 连接。

> - `esp_tls_conn_read()`：读取 TLS 层之上的应用数据。

> - `esp_tls_conn_write()`：将应用数据写入 TLS 连接。

> - `esp_tls_conn_destroy()`：释放连接。

任何应用层协议，如 HTTP1、HTTP2 等，均可调用 ESP-TLS 组件接口实现。

## 应用示例

使用 ESP-TLS 建立安全套接字连接的 HTTPS 简单示例，请参阅 protocols/https_request。

## ESP-TLS 组件的树形结构

    ├── 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

ESP-TLS 组件文件 esp-tls/esp_tls.h 包含该组件的公共 API 头文件。在 ESP-TLS 组件内部，默认使用 MbedTLS 作为底层 SSL/TLS 库，也可以通过 `esp_tls_register_stack()` API 注册自定义 TLS 协议栈。与 MbedTLS 相关的 API 存放在 esp-tls/private_include/esp_tls_mbedtls.h，自定义协议栈注册相关的 API 存放在 esp-tls/esp_tls_custom_stack.h。

## TLS 服务器验证

ESP-TLS 在客户端提供了多种验证 TLS 服务器的选项，如验证对端服务器的服务器证书、或使用预共享密钥验证服务器。用户应在 `esp_tls_cfg_t` 结构体中选择以下任一选项完成 TLS 服务器验证，若未做选择，则客户端默认在 TLS 连接创建时，会返回错误。

> - cacert_buf 和 cacert_bytes：以缓冲区的形式向 `esp_tls_cfg_t` 结构体提供 CA 证书，ESP-TLS 将使用缓冲区中的 CA 证书验证服务器。注意，须在 `esp_tls_cfg_t` 结构体中设置以下变量：

>   > - `cacert_buf` - 指针，指向包含 CA 证书的缓冲区。

>   > - `cacert_bytes` - CA 证书大小（以字节为单位）。

> - use_global_ca_store： `global_ca_store` 可一次性完成初始化及设置，并用于验证 ESP-TLS 连接的服务器，注意需要在这些服务器各自的 `esp_tls_cfg_t` 结构体中设置 `use_global_ca_store = true`。有关初始化和设置 `global_ca_store` 的不同 API，请参阅文末的 API 参考。

> - crt_bundle_attach：ESP x509 证书包 API 提供了便捷的服务器验证方法，即打包一组自定义的 x509 根证书，用于 TLS 服务器验证，详情请参阅 ESP x509 证书包。

> - psk_hint_key：要使用预共享密钥验证服务器，必须在 ESP-TLS menuconfig 中启用 CONFIG_ESP_TLS_PSK_VERIFICATION，然后向结构体 `esp_tls_cfg_t` 提供指向 PSK 提示和密钥的指针。若未选择有关服务器验证的其他选项，ESP-TLS 将仅用 PSK 验证服务器。

> - 跳过服务器验证：该选项并不安全，仅供测试使用。在 ESP-TLS menuconfig 中启用 CONFIG_ESP_TLS_INSECURE 和 CONFIG_ESP_TLS_SKIP_SERVER_CERT_VERIFY 可启用该选项，此时，若未在 `esp_tls_cfg_t` 结构体选择其他服务器验证选项，ESP-TLS 将默认跳过服务器验证。

>   警告

>   启用 跳过服务器验证 选项存在潜在风险，若未通过 API 或 `ca_store` 等其他机制提供服务器证书，可能导致设备与伪造身份的服务器建立 TLS 连接。

## SNI（服务器名称指示）

SNI 是 TLS 协议的一个扩展，它能让客户端在 TLS 握手过程中，主动指定要连接的主机名。当服务器通过同一个 IP 地址托管多个域名时，客户端必须使用这一功能才能成功建立连接。

如何确保 SNI 正常工作：

- 使用 HTTPS 连接时，ESP-TLS 默认启用 SNI，无需额外配置。

- 若需手动指定 SNI 主机名，请使用 `esp_tls_cfg_t` 中的 `common_name` 字段进行设置，确保在握手过程中向服务器发送正确的主机名。

- `common_name` 的值必须与服务器证书中的通用名称 (CN, Common Name) 完全匹配。

- 需将 `skip_common_name` 字段设置为 `false`，确保服务器证书能通过主机名完成正确验证。这是 SNI 正常运行的必要条件。

示例：

    esp_tls_cfg_t cfg = {
        .cacert_buf = ...,
        .cacert_bytes = ...,
        .common_name = "example.com", // SNI 主机名
        .skip_common_name = false,    // 确保证书验证无误
    };

## ESP-TLS 服务器证书选择回调

使用 MbedTLS 协议栈时，ESP-TLS 组件支持设置服务器证书选择回调函数。此时，在服务器握手期间可选择使用哪个服务器证书，该回调可获取客户端发送的 "Client Hello" 消息中提供的 TLS 扩展（ALPN、SPI 等），并基于此选择传输哪个服务器证书给客户端。要启用此功能，请在 ESP-TLS menuconfig 中启用 CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK。

证书选择回调可在结构体 `esp_tls_cfg_t` 中配置，具体如下：

    int cert_selection_callback(mbedtls_ssl_context *ssl)
    {
        /* 回调应执行的代码 */
        return 0;
    }

    esp_tls_cfg_t cfg = {
        cert_select_cb = cert_section_callback,
    };

## 自定义 TLS 协议栈支持

ESP-TLS 组件支持通过 `esp_tls_register_stack()` API 注册自定义 TLS 协议栈实现。这允许外部组件通过实现 `esp_tls_stack_ops_t` 接口来提供自己的 TLS 协议栈实现。注册后，所有在此之后创建的 TLS 连接都将使用自定义协议栈。

备注

由于自定义协议栈的实现封装在 ESP-TLS 内部，因此切换为自定义协议栈并不会影响项目中与 ESP-TLS 相关的代码。

## 在 ESP-IDF 中使用自定义 TLS 协议栈

要在工程中使用自定义 TLS 协议栈，请遵循以下步骤：

1. 在 menuconfig 中启用自定义协议栈选项 `CONFIG_ESP_TLS_CUSTOM_STACK` (Component config > ESP-TLS > SSL/TLS Library > Custom TLS stack)。

2. 实现 `esp_tls_stack_ops_t` 结构中定义的所有必需函数。必需函数包括：

   - `create_ssl_handle` - 为新连接初始化 TLS/SSL 上下文

   - `handshake` - 执行 TLS 握手

   - `read` - 从 TLS 连接读取已解密的数据

   - `write` - 向 TLS 连接写入数据，并在发送前完成加密

   - `conn_delete` - 清理 TLS 连接并释放相关资源

   - `net_init` - 初始化网络上下文

   - `get_ssl_context` - 获取协议栈特定的 SSL 上下文

   - `get_bytes_avail` - 获取可用于读取的字节数

   - `init_global_ca_store` - 初始化全局 CA 证书存储

   - `set_global_ca_store` - 将 CA 证书加载到全局存储

   - `get_global_ca_store` - 获取全局 CA 证书存储

   - `free_global_ca_store` - 释放全局 CA 证书存储

   - `get_ciphersuites_list` - 获取支持的密码套件列表

   可选函数（如果不支持，可以为 NULL）：

   - `get_client_session` - 获取客户端会话票据（须启用 CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS）

   - `free_client_session` - 释放客户端会话（须启用 CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS）

   - `server_session_ticket_ctx_init` - 初始化服务器会话票据上下文（须启用 CONFIG_ESP_TLS_SERVER_SESSION_TICKETS）

   - `server_session_ticket_ctx_free` - 释放服务器会话票据上下文（须启用 CONFIG_ESP_TLS_SERVER_SESSION_TICKETS）

   - `server_session_create` - 创建服务器会话（服务器端，如果提供了 server_session_init，该接口可以为 NULL）

   - `server_session_init` - 初始化服务器会话（服务器端，如果提供了 server_session_create，该接口可以为 NULL）

   - `server_session_continue_async` - 继续服务器端的异步握手（服务器端，如果提供了 server_session_create，该接口可以为 NULL）

   - `server_session_delete` - 删除服务器会话（服务器端，该接口可以为 NULL，此时将使用 `conn_delete` 进行清理）

3. 创建一个包含函数实现的静态/全局结构体：

       #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,
           // 可选函数如果不支持可以为 NULL
           .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. 在创建任何 TLS 连接之前注册自定义协议栈：

       void app_main(void) {
           // 第二个参数是传递给全局回调函数的用户上下文
           //（如 init_global_ca_store，set_global_ca_store 等）。
           // 如果不需要可以传 NULL，对于 C++ 实现则传递相应的指针
           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;
           }

           // 现在所有 TLS 连接都将使用你的自定义协议栈
           // ... 像往常一样使用 esp_tls_conn_new() 等创建 TLS 连接 ...
       }

重要

- 必须在创建任何 TLS 连接 之前 注册自定义协议栈。在创建 TLS 连接后调用 `esp_tls_register_stack()` 不会影响现有连接。

- `esp_tls_stack_ops_t` 结构必须指向静态或全局结构体（不在栈上），因为系统会以引用方式存储该结构体。

- 你的实现应将协议栈特定的上下文数据存储在 `esp_tls_t` 结构的 `priv_ctx` 和 `priv_ssl` 字段中。

- 所有必需函数的指针必须为非 NULL。可选函数如果不支持可以为 NULL。

- 注册函数只能调用一次。后续调用将返回 `ESP_ERR_INVALID_STATE`。

- 更多函数签名和要求，请参阅 esp-tls/esp_tls_custom_stack.h。

## ESP-TLS 中的 ATECC608A（安全元件）

ESP-TLS 支持在 ESP32 系列芯片上使用 ATECC608A 加密芯片，但必须将 MbedTLS 作为 ESP-TLS 的底层 SSL/TLS 协议栈。未经手动更改，ESP-TLS 默认以 MbedTLS 为其底层 TLS/SSL 协议栈。

备注

在 ESP32 系列上的 ATECC608A 芯片必须预先配置，详情请参阅 esp_cryptoauth_utility。

要启用安全元件支持，并将其应用于工程 TLS 连接，请遵循以下步骤：

1. 在工程中添加 esp-cryptoauthlib，详情请参阅 如何在 ESP-IDF 中使用 esp-cryptoauthlib。

2. 启用 menuconfig 选项 CONFIG_ESP_TLS_USE_SECURE_ELEMENT：

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

3. 选择 ATECC608A 芯片类型：

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

   如需了解更多 ATECC608A 芯片类型，或需了解如何获取连接到特定 ESP 模块的 ATECC608A 芯片类型，请参阅 ATECC608A 芯片类型。

4. 在 `esp_tls_cfg_t` 中提供以下配置，在 ESP-TLS 中启用 ATECC608A：

       esp_tls_cfg_t cfg = {
           /* 其他配置选项 */
           .use_secure_element = true,
       };

## ESP-TLS 的数字签名

ESP-TLS 支持在 ESP32-H2 中使用数字签名 (DS)，但只有当 ESP-TLS 以 MbedTLS（默认协议栈）为底层 SSL/TLS 协议栈时，才支持使用 TLS 的数字签名。有关数字签名的详细信息，请参阅 数字签名 (DS)。有关数字签名的技术细节（例如私钥参数计算），请参阅 ESP32-H2 技术参考手册 > 数字签名 (DS) [PDF]。在使用数字签名前，应预先配置数字签名外设，请参阅 TLS 连接所需的 DS 外设配置。

数字签名外设必须用所需的加密私钥参数初始化，相应参数在配置数字签名外设时获取。具备所需的数字签名上下文，即数字签名参数时，ESP-TLS 会在内部初始化数字签名外设。要将数字签名上下文传递给 ESP-TLS 上下文，请参阅以下代码段。注意，在删除 TLS 连接之前，不应释放传递给 ESP-TLS 上下文的数字签名上下文。

    #include "esp_tls.h"
    esp_ds_data_ctx_t *ds_ctx;
    /* 使用加密的私钥参数初始化 ds_ctx，这类参数可以从 nvs 中读取，或由应用程序代码提供 */
    esp_tls_cfg_t cfg = {
        .clientcert_buf = /* 客户端证书 */,
        .clientcert_bytes = /* 客户端证书长度 */,
        /* 其他配置选项 */
        .ds_data = (void *)ds_ctx,
    };

备注

当使用数字签名进行 TLS 连接时，除其他必要参数外，仅需提供客户端证书 (`clientcert_buf`) 和数字签名参数 (`ds_data`) ，此时可将客户端密钥 (`clientkey_buf`) 设置为 NULL。

- 现有一个基于 DS 外设的双向认证示例，已随独立的 espressif/mqtt 组件一同提供，其内部依赖 ESP-TLS 建立 TLS 连接。请参照组件文档获取并构建该示例。

## 在 ESP-TLS 中使用 ECDSA 外设

ESP-TLS 支持在 ESP32-H2 中使用 ECDSA 外设。使用 ECDSA 外设时，ESP-TLS 必须与 MbedTLS 一起作为底层 SSL/TLS 协议栈，并且 ECDSA 的私钥应存储在 eFuse 中。请参考 ECDSA 指南，了解如何在 eFuse 中烧写 ECDSA 密钥。

这样就可以使用 ECDSA 外设进行私钥操作。由于客户私钥已经存储在 eFuse 中，因此无需将其传递给 `esp_tls_cfg_t`。

    #include "esp_tls.h"
    esp_tls_cfg_t cfg = {
        .use_ecdsa_peripheral = true,
        .ecdsa_key_efuse_blk = 4,    // ECDSA 密钥的低 eFuse 块
        .ecdsa_key_efuse_blk_high = 5,   // ECDSA 密钥的高 eFuse 块（仅 SECP384R1）
        .ecdsa_curve = ESP_TLS_ECDSA_CURVE_SECP384R1, // 设置为 ESP_TLS_ECDSA_CURVE_SECP256R1 以使用 SECP256R1 曲线
    };

备注

在 TLS 中使用 ECDSA 外设时，只支持 `MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256` 密码套件。如果使用 TLS v1.3，则支持 `MBEDTLS_TLS1_3_AES_128_GCM_SHA256` 密码套件。

## 客户端会话票据

ESP-TLS 支持客户端会话恢复，可以在后续与同一服务器连接时避免完整的 TLS 握手，节省时间和资源。该功能在 ESP-TLS 使用 MbedTLS 作为底层协议栈时可用。

会话恢复机制在不同 TLS 版本中略有差异：

- TLS 1.2：通过会话 ID（由 TLS 协议栈内部管理）或会话票据（参见 RFC 5077）实现会话恢复。ESP-TLS 主要采用会话票据机制，从而显式控制应用程序。

- TLS 1.3：会话恢复完全依赖会话票据实现。服务器会在主握手完成后，通过 "NewSessionTicket" 消息发送票据。与 TLS 1.2 不同，这些票据可以在会话期间的任意时刻发送，无需在握手后立即完成。

要启用和使用客户端会话票据的步骤如下：

1. 启用 Kconfig 选项 CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS。

2. 在成功建立 TLS 连接（并完成握手）后，使用 `esp_tls_get_client_session()` 获取会话票据。

   > - 对于 TLS 1.3：会话票据可能在握手后由服务器随时发送，因此应用程序应定期或在特定的应用层交互之后调用 `esp_tls_get_client_session()`，确保获取最新的票据。TLS 协议栈接收并处理的每个新票据都会覆盖之前的票据，用于后续的会话恢复。

3. 将此会话票据安全地存储起来。

4. 后续连接同一服务器时，将存储的会话票据填入 `esp_tls_cfg_t::client_session` 字段。

5. 在不再需要客户端会话或获取新会话前，应调用 `esp_tls_free_client_session()` 释放客户端会话上下文。

    #include "esp_tls.h"

    // 全局或持久存储客户端会话
    esp_tls_client_session_t *saved_session = NULL;

    void connect_to_server(bool use_saved_session_arg) {
        esp_tls_cfg_t cfg = {0}; // 按需初始化配置参数
        // ... 设置其他 cfg 成员，如 cacert_buf, common_name 等

        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.");

            // 每次连接成功后，都要尝试获取/更新最新的会话票据。
            // 无论本次是新握手还是通过会话恢复连接，更新票据都是有益的。
            // 特别是对 TLS 1.3 而言，服务器可能会在握手完成后下发新票据。
            if (saved_session) {
                esp_tls_free_client_session(saved_session); // 释放之前的票据
                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.");
            }

            // 执行 TLS 通信...

        }
        esp_tls_conn_destroy(tls);
    }

备注

- 从服务器获取的会话票据通常有有效期，期限由服务器决定。

- 当尝试使用存储的票据进行连接时，如果服务器判定该票据无效（例如过期或被拒绝），ESP-TLS 会自动尝试执行完整的 TLS 握手来建立连接。在这种情况下，应用程序无需实现额外的重试逻辑。只有当会话恢复和后续的完整握手均失败时，才会报告连接失败。

- 当不再需要 `esp_tls_client_session_t` 上下文时，或在获取并存储新的会话票据前，应调用 `esp_tls_free_client_session()` 释放会话。

- 对于 TLS 1.3，服务器在一次连接中可能多次发送新会话票据 NewSessionTicket。每次成功调用 `esp_tls_get_client_session()` 都会返回由底层 TLS 协议栈处理的最新票据上下文。如果应用程序要使用最新的票据进行会话恢复，则需由应用程序负责管理并更新其存储的会话信息。

## TLS 加密套件

ESP-TLS 支持在客户端模式下设置加密套件列表，TLS 密码套件列表用于向服务器传递所支持的密码套件信息，用户可以根据自己需求增减加密套件，且适用于任何 TLS 协议栈配置。如果服务器支持列表中的任一密码套件，则 TLS 连接成功，反之连接失败。

连接客户端时，在 `esp_tls_cfg_t` 结构体中设置 `ciphersuites_list` 的步骤如下：

    /* 加密套件列表必须以 0 结尾，并且在整个 TLS 连接期间，加密套件的内存地址空间有效 */
    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 不会检查 `ciphersuites_list` 的有效性，因此需调用 `esp_tls_get_ciphersuites_list()` 获取 TLS 协议栈中支持的加密套件列表，并检查设置的加密套件是否在支持的加密套件列表中。

备注

此功能仅在 MbedTLS 协议栈中有效。

## TLS 协议版本

ESP-TLS 能够为 TLS 连接设置相应的 TLS 协议版本，指定版本将用于建立专用 TLS 连接。也就是说，在运行时不同的 TLS 连接可以配置到 TLS 1.2、TLS 1.3 等不同协议版本。

备注

目前，仅在 MbedTLS 作为 ESP-TLS 的底层 SSL/TLS 协议栈时支持此功能。

要在 ESP-TLS 中设置 TLS 协议版本，请设置 `esp_tls_cfg_t::tls_version`，从 `esp_tls_proto_ver_t` 中选择所需版本。如未指定协议版本字段，将默认根据服务器要求建立 TLS 连接。

ESP-TLS 连接的协议版本可按如下方式配置：

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

## API 参考

### 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.

  参数:

    cfg -- [in] server configuration as esp_tls_cfg_server_t

  返回:

    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.

  参数:

    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.

  返回:

    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.

  备注

  The cfg->timeout_ms parameter controls the connection timeout:

  - timeout_ms > 0: The connection attempt will be aborted if it does not complete within the specified duration.

  - timeout_ms <= 0: No application-level timeout is applied. The connection relies on the underlying socket timeout (ESP_TLS_DEFAULT_CONN_TIMEOUT). On timeout, the function returns -1 and records ESP_ERR_ESP_TLS_CONNECTION_TIMEOUT in the error handle.

  参数:

    - 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.

  返回:

    - -1 If connection establishment fails (including timeout).

    - 1 If connection establishment is successful.

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.

  参数:

    - 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.

  返回:

    - -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.

  参数:

    - 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.

  返回:

    - -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.

  参数:

    - url -- [in] url of host.

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

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

  返回:

    - -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.

  参数:

    - 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.

  返回:

    - >=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'.

  参数:

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

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

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

  返回:

    - >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.

  参数:

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

  返回:

    - 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.

  参数:

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

  返回:

    - -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.

  参数:

    - tls -- [in] handle to esp_tls context

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

  返回:

    - 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.

  参数:

    - tls -- [in] handle to esp_tls context

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

  返回:

    - 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.

  参数:

    - tls -- [in] handle to esp_tls context

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

  返回:

    - 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.

  参数:

    - tls -- [in] handle to esp_tls context

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

  返回:

    - 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.

  参数:

    tls -- [in] handle to esp_tls context

  返回:

    - 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().

  返回:

    - 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().

  参数:

    - 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.

  返回:

    - 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.

  参数:

    - 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

  返回:

    - 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.

  参数:

    - 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

  返回:

    - 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.

  参数:

    - tls -- [in] handle to esp_tls context

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

  返回:

    - 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.

  备注

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

  返回:

    - 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

  返回:

    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.

  参数:

    - cfg -- [in] Pointer to esp_tls_cfg_server_t

    - sockfd -- [in] FD of accepted connection

    - tls -- [out] Pointer to allocated esp_tls_t

  返回:

    - 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();

  参数:

    tls -- [in] pointer to esp_tls_t

  返回:

    - 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

  参数:

    - cfg -- [in] Pointer to esp_tls_cfg_server_t

    - sockfd -- [in] FD of accepted connection

    - tls -- [out] Pointer to allocated esp_tls_t

  返回:

    - 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()

  参数:

    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.

  参数:

    - 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

  返回:

    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 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

    When true, esp-tls skips the call to mbedtls_ssl_set_hostname(). This disables BOTH server-hostname matching against the certificate (CN/SAN) and Server Name Indication (SNI), not just the legacy CN field. Only set on loopback / debug clients that can tolerate the loss of hostname authentication. Must be 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 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

  备注

  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 ...
      }

  备注

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

  备注

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

  备注

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

  备注

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

  备注

  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.

  参数:

    - 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.

  返回:

    - 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.

  备注

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

  备注

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

  返回:

    - 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.

  返回:

    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.

  备注

  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

  备注

  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.

  备注

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

  备注

  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

    备注

    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

    备注

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

    备注

    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

    备注

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

    备注

    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

    备注

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

    备注

    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

    备注

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

    备注

    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.

    备注

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

    备注

    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.

    备注

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

    备注

    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.

    备注

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

    备注

    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.

    备注

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

    备注

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

    备注

    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.

    备注

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

    备注

    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.

    备注

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

    备注

    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.

    备注

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

    备注

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

    备注

    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).

    备注

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

    备注

    This is only used if CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is enabled.

    备注

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

    备注

    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().

    备注

    This should free all memory associated with the session.

    备注

    This is only used if CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is enabled.

    备注

    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).

    备注

    This is called when setting up server session tickets.

    备注

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

    备注

    This is only used if CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is enabled.

    备注

    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.

    备注

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

    备注

    This is only used if CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is enabled.

    备注

    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().

    备注

    This function should handle the complete handshake internally.

    备注

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

    备注

    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

    备注

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

    备注

    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.

    备注

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

    备注

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

    备注

    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

    备注

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

    备注

    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.

    备注

    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.

    备注

    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.

  备注

  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

  备注

  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.

  备注

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

  备注

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

此文档对您有帮助吗？

- 反馈已收到，谢谢！
- 如果您有其他意见，欢迎填写乐鑫文档反馈表。

- 我们重视您的反馈。
- 您可以填写乐鑫文档反馈表告诉我们如何改进该文档。