# HTTPS Server

[中文]

## Overview

This component is built on top of HTTP Server. The HTTPS server takes advantage of hook registration functions in the regular HTTP server to provide callback function for SSL session.

All documentation for HTTP Server applies also to a server you create this way.

## Used APIs

The following APIs of HTTP Server should not be used with HTTPS Server, as they are used internally to handle secure sessions and to maintain internal state:

- "send", "receive" and "pending" callback registration functions - secure socket handling

  - `httpd_sess_set_send_override()`

  - `httpd_sess_set_recv_override()`

  - `httpd_sess_set_pending_override()`

- "transport context" - both global and session

  - `httpd_sess_get_transport_ctx()` - returns SSL used for the session

  - `httpd_sess_set_transport_ctx()`

  - `httpd_get_global_transport_ctx()` - returns the shared SSL context

  - `httpd_config::global_transport_ctx`

  - `httpd_config::global_transport_ctx_free_fn`

  - `httpd_config::open_fn` - used to set up secure sockets

Everything else can be used without limitations.

## Usage

Please see the example protocols/https_server to learn how to set up a secure server.

Basically, all you need is to generate a certificate, embed it into the firmware, and pass the init struct into the start function after the certificate address and lengths are correctly configured in the init struct.

The server can be started with or without SSL by changing a flag in the init struct - `httpd_ssl_config::transport_mode`. This could be used, e.g., for testing or in trusted environments where you prefer speed over security.

## Performance

The initial session setup can take about two seconds, or more with slower clock speed or more verbose logging. Subsequent requests through the open secure socket are much faster (down to under 100 ms).

## Event Handling

ESP HTTPS Server has various events for which a handler can be triggered by the Event Loop Library when the particular event occurs. The handler has to be registered using `esp_event_handler_register()`. This helps in event handling for ESP HTTPS Server.

`esp_https_server_event_id_t` has all the events which can happen for ESP HTTPS server.

Expected data type for different ESP HTTPS server events in event loop:

> - HTTPS_SERVER_EVENT_ERROR : `esp_https_server_last_error_t`

> - HTTPS_SERVER_EVENT_START : `NULL`

> - HTTPS_SERVER_EVENT_ON_CONNECTED : `NULL`

> - HTTPS_SERVER_EVENT_ON_DATA : `int`

> - HTTPS_SERVER_EVENT_SENT_DATA : `NULL`

> - HTTPS_SERVER_EVENT_DISCONNECTED : `NULL`

> - HTTPS_SERVER_EVENT_STOP : `NULL`

## Application Examples

- protocols/https_server/simple demonstrates how to create an HTTPS server that returns a simple HTML page when visited.

- protocols/https_server/wss_server demonstrates how to create an SSL server with a simple WebSocket request handler that supports handling multiple clients, PING-PONG mechanism, and sending asynchronous messages to all clients.

## HTTPS Server Cert Selection Hook

The ESP HTTPS Server component provides an option to set the server certification selection hook. This feature allows you 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_HTTPS_SERVER_CERT_SELECT_HOOK in the ESP HTTPS Server menuconfig. Please note that the ESP-TLS option is only available when Mbedtls is used as the TLS stack for ESP-TLS (default behaviour).

When enabled, you can set the certificate selection callback using the `httpd_ssl_config::cert_select_cb` member of the `httpd_ssl_config_t` structure.

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

      httpd_ssl_config_t cfg = {
          cert_select_cb = cert_section_callback,
      };

## API Reference

### Header File

- components/esp_https_server/include/esp_https_server.h

- This header file can be included with:

  >     #include "esp_https_server.h"

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

  >     REQUIRES esp_https_server

  > or

  >     PRIV_REQUIRES esp_https_server

### Functions

esp_err_t httpd_ssl_start(httpd_handle_t *handle, httpd_ssl_config_t *config)

  Create a SSL capable HTTP server (secure mode may be disabled in config)

  Parameters:

    - config -- [inout] - server config, must not be const. Does not have to stay valid after calling this function.

    - handle -- [out] - storage for the server handle, must be a valid pointer

  Returns:

    success

esp_err_t httpd_ssl_stop(httpd_handle_t handle)

  Stop the server. Blocks until the server is shut down.

  Parameters:

    handle -- [in]

  Returns:

    - ESP_OK: Server stopped successfully

    - ESP_ERR_INVALID_ARG: Invalid argument

    - ESP_FAIL: Failure to shut down server

### Structures

struct esp_https_server_user_cb_arg

  Callback data struct, contains the ESP-TLS connection handle and the connection state at which the callback is executed.

  Public Members

  httpd_ssl_user_cb_state_t user_cb_state

    State of user callback

  esp_tls_t *tls

    ESP-TLS connection handle

struct httpd_ssl_config

  HTTPS server config struct

  Please use HTTPD_SSL_CONFIG_DEFAULT() to initialize it.

  Public Members

  httpd_config_t httpd

    Underlying HTTPD server config

    Parameters like task stack size and priority can be adjusted here.

  const uint8_t *servercert

    Server certificate

  size_t servercert_len

    Server certificate byte length

  const uint8_t *cacert_pem

    CA certificate ((CA used to sign clients, or client cert itself)

  size_t cacert_len

    CA certificate byte length

  const uint8_t *prvtkey_pem

    Private key

  size_t prvtkey_len

    Private key byte length

  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)

  httpd_ssl_transport_mode_t transport_mode

    Transport Mode (default secure)

  uint16_t port_secure

    Port used when transport mode is secure (default 443)

  uint16_t port_insecure

    Port used when transport mode is insecure (default 80)

  bool session_tickets

    Enable tls session tickets

  bool use_secure_element

    Enable secure element for server session

  esp_https_server_user_cb *user_cb

    User callback for esp_https_server

  void *ssl_userdata

    User data to add to the ssl context

  esp_https_server_cert_select_cb cert_select_cb

    Certificate selection callback to use. The callback is only applicable when CONFIG_ESP_HTTPS_SERVER_CERT_SELECT_HOOK is enabled in menuconfig

  const char **alpn_protos

    Application protocols the server supports in order of preference. Used for negotiating during the TLS handshake, first one the client supports is selected. The data structure must live as long as the https server itself

  uint32_t tls_handshake_timeout_ms

    TLS handshake timeout in milliseconds, default timeout is 10 seconds if not set

### Macros

HTTPD_SSL_CONFIG_DEFAULT()

  Default config struct init Notes:

  - port is set when starting the server, according to 'transport_mode'

  - one socket uses ~ 40kB RAM with SSL, we reduce the default socket count to 4

  - SSL sockets are usually long-lived, closing LRU prevents pool exhaustion DOS

  - Stack size may need adjustments depending on the user application

### Type Definitions

typedef esp_tls_handshake_callback esp_https_server_cert_select_cb

typedef struct esp_https_server_user_cb_arg esp_https_server_user_cb_arg_t

  Callback data struct, contains the ESP-TLS connection handle and the connection state at which the callback is executed.

typedef esp_tls_last_error_t esp_https_server_last_error_t

typedef void esp_https_server_user_cb(esp_https_server_user_cb_arg_t *user_cb)

  Callback function prototype Can be used to get connection or client information (SSL context) E.g. Client certificate, Socket FD, Connection state, etc.

  Param user_cb:

    Callback data struct

typedef struct httpd_ssl_config httpd_ssl_config_t

### Enumerations

enum esp_https_server_event_id_t

  Values:

  enumerator HTTPS_SERVER_EVENT_ERROR

    This event occurs when there are any errors during execution

  enumerator HTTPS_SERVER_EVENT_START

    This event occurs when HTTPS Server is started

  enumerator HTTPS_SERVER_EVENT_ON_CONNECTED

    Once the HTTPS Server has been connected to the client

  enumerator HTTPS_SERVER_EVENT_ON_DATA

    Occurs when receiving data from the client

  enumerator HTTPS_SERVER_EVENT_SENT_DATA

    Occurs when an ESP HTTPS server sends data to the client

  enumerator HTTPS_SERVER_EVENT_DISCONNECTED

    The connection has been disconnected

  enumerator HTTPS_SERVER_EVENT_STOP

    This event occurs when HTTPS Server is stopped

enum httpd_ssl_transport_mode_t

  Values:

  enumerator HTTPD_SSL_TRANSPORT_SECURE
  enumerator HTTPD_SSL_TRANSPORT_INSECURE

enum httpd_ssl_user_cb_state_t

  Indicates the state at which the user callback is executed, i.e at session creation or session close.

  Values:

  enumerator HTTPD_SSL_USER_CB_SESS_CREATE
  enumerator HTTPD_SSL_USER_CB_SESS_CLOSE

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.