net: lib: http_server: add option to use ALPN

Web browsers don't support HTTP Upgrade mechanism to upgrade to HTTP2.
Instead, HTTP2 is supported only over TLS, and ALPN is used to negotiate
the protocol to be used.

This commit adds the supported HTTP protocols to the ALPN list, so that
web browsers can use HTTP2 with the server.

Signed-off-by: Matt Rodgers <mrodgers@witekio.com>
This commit is contained in:
Matt Rodgers 2024-08-30 11:11:11 +01:00 committed by Anas Nashif
parent d4da23e3c3
commit 2eda6df48a
2 changed files with 23 additions and 1 deletions

View File

@ -179,6 +179,15 @@ config HTTP_SERVER_RESTART_DELAY
allow any existing connections to finalize to avoid binding errors
during initialization.
config HTTP_SERVER_TLS_USE_ALPN
bool "ALPN support for HTTPS server"
depends on NET_SOCKETS_SOCKOPT_TLS
depends on MBEDTLS_SSL_ALPN
help
Use ALPN (application layer protocol negotiation) to negotiate HTTP2
protocol for TLS connections. Web browsers use this mechanism to determine
whether HTTP2 is supported.
config WEBSOCKET_CONSOLE
bool
default y if HTTP_SERVER_WEBSOCKET && SHELL_BACKEND_WEBSOCKET

View File

@ -58,6 +58,10 @@ static struct http_server_ctx server_ctx;
static K_SEM_DEFINE(server_start, 0, 1);
static bool server_running;
#if defined(CONFIG_HTTP_SERVER_TLS_USE_ALPN)
static const char *const alpn_list[] = {"h2", "http/1.1"};
#endif
static void close_client_connection(struct http_client_ctx *client);
HTTP_SERVER_CONTENT_TYPE(html, "text/html")
@ -185,8 +189,17 @@ int http_server_init(struct http_server_ctx *ctx)
zsock_close(fd);
continue;
}
#if defined(CONFIG_HTTP_SERVER_TLS_USE_ALPN)
if (zsock_setsockopt(fd, SOL_TLS, TLS_ALPN_LIST, alpn_list,
sizeof(alpn_list)) < 0) {
LOG_ERR("setsockopt: %d", errno);
zsock_close(fd);
continue;
}
#endif
#endif /* defined(CONFIG_HTTP_SERVER_TLS_USE_ALPN) */
}
#endif /* defined(CONFIG_NET_SOCKETS_SOCKOPT_TLS) */
if (zsock_setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &(int){1},
sizeof(int)) < 0) {