From a43951974863d573acf0de4d382248961a0b0d97 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Fri, 4 Dec 2026 14:32:56 -0500 Subject: [PATCH 1/2] View the HTTP user agent and CA certificate instead of copying them HttpRequest::user_agent and ca_certificate become CStringView, a small non-owning view that can only be built from a std::string or a string literal, so its text is always NUL-terminated for esp_http_client and libcurl. The reader views the strings DecoderSource::Impl::config already holds, which is declared first so it outlives both worker threads and is never changed after construction. Building an AudioReader no longer allocates, and a multi-KB PEM certificate is no longer held twice. --- CLAUDE.md | 1 + src/audio_reader.cpp | 7 +- src/audio_reader.h | 6 +- src/c_string_view.h | 87 +++++++++++++++++++++++++ src/decoder_source.cpp | 9 ++- src/host/http_client.cpp | 5 +- src/platform/http_client.h | 15 +++-- tests/CMakeLists.txt | 2 + tests/test_micro_decoder.cpp | 122 +++++++++++++++++++++++++++++++++++ 9 files changed, 240 insertions(+), 14 deletions(-) create mode 100644 src/c_string_view.h diff --git a/CLAUDE.md b/CLAUDE.md index b63bbdb..9cf5659 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,6 +34,7 @@ src/ decoder_source.cpp - thread lifecycle and orchestration audio_decoder.{h,cpp} - FLAC/MP3/Opus/Vorbis/WAV decode loop audio_reader.{h,cpp} - HTTP → RingBuffer + c_string_view.h - CStringView: non-owning view of NUL-terminated text ring_buffer.{h,cpp} - SPSC byte ring buffer; owns storage, zero-copy on both sides, no lock to move data md_transfer_buffer.{h,cpp} - flat staging buffer with start-pointer + length cursors (decoder output) types.cpp - AudioStreamInfo, detect_audio_file_type{,_from_content}, audio_file_type_to_string diff --git a/src/audio_reader.cpp b/src/audio_reader.cpp index 1a19830..a5ab7cc 100644 --- a/src/audio_reader.cpp +++ b/src/audio_reader.cpp @@ -19,7 +19,6 @@ #include #include #include -#include namespace micro_decoder { @@ -50,11 +49,11 @@ static uint64_t now_ms() { AudioReader::AudioReader(uint32_t http_timeout_ms, uint32_t http_read_timeout_ms, uint32_t write_timeout_ms, size_t http_rx_buffer_size, - std::string user_agent, std::string ca_certificate) + CStringView user_agent, CStringView ca_certificate) : max_read_size_(http_rx_buffer_size == 0 ? DEFAULT_RX_BUFFER_SIZE : http_rx_buffer_size), write_timeout_ms_(write_timeout_ms) { - this->request_.user_agent = std::move(user_agent); - this->request_.ca_certificate = std::move(ca_certificate); + this->request_.user_agent = user_agent; + this->request_.ca_certificate = ca_certificate; this->request_.rx_buffer_size = http_rx_buffer_size; this->request_.connect_timeout_ms = http_timeout_ms; this->request_.read_timeout_ms = http_read_timeout_ms; diff --git a/src/audio_reader.h b/src/audio_reader.h index 53eb3e9..c70545d 100644 --- a/src/audio_reader.h +++ b/src/audio_reader.h @@ -17,6 +17,7 @@ #pragma once +#include "c_string_view.h" #include "micro_decoder/types.h" #include "platform/http_client.h" #include "ring_buffer.h" @@ -40,7 +41,8 @@ enum class AudioReaderState : uint8_t { * @brief Reads raw audio data from an HTTP URL into a RingBuffer. * * Runs on the reader thread. Typical usage: - * 1. Construct with the HTTP timeouts and receive buffer size. + * 1. Construct with the HTTP timeouts, receive buffer size, user agent, and CA certificate. + * The last two are viewed rather than copied, so their text must outlive the reader. * 2. Call set_sink() to set the destination RingBuffer. * 3. Call start_url() to connect and detect the file type. * 4. Call run() in a loop until it returns FINISHED or FAILED. @@ -60,7 +62,7 @@ class AudioReader { public: explicit AudioReader(uint32_t http_timeout_ms, uint32_t http_read_timeout_ms, uint32_t write_timeout_ms, size_t http_rx_buffer_size, - std::string user_agent, std::string ca_certificate); + CStringView user_agent, CStringView ca_certificate); ~AudioReader(); AudioReader(const AudioReader&) = delete; diff --git a/src/c_string_view.h b/src/c_string_view.h new file mode 100644 index 0000000..a0d1399 --- /dev/null +++ b/src/c_string_view.h @@ -0,0 +1,87 @@ +// Copyright 2026 Kevin Ahrendt +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/// @file c_string_view.h +/// @brief CStringView: a non-owning view of NUL-terminated text + +#pragma once + +#include +#include + +namespace micro_decoder { + +/** + * @brief Non-owning view of text that is guaranteed to be NUL-terminated + * + * Lets text be handed to C APIs that take a `const char*` without copying it first. A plain + * std::string_view cannot do that: it may end anywhere inside a larger buffer. This view can + * only be built from a std::string or a string literal, both of which end in a NUL, so + * c_str() is always safe to pass on. + * + * @note The view holds a pointer, not a copy. The text it was built from must outlive every + * use of the view and must not be modified or reallocated meanwhile. Building one from a + * temporary std::string does not compile, which catches the most common way to break that. + */ +class CStringView { +public: + /// @brief Constructs an empty view + constexpr CStringView() = default; + + /// @brief Views the characters of a std::string the caller keeps alive + /// @note Implicit, like std::string_view's conversions, so a std::string can be passed + /// wherever a view is taken. + /// @param str Text to view; must outlive the view and stay unchanged while it is used + // cppcheck-suppress noExplicitConstructor // converting is the point of a view type + CStringView(const std::string& str) : data_(str.c_str()), size_(str.size()) {} + + /// @brief Views a string literal + /// @note The length is measured up to the first NUL rather than taken from N, so a + /// character array holding shorter text is viewed correctly too. + /// @param literal NUL-terminated character array + template + // cppcheck-suppress noExplicitConstructor // lets a literal stand in for a view + constexpr CStringView(const char (&literal)[N]) + : data_(literal), size_(std::char_traits::length(literal)) {} + + /// @brief Refuses a temporary, which would be destroyed while the view still points at it + CStringView(const std::string&&) = delete; + + /// @brief Returns the text as a NUL-terminated C string + /// @return Pointer to the first character; never nullptr + constexpr const char* c_str() const { + return this->data_; + } + + /// @brief Returns the length of the text, excluding the terminating NUL + /// @return Number of characters + constexpr size_t size() const { + return this->size_; + } + + /// @brief Returns true when the text is empty + /// @return true if size() is 0 + constexpr bool empty() const { + return this->size_ == 0; + } + +private: + // Pointer fields + const char* data_{""}; + + // size_t fields + size_t size_{0}; +}; + +} // namespace micro_decoder diff --git a/src/decoder_source.cpp b/src/decoder_source.cpp index 6ab6b0f..7b841d8 100644 --- a/src/decoder_source.cpp +++ b/src/decoder_source.cpp @@ -80,6 +80,11 @@ static constexpr uint32_t MAX_HTTP_IDLE_BACKOFF_MS = 100; /// @brief Internal implementation state for DecoderSource (pImpl) struct DecoderSource::Impl { // Struct fields + /// @brief The caller's settings, fixed for the object's lifetime + /// @note Declared first so it is destroyed last, after both worker threads are joined: + /// the reader's HTTP client views http_user_agent and http_ca_certificate here rather + /// than copying them. Nothing changes this after the constructor, so those views never + /// see the strings reallocate. DecoderConfig config; EventFlags event_flags; RingBuffer ring_buffer; @@ -329,7 +334,9 @@ struct DecoderSource::Impl { void reader_thread_main() { // One AudioReader for the thread's whole life, so a persistent reader keeps its HTTP // client (and, on ESP-IDF, the esp_http_client handle with its receive buffer and TLS - // transport) between playbacks instead of rebuilding it for each one + // transport) between playbacks instead of rebuilding it for each one. It views the + // user agent and CA certificate in this->config instead of copying them, which is + // safe because config outlives this thread and never changes (see its declaration). AudioReader reader(this->config.http_timeout_ms, this->config.http_read_timeout_ms, this->config.reader_write_timeout_ms, this->config.http_rx_buffer_size, this->config.http_user_agent, this->config.http_ca_certificate); diff --git a/src/host/http_client.cpp b/src/host/http_client.cpp index a50e62c..c9585ac 100644 --- a/src/host/http_client.cpp +++ b/src/host/http_client.cpp @@ -103,9 +103,10 @@ class CurlHttpClient final : public HttpClient { } if (!request.ca_certificate.empty()) { #ifdef CURLOPT_CAINFO_BLOB - // CURL_BLOB_COPY: libcurl copies the data immediately, so .data() lifetime is fine. + // CURL_BLOB_COPY: libcurl copies the data immediately, so the view only has to + // outlive this call. curl_blob blob{ - static_cast(const_cast(request.ca_certificate.data())), + static_cast(const_cast(request.ca_certificate.c_str())), request.ca_certificate.size(), CURL_BLOB_COPY, }; diff --git a/src/platform/http_client.h b/src/platform/http_client.h index 30c9882..52e6025 100644 --- a/src/platform/http_client.h +++ b/src/platform/http_client.h @@ -17,6 +17,8 @@ #pragma once +#include "c_string_view.h" + #include #include #include @@ -52,12 +54,14 @@ struct HttpRequest { std::string url; /// @brief User-Agent header value; empty uses the platform client's default - std::string user_agent; + /// @note Not copied: the text must outlive the HttpClient this request is opened on. + CStringView user_agent; /// @brief PEM-encoded CA certificate(s) used to verify HTTPS servers /// Empty falls back to the platform default trust store (certificate bundle on ESP-IDF, /// system trust store on host). Ignored for plain HTTP. - std::string ca_certificate; + /// @note Not copied: the text must outlive the HttpClient this request is opened on. + CStringView ca_certificate; /// @brief Polled while open() blocks; nullptr disables cancellation HttpCancelCheck cancel_check{nullptr}; @@ -88,9 +92,10 @@ struct HttpRequest { * * A client may be opened again after close(). Implementations are free to keep their * connection handle and buffers across that cycle instead of rebuilding them, so every - * HttpRequest passed to one instance must differ only in url and the cancel hook. The - * ca_certificate string must also stay alive and unchanged for as long as the instance: - * the ESP-IDF client keeps a pointer to its characters rather than a copy. + * HttpRequest passed to one instance must differ only in url and the cancel hook. The text + * behind user_agent and ca_certificate is only viewed, never copied into the request, so it + * must stay alive and unchanged for as long as the instance: the ESP-IDF client goes on + * pointing at the certificate's characters after open() returns. * * @code * HttpRequest request; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index b28f652..d1e4e61 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -123,6 +123,8 @@ set(DECODER_TESTS persistent_threads_stop_and_destroy persistent_threads_reader_recovers_after_failure persistent_threads_reader_reuses_connection + reader_views_request_text + play_url_user_agent ) foreach(test_name IN LISTS DECODER_TESTS) diff --git a/tests/test_micro_decoder.cpp b/tests/test_micro_decoder.cpp index a3ce417..ba7003a 100644 --- a/tests/test_micro_decoder.cpp +++ b/tests/test_micro_decoder.cpp @@ -40,6 +40,7 @@ // Internal headers (tests link the static library and poke its internals) #include "audio_reader.h" +#include "c_string_view.h" #include "md_transfer_buffer.h" #include "platform/event_flags.h" #include "ring_buffer.h" @@ -51,6 +52,23 @@ #include #include +// The sanitizer runtimes count the bytes the program has live on the heap, which lets a test +// see whether something allocated. Both CI test jobs run under a sanitizer; other builds skip +// those checks. +#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__) +#define MD_TEST_HEAP_STATS 1 +#elif defined(__has_feature) +#if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) +#define MD_TEST_HEAP_STATS 1 +#endif +#endif +#ifdef MD_TEST_HEAP_STATS +// Declared here rather than through : the ASan and TSan +// runtimes of both GCC and Clang export it, but GCC's sanitizer headers are not always +// installed alongside its runtimes (they are missing on the CI image). +extern "C" size_t __sanitizer_get_current_allocated_bytes(); +#endif + #include #include #include @@ -62,6 +80,7 @@ #include #include #include +#include #include using namespace micro_decoder; @@ -437,6 +456,11 @@ class TestHttpServer { size_t bytes_sent() const { return this->bytes_sent_.load(); } + // Head of every request answered since start(), oldest first + std::vector request_heads() const { + std::lock_guard lock(this->heads_mutex_); + return this->request_heads_; + } private: void serve_loop() { @@ -519,6 +543,10 @@ class TestHttpServer { return false; // an idle keep-alive connection, not a request } this->requests_.fetch_add(1); + { + std::lock_guard lock(this->heads_mutex_); + this->request_heads_.push_back(request.substr(0, request.find("\r\n\r\n"))); + } const Response& resp = this->response_; const bool endless = !resp.infinite_pattern.empty(); @@ -569,6 +597,8 @@ class TestHttpServer { // Struct fields Response response_; std::thread thread_; + mutable std::mutex heads_mutex_; + std::vector request_heads_; // guarded by heads_mutex_ // size_t / atomic fields std::atomic bytes_sent_{0}; @@ -2718,6 +2748,96 @@ static bool test_persistent_threads_reader_reuses_connection() { return true; } +static bool test_reader_views_request_text() { + // The reader views the user agent and CA certificate it is given instead of copying + // them, so building one allocates nothing, however long the text. A PEM bundle can run to + // several KB, which a copy would hold twice on a device. Nothing here opens a + // connection, so the CA text need not be a real certificate. + const std::string user_agent(512, 'u'); + const std::string ca_certificate(8192, 'c'); + // A view of a temporary would dangle as soon as the constructor returned + static_assert(!std::is_constructible::value, + "CStringView must refuse a temporary std::string"); + static_assert(std::is_constructible::value && + std::is_constructible::value, + "CStringView must accept a std::string the caller keeps and a literal"); +#ifdef MD_TEST_HEAP_STATS + const size_t heap_before = __sanitizer_get_current_allocated_bytes(); +#else + std::printf(" no sanitizer: heap check skipped\n"); +#endif + { + AudioReader reader(5000, 500, 25, 2048, user_agent, ca_certificate); +#ifdef MD_TEST_HEAP_STATS + CHECK_EQ(__sanitizer_get_current_allocated_bytes(), heap_before); +#endif + } + return true; +} + +/// @brief Returns the User-Agent header line of an HTTP request head, or "" if it has none +static std::string user_agent_line(const std::string& head) { + static constexpr const char* NAME = "\r\nUser-Agent:"; + size_t start = head.find(NAME); + if (start == std::string::npos) { + return ""; + } + start += 2; // past the CRLF that ends the previous line + return head.substr(start, head.find("\r\n", start) - start); +} + +static bool test_play_url_user_agent() { + // The configured user agent reaches the server on every request, including those of a + // later playback by a persistent reader, which reuses the view taken when its thread + // started. An empty one sends no User-Agent header at all on the host client. + std::vector payload; + TestHttpServer::Response resp; + resp.content_type = "audio/wav"; + resp.body = make_wav(2, 44100, 1024, &payload); + + for (bool persistent : {false, true}) { + std::printf(" persistent_threads=%d\n", persistent); + TestHttpServer server; + CHECK(server.start(resp)); + DecoderConfig config; + config.persistent_threads = persistent; + config.http_user_agent = "micro-decoder-test-agent/1.0 (user-agent check)"; + CaptureListener listener; + DecoderSource src(config); + src.set_listener(&listener); + for (int playback = 0; playback < 2; ++playback) { + listener.reset_capture(); + CHECK(src.play_url(server.url("/stream.wav"))); + CHECK(pump_to_completion(src, listener)); + CHECK(listener.pcm() == payload); + } + std::vector heads = server.request_heads(); + CHECK_EQ(heads.size(), 2); + for (const std::string& head : heads) { + CHECK(user_agent_line(head) == + "User-Agent: micro-decoder-test-agent/1.0 (user-agent check)"); + } + server.stop(); + } + + // Empty: the platform client's default, which for libcurl is no header + TestHttpServer server; + CHECK(server.start(resp)); + DecoderConfig config; + config.http_user_agent.clear(); + CaptureListener listener; + DecoderSource src(config); + src.set_listener(&listener); + CHECK(src.play_url(server.url("/stream.wav"))); + CHECK(pump_to_completion(src, listener)); + CHECK(listener.pcm() == payload); + std::vector heads = server.request_heads(); + CHECK_EQ(heads.size(), 1); + CHECK(user_agent_line(heads[0]).empty()); + server.stop(); + return true; +} + static const TestCase TESTS[] = { {"detect_content_type", test_detect_content_type}, {"detect_url_extension", test_detect_url_extension}, @@ -2765,6 +2885,8 @@ static const TestCase TESTS[] = { test_persistent_threads_reader_recovers_after_failure}, {"persistent_threads_reader_reuses_connection", test_persistent_threads_reader_reuses_connection}, + {"reader_views_request_text", test_reader_views_request_text}, + {"play_url_user_agent", test_play_url_user_agent}, }; int main(int argc, char* argv[]) { From e7f3795d6d73632bde37e17b3ad2628b9069aa02 Mon Sep 17 00:00:00 2001 From: Kevin Ahrendt Date: Fri, 4 Dec 2026 14:44:18 -0500 Subject: [PATCH 2/2] Refuse writable or unterminated arrays in CStringView A writable char array could change under the view, and a const array with no NUL let the length scan run off its end. The first no longer compiles; the second fails to compile in a constant expression and aborts at run time. The heap test's comment now says it shows nothing is kept, since the sanitizer counts live bytes. --- src/c_string_view.h | 32 +++++++++++++++++++++++++------- tests/test_micro_decoder.cpp | 19 +++++++++++++++---- 2 files changed, 40 insertions(+), 11 deletions(-) diff --git a/src/c_string_view.h b/src/c_string_view.h index a0d1399..c44d690 100644 --- a/src/c_string_view.h +++ b/src/c_string_view.h @@ -18,6 +18,7 @@ #pragma once #include +#include #include namespace micro_decoder { @@ -27,8 +28,8 @@ namespace micro_decoder { * * Lets text be handed to C APIs that take a `const char*` without copying it first. A plain * std::string_view cannot do that: it may end anywhere inside a larger buffer. This view can - * only be built from a std::string or a string literal, both of which end in a NUL, so - * c_str() is always safe to pass on. + * only be built from a std::string or a const character array whose last element is a NUL, + * such as a string literal, so c_str() is always safe to pass on. * * @note The view holds a pointer, not a copy. The text it was built from must outlive every * use of the view and must not be modified or reallocated meanwhile. Building one from a @@ -46,14 +47,20 @@ class CStringView { // cppcheck-suppress noExplicitConstructor // converting is the point of a view type CStringView(const std::string& str) : data_(str.c_str()), size_(str.size()) {} - /// @brief Views a string literal - /// @note The length is measured up to the first NUL rather than taken from N, so a - /// character array holding shorter text is viewed correctly too. - /// @param literal NUL-terminated character array + /// @brief Views a string literal, or any const character array ending in a NUL + /// @note The length is measured up to the first NUL rather than taken from N, so an + /// array holding shorter text is viewed correctly too. An array whose last element is + /// not a NUL fails to compile in a constant expression and aborts otherwise, rather than + /// letting the length scan run off its end. + /// @param literal Character array whose last element is a NUL template // cppcheck-suppress noExplicitConstructor // lets a literal stand in for a view constexpr CStringView(const char (&literal)[N]) - : data_(literal), size_(std::char_traits::length(literal)) {} + : data_(literal), size_(terminated_length(literal)) {} + + /// @brief Refuses a writable array, whose text could change while the view points at it + template + CStringView(char (&)[N]) = delete; /// @brief Refuses a temporary, which would be destroyed while the view still points at it CStringView(const std::string&&) = delete; @@ -77,6 +84,17 @@ class CStringView { } private: + /// @brief Returns the length of the text in a NUL-terminated array + /// @param text Character array whose last element must be a NUL + /// @return Characters before the first NUL + template + static constexpr size_t terminated_length(const char (&text)[N]) { + // std::abort() is not constexpr, so reaching it in a constant expression is a + // compile error + return text[N - 1] == '\0' ? std::char_traits::length(text) + : (std::abort(), static_cast(0)); + } + // Pointer fields const char* data_{""}; diff --git a/tests/test_micro_decoder.cpp b/tests/test_micro_decoder.cpp index 22fd6f1..32c3b82 100644 --- a/tests/test_micro_decoder.cpp +++ b/tests/test_micro_decoder.cpp @@ -85,6 +85,7 @@ extern "C" size_t __sanitizer_get_current_allocated_bytes(); #include #include #include +#include #include #include #include @@ -3191,14 +3192,24 @@ static bool test_prepare_then_stop() { static bool test_reader_views_request_text() { // The reader views the user agent and CA certificate it is given instead of copying - // them, so building one allocates nothing, however long the text. A PEM bundle can run to - // several KB, which a copy would hold twice on a device. Nothing here opens a - // connection, so the CA text need not be a real certificate. + // them, so a reader holds nothing on the heap, however long the text. A PEM bundle can + // run to several KB, which a copy would hold twice on a device. The sanitizer counts + // live bytes, so this shows nothing is kept, not that nothing was briefly allocated. + // Nothing here opens a connection, so the CA text need not be a real certificate. const std::string user_agent(512, 'u'); const std::string ca_certificate(8192, 'c'); // A view of a temporary would dangle as soon as the constructor returned - static_assert(!std::is_constructible::value, + static_assert(!std::is_constructible::value && + !std::is_constructible::value, "CStringView must refuse a temporary std::string"); + // None of these promise a NUL at the end, or text that stays unchanged + static_assert(!std::is_constructible::value && + !std::is_constructible::value && + !std::is_constructible::value && + !std::is_constructible::value, + "CStringView must refuse text without a NUL-termination guarantee"); + static_assert(CStringView("abc").size() == 3 && CStringView("ab\0cd").size() == 2, + "CStringView measures a literal up to its first NUL"); static_assert(std::is_constructible::value && std::is_constructible::value, "CStringView must accept a std::string the caller keeps and a literal");