SharkSSL C/C++ Reference
TLS, cryptography, certificates, and PSA integration
SharkSSL Socket Example Lib

Detailed Description

The SharkSSL Socket Example Lib (selib.h/selib.c) is a basic module that wraps the transport agnostic SharkSSL functions for encoding and decoding into functions that interface to TCP/IP socket calls.

Socket Example Lib

In addition, the file selib.c includes wrappers for standard BSD socket calls at the end of the file. TCP/IP stacks not using the BSD API must define NO_BSD_SOCK and implement the following functions in a separate file: se_bind, se_accept, se_connect, se_close, se_sockValid, se_send, and se_recv.

Modules

 Bare Metal Systems
 

Macros

#define INFINITE_TMO   (~((U32)0))
 Use INFINITE_TMO for standard blocking call. More...
 
#define SeCtx   void
 
#define SOCKET   int
 Infinite wait time option for socket read functions. More...
 
#define INVALID_SOCKET   ((SOCKET)-1)
 
#define SOCKET_constructor(o, ctx)   ((void)(ctx), (*(o) = INVALID_SOCKET))
 
#define se_getSockName(sock, buf, status)
 
#define xprintf(data)   _xprintf data
 The macro xprintf expands to function _xprintf if the code is compiled with XPRINTF set to 1. More...
 

Functions

void se_disableTrace (int disable)
 Disable/enable the trace when XPRINTF is defined. More...
 
void printCiphersuite (U16 cipherSuite)
 Print the selected ciphersuite. More...
 
int seSec_handshake (SharkSslCon *s, SOCKET *sock, U32 timeout, const char *commonName)
 Performs the initial SSL handshaking using an asymmetric cipher in order to establish cipher settings and a shared key for the session. More...
 
int seSec_keyUpdate (SharkSslCon *s, SOCKET *sock, U8 requestUpdate)
 Sends a TLS 1.3 KeyUpdate handshake message. More...
 
int seSec_close (SharkSslCon *s, SOCKET *sock)
 Sends the complete close_notify alert. More...
 
int seSec_read (SharkSslCon *s, SOCKET *sock, U8 **buf, U32 timeout)
 Read data from socket stream and decode the encrypted data. More...
 
int seSec_write (SharkSslCon *s, SOCKET *sock, U8 *buf, int maxLen)
 Encrypts and sends plaintext to the connected peer. More...
 
int se_connect (SOCKET *sock, const char *address, U16 port)
 Initializes a SOCKET object connected to a remote host/address at a given port. More...
 
int se_bind (SOCKET *sock, U16 port)
 Initializes a SOCKET object bound to a local port, ready to accept client connections. More...
 
int se_accept (SOCKET **listenSock, U32 timeout, SOCKET **outSock)
 Waits for remote connections on the server SOCKET object 'listenSock', initialized by function se_bind, and initializes socket object 'outSock' to represent the new connection. More...
 
void se_close (SOCKET *sock)
 Close a connected socket connection. More...
 
int se_sockValid (SOCKET *sock)
 Tests whether the local socket handle is valid. More...
 
S32 se_send (SOCKET *sock, const void *buf, U32 len)
 Sends data to the connected peer. More...
 
int se_sendAll (SOCKET *sock, const void *buf, int len)
 Sends all bytes on a blocking transport, continuing partial sends. More...
 
S32 se_recv (SOCKET *sock, void *buf, U32 len, U32 timeout)
 Waits for data sent by peer. More...
 
void _xprintf (const char *fmt,...)
 The example code and macro xprintf requires this function when the code is compiled with macro XPRINTF set to 1. More...
 
void mainTask (SeCtx *ctx)
 Main entry for all example programs. More...
 

Macro Definition Documentation

◆ INFINITE_TMO

#define INFINITE_TMO   (~((U32)0))

Use INFINITE_TMO for standard blocking call.

◆ INVALID_SOCKET

#define INVALID_SOCKET   ((SOCKET)-1)

◆ se_getSockName

#define se_getSockName (   sock,
  buf,
  status 
)
Value:
do { \
struct sockaddr_in in; int size=sizeof(struct sockaddr_in); \
*(status) = getsockname(*(sock), (struct sockaddr *)&in, &size); \
memcpy((buf), &in.sin_addr.s_addr, 4); \
if(*(status) == 0) *(status) = 4; \
} while(0)

◆ SeCtx

#define SeCtx   void

◆ SOCKET

#define SOCKET   int

Infinite wait time option for socket read functions.

The SOCKET object/handle defaults to 'int' when using a BSD compatible TCP/IP stack. A platform may define a pointer-sized SOCKET before this default. Non BSD compatible TCP IP stacks must set the macro NO_BSD_SOCK and define the SOCKET object. See the header file selib.h for details.

◆ SOCKET_constructor

#define SOCKET_constructor (   o,
  ctx 
)    ((void)(ctx), (*(o) = INVALID_SOCKET))

◆ xprintf

#define xprintf (   data)    _xprintf data

The macro xprintf expands to function _xprintf if the code is compiled with XPRINTF set to 1.

Parameters
datais standard printf arguments enclosed in parenthesis; thus you must use double parenthesis when using macro xprintf.

Function Documentation

◆ _xprintf()

void _xprintf ( const char *  fmt,
  ... 
)

The example code and macro xprintf requires this function when the code is compiled with macro XPRINTF set to 1.

Parameters
fmtthe format string.
...variable arguments.

◆ mainTask()

void mainTask ( SeCtx *  ctx)

Main entry for all example programs.

Entry point implemented by the selected standalone example.

It is application code, not a TLS-library initialization routine.

Parameters
ctxSeCtx *; socket-stack context on bare-metal ports, or NULL where the port does not use it. Its lifetime must cover the example execution.

◆ printCiphersuite()

void printCiphersuite ( U16  cipherSuite)

Print the selected ciphersuite.

Parameters
cipherSuiteU16; TLS cipher-suite identifier to print through xprintf. Unknown or disabled identifiers use the fallback diagnostic.

◆ se_accept()

int se_accept ( SOCKET **  listenSock,
U32  timeout,
SOCKET **  outSock 
)

Waits for remote connections on the server SOCKET object 'listenSock', initialized by function se_bind, and initializes socket object 'outSock' to represent the new connection.

Returns
  • 1 Success
  • 0 timeout
  • -1 error
Parameters
listenSockSOCKET **; required pointer to a pointer to the initialized listening object. The indirection accommodates ports that exchange socket objects.
timeoutU32; wait in milliseconds, or INFINITE_TMO.
outSockSOCKET **; required pointer to a pointer to available caller-owned socket storage; receives the accepted socket on success.

◆ se_bind()

int se_bind ( SOCKET *  sock,
U16  port 
)

Initializes a SOCKET object bound to a local port, ready to accept client connections.

Returns
Zero on success. Error codes returned:
  • -1 Cannot create socket: Fatal
  • -2 Cannot listen: Fatal
  • -3 Cannot bind: socket in use
Parameters
sockSOCKET *; required caller-owned socket object, initialized for this operation.
portU16; local TCP port; zero requests an ephemeral port on BSD-style stacks. The object must not already hold an open socket.

◆ se_close()

void se_close ( SOCKET *  sock)

Close a connected socket connection.

Closes and invalidates the socket handle; does not free the caller-owned SOCKET object or an associated TLS connection.

Parameters
sockSOCKET *; required caller-owned socket object, initialized for this operation.

◆ se_connect()

int se_connect ( SOCKET *  sock,
const char *  address,
U16  port 
)

Initializes a SOCKET object connected to a remote host/address at a given port.

Returns
Zero on success. Error codes returned:
  • -1 Cannot create socket: Fatal
  • -2 Cannot resolve 'address'
  • -3 Cannot connect
Parameters
sockSOCKET *; required caller-owned socket object, initialized for this operation.
addressconst char *; required NUL-terminated hostname or numeric address, borrowed for this call.
portU16; remote TCP port, from 1 to 65535. Do not pass an already open socket object.

◆ se_disableTrace()

void se_disableTrace ( int  disable)

Disable/enable the trace when XPRINTF is defined.

Parameters
disableint; nonzero disables the optional example trace output; zero enables it.

◆ se_recv()

S32 se_recv ( SOCKET *  sock,
void *  buf,
U32  len,
U32  timeout 
)

Waits for data sent by peer.

Parameters
sockthe SOCKET object.
bufwritable caller-owned receive buffer of at least len bytes.
lenis the 'buf' length.
timeoutin milliseconds. The timeout can be set to INFINITE_TMO.
Returns
the length of the data read, zero on timeout, or a negative value on error.

◆ se_send()

S32 se_send ( SOCKET *  sock,
const void *  buf,
U32  len 
)

Sends data to the connected peer.

Parameters
sockSOCKET *; required caller-owned socket object, initialized for this operation.
bufconst void *; input bytes borrowed for this call; required when len is nonzero.
lenU32; number of bytes offered for sending, within the socket port's supported signed send length.
Returns
S32; bytes accepted by the socket, possibly fewer than len; negative on error. Zero makes no progress. Callers must handle partial sends; this does not confirm receipt by the peer.

◆ se_sendAll()

int se_sendAll ( SOCKET *  sock,
const void *  buf,
int  len 
)

Sends all bytes on a blocking transport, continuing partial sends.

Parameters
sockSOCKET *; required connected, caller-owned socket object.
bufconst void *; borrowed input, required when len is nonzero.
lenint; nonnegative byte count. Zero is a no-op.
Returns
int; len after complete sending, or -1 on invalid arguments or transport failure. Zero progress, a negative socket result, or an invalid send count closes the socket. Invalid arguments perform no I/O. This helper does not wait/retry a would-block error. Use it only with the blocking-send contract of the example socket ports.

◆ se_sockValid()

int se_sockValid ( SOCKET *  sock)

Tests whether the local socket handle is valid.

This does not test peer liveness.

Parameters
sockSOCKET *; required caller-owned socket object, initialized for this operation.
Returns
int: nonzero when the local handle is not the port invalid-socket value; zero otherwise. This does not prove that the peer is still connected.

◆ seSec_close()

int seSec_close ( SharkSslCon *  s,
SOCKET *  sock 
)

Sends the complete close_notify alert.

On success, leaves the socket open and SharkSslCon allocated.

On success the socket remains open; close it with se_close and release the TLS connection separately. An incomplete transport write closes the socket.

Returns
Zero on success or a negative value on TLS or socket error.

A socket send failure closes the socket. Call se_close if still valid and SharkSsl_terminateCon separately when their lifetimes end.

Parameters
sSharkSslCon *; required live TLS connection associated with sock; caller retains ownership.
sockSOCKET *; required caller-owned socket object, initialized for this operation.
Returns
int: 0 after sending the TLS close alert; -1 on TLS or socket failure.

◆ seSec_handshake()

int seSec_handshake ( SharkSslCon *  s,
SOCKET *  sock,
U32  timeout,
const char *  commonName 
)

Performs the initial SSL handshaking using an asymmetric cipher in order to establish cipher settings and a shared key for the session.

By default this calls SharkSslCon_trusted to report chain, expected-name, and configured date checks, including supported Subject Alternative Names. The optional BASIC_TRUST_CHECK example setting instead compares only the subject common name and CA result; it does not implement SAN/date checks. A positive handshake result is a SharkSslConTrust value, not automatic application approval of the peer. Apply the required trust policy.

Parameters
sthe SharkSslCon object.
sockthe SOCKET object.
timeoutin milliseconds. The timeout can be set to INFINITE_TMO.
commonNameis optional and is used for certificate domain name verification. NULL omits the expected-name check.
Returns
  • A negative value on error. The negative value is an inverted SharkSslCon_RetVal value.
  • Zero on timeout.
  • The return value is SharkSslConTrust for any return value greater than zero.

◆ seSec_keyUpdate()

int seSec_keyUpdate ( SharkSslCon *  s,
SOCKET *  sock,
U8  requestUpdate 
)

Sends a TLS 1.3 KeyUpdate handshake message.

Returns
Zero on success or a negative value if the connection is not using TLS 1.3, output is pending, or a socket error occurs.
Parameters
sSharkSslCon *; required live TLS connection associated with sock; caller retains ownership.
sockSOCKET *; required caller-owned socket object, initialized for this operation.
requestUpdateU8; zero updates the local sending key only; nonzero also requests a peer key update.
Returns
int: 0 after sending the update; -1 if TLS cannot generate it or the socket cannot send it.

◆ seSec_read()

int seSec_read ( SharkSslCon *  s,
SOCKET *  sock,
U8 **  buf,
U32  timeout 
)

Read data from socket stream and decode the encrypted data.

The buffer is managed by SharkSSL and the data returned is valid until the next SharkSSL call. This function blocks until data is available or until 'timeout' milliseconds.

Parameters
sthe SharkSslCon object.
sockthe SOCKET object.
bufis a pointer set to the SharkSSL receive buffer offset to the decrypted TLS application data. It does not parse WebSocket framing.
timeoutin milliseconds. The timeout can be set to INFINITE_TMO.
Returns
The function returns the number of bytes available in 'buf' on success. The function returns 0 on timeout and a negative value on error.

◆ seSec_write()

int seSec_write ( SharkSslCon *  s,
SOCKET *  sock,
U8 *  buf,
int  maxLen 
)

Encrypts and sends plaintext to the connected peer.

Returns maxLen only after sending all encoded records. Zero length is a no-op. Invalid lengths are rejected before encryption. A TLS error or incomplete transport write closes the socket and returns a negative value.

Parameters
sSharkSslCon *; required live TLS connection associated with sock; caller retains ownership.
sockSOCKET *; required caller-owned socket object, initialized for this operation.
bufU8 *; plaintext borrowed for this call, or NULL to use data already in the SharkSSL encryption buffer.
maxLenint; plaintext byte count from 0 to 65535. With buf=NULL, it must fit SharkSslCon_getEncBufSize. Invalid lengths are rejected before encryption or socket I/O. A zero length is a no-op. Short socket writes resume the already encrypted record; a failed or zero-progress send closes the socket. A TLS warning does not count as an application write and returns a negative error with the socket closed.
Returns
int: maxLen after all plaintext has been sent; negative on failure.