C++ API Reference
Overview
The public session API is declared in cpp/src/api.hpp. Its types live in namespace sst. Use the C++ Guide for builds, configuration, and runnable examples.
| C concept | C++ equivalent |
|---|---|
SST_ctx_t, init_SST(), free_SST_ctx_t() | SST_API; credentials are released automatically. |
session_key_list_t | SessionKeyList; fixed storage for ten keys. |
SST_session_ctx_t, free_session_ctx() | SST_Session; destruction also closes its socket. |
| Client/server handshake functions | SST_API methods returning std::unique_ptr<SST_Session>. |
receive_thread_read_one_each() | SST_Session::receive_loop(). |
| Buffer encryption without malloc | Static SST_API methods with caller-provided buffers. |
convert_skid_buf_to_int(), update_validity() | Free functions of the same names; see Utilities. |
ipfs.h | cpp/src/ipfs.hpp, namespace sst::ipfs. |
The C++ API shares the C wire protocol and properties config format. It does not currently expose equivalents of the C session-key save/load functions.
Source layout
api.hpp is the only header applications need for secure sessions. Its implementation is split by responsibility:
File under cpp/src/ | Contents |
|---|---|
api.cpp | SST_API construction, credential loading, and Auth requests (session keys, add-reader). |
config.cpp | Config file parsing, defaults, and validation. |
handshake.cpp | Client and server sides of the entity-to-entity session key handshake. |
session.cpp | SST_Session lifetime and secure message I/O. |
session_key.cpp | Key validity, SessionKeyList, and buffer encryption with a session key. |
api_internal.hpp/cpp | Shared byte, socket, and crypto helpers. Internal; not part of the public API. |
message/ | One class per Auth/entity message in namespace sst::message, mirroring the Auth server's Java org.iot.auth.message package. Internal; api.hpp does not expose them. |
Errors
SST_Exception
class SST_Exception : public std::runtime_error {
public:
explicit SST_Exception(const std::string& message,
SST_ErrorCode code = SST_ErrorCode::Unspecified);
SST_ErrorCode code() const noexcept;
};
Setup operations throw SST_Exception: construction, session key requests, add-reader requests, and handshakes. what() returns the diagnostic text and code() returns a stable category, so applications can react to the kind of failure without parsing messages.
SST_ErrorCode
| Code | Typical cause |
|---|---|
None | No error (successful SST_IOResult). |
Unspecified | Exception constructed without a category. |
InvalidArgument | Null buffer with a non-zero length, oversized payload, purpose index other than 0 or 1, or an invalid SessionKeyList index or slot. |
Configuration | Config file missing or unreadable, unknown key, empty or malformed value, too many purposes, or conflicting distribution-key settings. |
KeyLoad | The entity private key, Auth public key, or permanent distribution key could not be loaded. |
Network | Connecting to, reading from, or writing to Auth or a peer entity failed. |
Protocol | Unexpected message type, nonce mismatch, wrong session key ID, or wrong sequence number. |
Crypto | Encryption, decryption, MAC verification, or signature verification failed. |
KeyExpired | The session key's absolute validity has passed. |
BufferTooSmall | The caller's plaintext buffer cannot hold the received message. |
AuthRejected | Auth replied with an AUTH_ALERT. |
PeerClosed | The peer closed the connection during a handshake or receive. |
Io | Local file I/O failed (IPFS helpers). |
SST_IOResult
enum class SST_IOStatus { Success, PeerClosed, Error };
struct SST_IOResult {
SST_IOStatus status;
unsigned int bytes;
SST_ErrorCode error;
bool ok() const;
int legacy_value() const;
};
Returned by the typed message methods of SST_Session. bytes is meaningful on Success: framed bytes for sends and plaintext bytes for receives. An empty plaintext is a successful receive and is distinct from PeerClosed. legacy_value() converts the result to the integer convention of the original methods: -1 on Error, otherwise bytes.
SST_API
Construction
explicit SST_API(const std::string& config_path);
Loads the entity config, private key, and Auth public key, or permanent distribution keys when enabled. Relative credential paths are resolved from the process working directory. Construction throws SST_Exception with Configuration or KeyLoad on failure. The context is neither copyable nor movable.
The config parser rejects unknown keys, malformed integers (including trailing characters), and more than two entityInfo.purpose entries. See Configuration in the C++ Guide.
Request session keys
SessionKeyList get_session_key();
void get_session_key(SessionKeyList& existing_s_key_list);
SessionKeyList get_session_key_with_index(int purpose_index);
void get_session_key_with_index(int purpose_index,
SessionKeyList& existing_s_key_list);
session_key_t* get_session_key_by_ID(
const unsigned char* target_session_key_id,
SessionKeyList& existing_s_key_list);
The no-list overload returns a new list. The list overload appends received keys, or skips the request with a warning if the list cannot accommodate them. The indexed overloads select one of up to two configured purposes (0 or 1). The selected purpose applies to that request only; it is not stored in the context.
Key lookup accepts an eight-byte ID, checks the supplied list, and requests the key from Auth if needed. The returned pointer is borrowed from the list: a later addition can overwrite that slot, so copy the key if it must outlive changes to the list.
Auth communication through one SST_API instance is serialized by an internal mutex. Session key and add-reader requests share the same exchange code, including nonce verification and distribution-key renewal. An Auth response can be up to 4096 bytes, which is larger than the C API's 1024-byte limit: ten session keys plus an RSA-encrypted distribution key and its signature do not fit in 1024 bytes.
Establish a secure session
std::unique_ptr<SST_Session> secure_connect_to_server(session_key_t& s_key);
static std::unique_ptr<SST_Session> secure_connect_to_server_with_socket(
session_key_t& s_key, int sock);
std::unique_ptr<SST_Session> server_secure_comm_setup(
int clnt_sock, SessionKeyList& existing_s_key_list);
The client method connects to the configured entity server and completes the handshake; on success it refreshes the key's validity, as the C API does. The socket overload uses an already-connected descriptor. The server method takes an accepted client descriptor and looks up the client's session key in the supplied list or requests it from Auth.
The returned session owns the socket. The handshake methods close the descriptor on failure, including caller-supplied descriptors. Do not also close an owned descriptor from application code.
Add a file reader
void send_add_reader_req_via_TCP(const std::string& add_reader);
Sends a serialized request such as {"AddReader":"net1.Bob"} to Auth. The argument is the request text, not a filename. File-based reader lists are handled by the IPFS examples.
Encrypt or decrypt a buffer
static int encrypt_buf_with_session_key(
const session_key_t& s_key, const unsigned char* plaintext,
unsigned int plaintext_length, unsigned char* encrypted,
unsigned int* encrypted_length);
static int decrypt_buf_with_session_key(
const session_key_t& s_key, const unsigned char* encrypted,
unsigned int encrypted_length, unsigned char* decrypted,
unsigned int* decrypted_length);
Both return 0 on success and -1 on an expired key or crypto failure. The caller supplies the output buffer. Size it with Crypto::get_expected_encrypted_total_length() or Crypto::get_expected_decrypted_maximum_length(), using the key's cipher and HMAC parameters. Output-length pointers receive the actual length; they do not communicate buffer capacity.
Inspect the context
const config_t& get_config() const;
const distribution_key_t& get_dist_key() const;
std::mutex& get_mutex();
The accessors return references into the context. If Auth requests may run on other threads, hold get_mutex() while reading them, because a request can renew the distribution key. Do not hold that mutex while calling a method that communicates with Auth: those methods acquire the same non-recursive mutex internally.
SessionKeyList
SessionKeyList();
int size() const;
bool empty() const;
int find(uint64_t key_id) const;
session_key_t& at(size_t index);
const session_key_t& at(size_t index) const;
session_key_t& at_slot(int slot);
const session_key_t& at_slot(int slot) const;
int add(const session_key_t& key);
void append(const SessionKeyList& src);
bool addable(int requested_num_key);
A fixed-size circular list of up to MAX_SESSION_KEY (ten) keys; it never allocates.
at(index)accesses active keys in oldest-to-newest order.at_slot(slot)accesses the storage slot returned byfind()oradd(). Both throw on an invalid or inactive position.find()returns the storage slot of a key ID, or-1.add()returns the slot it wrote and overwrites the oldest key when full.append()adds all keys of another list, oldest first.addable()checks capacity. When the list lacks room, it succeeds only if the oldest keys that must make way have all expired, and then drops them; otherwise the list is unchanged.
The public num_key, rear_idx, and s_key fields remain for source compatibility. New code should use the accessors and add()/append(); direct writes must preserve the ring invariant.
Lists have no internal locking. Use a list from one thread at a time, or hold an application mutex throughout the API calls that use it and any access to keys borrowed from it.
SST_Session
Send and receive
int send_secure_message(const unsigned char* msg, unsigned int msg_length);
int send_secure_message(const std::string& msg);
int read_secure_message(unsigned char* plaintext,
unsigned int plaintext_capacity);
SST_IOResult send_secure_message_result(const unsigned char* msg,
unsigned int msg_length);
SST_IOResult send_secure_message_result(const std::string& msg);
SST_IOResult read_secure_message_result(unsigned char* plaintext,
unsigned int plaintext_capacity);
- Send at most
MAX_PAYLOAD_LENGTH(1024) plaintext bytes per message. A successful send returns the number of framed bytes written; failure returns-1. The C API's send function instead returns0on success. - Receive into a caller-provided buffer;
MAX_SECURE_COMM_MSG_LENGTH(1091) bytes always suffice. Pass its capacity as the second argument. The result is the plaintext length,0on peer closure, or-1on failure. - With the integer methods, a receive result of
0can mean either an empty plaintext or peer closure. The_resultmethods return anSST_IOResultthat distinguishesSuccess,PeerClosed, andError, and carries anSST_ErrorCodesuch asKeyExpired,Protocol, orBufferTooSmallon failure. - Each direction has its own sequence number, encrypted with the payload, so authentication also protects message order.
- Sending and receiving have separate mutexes, allowing one thread to send while another receives.
Shutdown and inspection
void receive_loop();
void shutdown();
int get_sock() const;
const session_key_t& get_session_key() const;
unsigned int get_sent_seq_num() const;
unsigned int get_received_seq_num() const;
receive_loop() reads and logs messages until closure or error. shutdown() shuts down both socket directions to release a blocked receiver: an interrupted read returns 0 at a frame boundary or -1 for a truncated frame. Join receiver threads before destroying the session. The destructor closes the socket; sessions are neither copyable nor movable and are normally managed through std::unique_ptr.
get_sock() borrows the descriptor; the session retains ownership. Read the sequence-number counters only when no send or receive is running.
Data types
| Type | Purpose |
|---|---|
session_key_t | Key ID, cipher and MAC keys with their sizes, enc_mode, hmac_mode, abs_validity, and rel_validity. |
distribution_key_t | Cipher and MAC keys shared with Auth, with abs_validity and enc_mode. |
config_t | Parsed entity config, returned by SST_API::get_config(). |
perm_dist_key_mode_t | USE_PERMANENT_DIST_KEY or NO_PERMANENT_DIST_KEY. |
abs_validity is a Unix-epoch expiration time in milliseconds, matching Auth's serialized values; rel_validity is the key lifetime in milliseconds after a handshake. The fields are serialized explicitly on the wire, so these structs are not required to be binary compatible with the C structs.
Utilities
uint64_t convert_skid_buf_to_int(const unsigned char* buf, int byte_length);
void update_validity(session_key_t& session_key);
bool is_session_key_valid(const session_key_t& session_key);
convert_skid_buf_to_int() converts a big-endian session key ID to an integer, as used by SessionKeyList::find(). update_validity() sets abs_validity to now plus rel_validity. is_session_key_valid() returns true while the key's absolute validity has not passed.
Supporting modules
| Header | Purpose |
|---|---|
crypto.hpp | Static sst::Crypto key loading, RSA encryption and signatures, AES-CBC/CTR/GCM, SHA-256, HMAC, and symmetric encrypt-then-authenticate helpers. |
net/sockets.hpp | Owning POSIX TCP socket wrappers for numeric IPv4/IPv6 addresses: Socket, ClientSocket, ServerSocket, and SST_SocketInfo. They transfer plain bytes; use SST_Session for secure framing. |
ipfs.hpp | sst::ipfs file encryption, IPFS, and File System Manager helpers. |
log/log_manager.hpp | spdlog-based LogManager and LOG_INF, LOG_ERR, and related macros. |
Crypto operations write into caller-provided output buffers. OpenSSL still allocates its key and operation contexts internally, so the library is not allocation-free. Raw EVP_PKEY* objects returned by crypto key loaders must be released with EVP_PKEY_free().
In net/sockets.hpp, a failed constructor leaves get_fd() equal to -1; Connect() and Accept() return 0 or -1. Read() waits for the requested byte count, EOF, or an error, and Write() makes one POSIX write that may be partial. See the socket README and the logging README for details.