Skip to main content

C++ Guide

Overview​

SST's C++17 API lives in entity/c/cpp/, within the sst-c-api submodule. It implements the same wire protocol as the C API and can communicate with Auth and C entities using the same properties configs.

sst::SST_API loads configuration and credentials and requests session keys. sst::SessionKeyList stores keys, and sst::SST_Session owns a connected socket and exchanges encrypted messages. Setup failures throw sst::SST_Exception with an sst::SST_ErrorCode category; message send/receive operations return status codes or a typed sst::SST_IOResult. See the C++ API Reference for signatures and ownership rules.

The library is organized into four layers:

LayerLocation under cpp/src/Purpose
APIapi.hpp, implemented in api.cpp, config.cpp, handshake.cpp, session.cpp, and session_key.cppPublic SST_API, SessionKeyList, and SST_Session interfaces.
Cryptocrypto.hpp/cppStateless sst::Crypto primitives: RSA, AES, SHA-256, and HMAC.
Networknet/sockets.hpp/cppOwning POSIX TCP socket wrappers.
Logginglog/log_manager.hpp/cppspdlog-based singleton logger with rotating file output.

Protocol messages are implemented as internal classes under message/, one per file, mirroring the Java message package of the Auth server. ipfs.hpp/cpp provides the sst::ipfs file-sharing helpers.

Prerequisites​

  • A C++17 compiler (clang or gcc), CMake 3.19 or newer, and OpenSSL 3 development headers.
  • A POSIX environment, such as Linux or macOS.
  • spdlog, supplied as an installed CMake package or a local source tree, or fetched by CMake. Fetching requires Git and network access; see Offline builds.

Standalone build for a device​

The SST C/C++ API repository can be used directly by a device developer. From a clone of that repository, the C++ source is under cpp/. The following builds the library with its C++ dependencies:

git clone https://github.com/iotauth/sst-c-api.git
cmake -S sst-c-api/cpp -B cpp-build
cmake --build cpp-build --target sst-cpp-api

The current C++17 transport uses POSIX sockets and threads. A gateway can run it on behalf of an actuator driven by a bare-metal microcontroller. Running this library directly on a board without an operating system requires a port of those platform services. Provision the gateway's entity configuration and credentials and point it at the deployment's Auth. The SST main repository pins the same API source as a submodule for integration tests and examples.

Full checkout for the Auth examples​

For the end-to-end examples below, initialize that submodule along with the main repository:

git clone --recurse-submodules https://github.com/iotauth/iotauth.git
cd iotauth
export SST_ROOT="$PWD"

For an existing checkout, run git submodule update --init entity/c from the repository root. In the commands below, set SST_ROOT to that absolute checkout path in each terminal.

On macOS, CMake can use Homebrew's OpenSSL:

brew install openssl@3 cmake
export OPENSSL_ROOT_DIR="$(brew --prefix openssl@3)"

Build and test the library​

cd "$SST_ROOT/entity/c/cpp"
cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug
cmake --build build --parallel
ctest --test-dir build --output-on-failure

This builds the static sst-cpp-api library and six test executables. A Debug build keeps the assertion-based checks enabled. Run the tests from a writable directory because the fixtures create temporary files.

TestCoverage
crypto_testAES-CBC/CTR/GCM round trips, encrypt-then-authenticate with and without HMAC, SHA-256, and RSA sign/verify.
socket_testIPv4/IPv6 loopback connections, invalid addresses, descriptor ownership and duplication, and reads at peer closure.
api_testConfig parsing (including error cases), SessionKeyList bookkeeping, and session key buffer encryption.
message_testEach message class against the wire format of its Java counterpart in Auth.
protocol_testA local Auth stand-in for public-key and distribution-key requests, key-ID lookups, nonce and alert failures, responses larger than 1024 bytes, and handshake wire regressions.
ipfs_testRuns a local stand-in for the IPFS command to check subprocess output, file permissions, and error handling.

None of these tests require Auth or IPFS. Each example directory has a separate CMake project; building the library alone does not build the examples.

To check only a session-key request against a running Auth, build the optional probe, which is excluded from the default build:

cmake --build build --target auth_connect_test
cd examples/server_client_example
../../build/auth_connect_test ../../../examples/server_client_example/c_client.config

See Testing and CI for how these tests and the C++ examples run in GitHub Actions.

Offline builds​

CMake first reuses an existing spdlog::spdlog target or an installed spdlog package, and only then downloads spdlog v1.17.0. Pass -DSST_FETCH_SPDLOG=OFF to disable the download, and point CMake at a local copy:

# An installed package outside the usual search paths
cmake -S . -B build -DSST_FETCH_SPDLOG=OFF -DCMAKE_PREFIX_PATH=/path/to/prefix
# Or an existing spdlog source checkout
cmake -S . -B build -DSST_FETCH_SPDLOG=OFF -DSST_SPDLOG_SOURCE_DIR=/path/to/spdlog

Use the library from another CMake project​

Add the cpp/ source directory and link the target:

add_subdirectory("${SST_ROOT}/entity/c/cpp" sst-cpp-build)
add_executable(my_entity main.cpp)
target_link_libraries(my_entity PRIVATE sst-cpp-api)

Here SST_ROOT is a CMake variable (for example, set it with -DSST_ROOT=/path/to/iotauth). The target exports the cpp/src/ include directory, so application code uses #include "api.hpp". It also links OpenSSL, spdlog, and the platform thread library publicly, because the logging header exposes spdlog types. The C++ project currently has no install/package-export rules.

Configuration​

The C++ API reads the C properties format, including entityInfo.name, entityInfo.purpose, and auth.port.number, so C and C++ entities can share configs. The earlier C++ short names (for example, name = ...) are still accepted as aliases.

The parser is strict. It rejects unknown keys, empty values, malformed integers (including trailing characters), out-of-range ports, more than two entityInfo.purpose entries, and distribution-key paths given while PermanentDistKeyMode is off. Each failure throws SST_Exception with code Configuration.

Relative credential paths are resolved from the process working directory, not from the config file's directory. Python properties configs resolve credential paths relative to the config file instead; see Python configuration formats.

Run the server/client example​

Generate example credentials and build Auth as described in Quick Start. From the main repository:

cd "$SST_ROOT/examples"
./generateAll.sh
cd "$SST_ROOT/auth/auth-server"
mvn clean install
java -jar target/auth-server-jar-with-dependencies.jar \
-p ../properties/exampleAuth101.properties

Leave Auth running. Build the C++ examples in another terminal:

cd "$SST_ROOT/entity/c/cpp/examples/server_client_example"
cmake -S . -B build
cmake --build build

Start the server from that example directory:

./build/entity_server ../../../examples/server_client_example/c_server.config

In a third terminal, start the client from the same directory:

cd "$SST_ROOT/entity/c/cpp/examples/server_client_example"
./build/entity_client ../../../examples/server_client_example/c_client.config

The programs reuse the C example's configs and exchange encrypted messages over two successive connections. Run the C++ binaries from the example directory, as shown: credential paths in these configs are relative to the process working directory. The equivalent C binaries run from their own build/ directory, which has the same depth within entity/.

Client lifecycle​

This small client sends one message. Supply a client config whose credential paths match the working directory, and use a running compatible server:

#include "api.hpp"
#include <iostream>

int main(int argc, char** argv) {
if (argc != 2) return 1;
try {
sst::SST_API api(argv[1]);
auto keys = api.get_session_key();
if (keys.empty()) return 1;
auto session = api.secure_connect_to_server(keys.at(0));
sst::SST_IOResult sent = session->send_secure_message_result("hello");
if (!sent.ok()) return 1;
// The session destructor closes the socket.
} catch (const sst::SST_Exception& error) {
std::cerr << error.what() << '\n';
return error.code() == sst::SST_ErrorCode::AuthRejected ? 2 : 1;
}
}

Access keys with at(index), in oldest-to-newest order, rather than through the legacy s_key array. For a receiver thread, call session->shutdown() and join the thread before destroying the session. shutdown() interrupts a blocked receive; the session destructor closes the descriptor.

Handling errors​

  • Setup (construction, key requests, add-reader requests, and handshakes) throws SST_Exception. Use what() for the diagnostic text and code() to branch on the category, such as Configuration, KeyLoad, Network, Protocol, Crypto, or AuthRejected.
  • Messaging returns status codes instead of throwing, so a closed connection can be handled in normal control flow. send_secure_message() and read_secure_message() return -1 on failure. A receive result of 0 can mean either an empty message or peer closure; use read_secure_message_result() when the two must be distinguished. Its SST_IOResult reports Success, PeerClosed, or Error, plus a code such as KeyExpired or BufferTooSmall.

Threads​

  • One SST_API can be shared between threads: Auth requests are serialized by an internal mutex. get_mutex() lets you read get_config() or get_dist_key() safely while requests may run, but do not hold it while calling a method that talks to Auth.
  • SessionKeyList has no internal locking. Use a list from one thread at a time, or guard it with an application mutex for the whole call, including use of keys borrowed from it. get_session_key_by_ID() returns a pointer into the list that a later addition can overwrite.
  • SST_Session has separate send and receive mutexes, so one thread can send while another receives.

The threaded_get_target_id_client and threaded_get_target_id_server programs in the server/client example demonstrate concurrent key requests by ID.

More examples​

Example under entity/c/cpp/Purpose
examples/server_client_example/Secure sessions and session-key lookup by ID from multiple threads.
examples/file_block_encrypt_example/Standalone block encryption with a locally generated key; no Auth required.
examples/ipfs_examples/Encrypted IPFS uploads/downloads with plain or secure File System Managers.

The C++ IPFS README provides the file-sharing topology, configuration paths, and run commands. cpp/src/ipfs.hpp exposes the corresponding sst::ipfs helpers.