DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_ssl_security

C++20 or laterDataReel 6.4.3POSIX (Linux, UNIX)

Legacy: examples_socket/ssl_security/testprog.cpp · Modern: examples_modern/socket/ssl_security/modern.cpp

Modern equivalent of the 6.3.1 gxSSL checks. The legacy program forks fake peers; this one runs them in std::jthreads and measures with std::chrono::steady_clock:

  handshake  A TLS client talking to a server that never answers gives
             up after SetHandshakeTimeout() seconds instead of hanging.
  verify     VerifyCert() refuses a good certificate for the wrong
             host name.
  close      CloseSSLSocket() twice, and on an object never opened, is
             safe.

Returns 0 if every check passes.

Legacy calls in this program

LegacyModern C++StandardNotes
strcpy(), strncpy(), memmove() into char arraysstd::string; std::array<char, N> + string_view::copy()C++11 / C++17
gxSocketkeep gxSocket (C++ has no sockets); servers in std::jthread with std::stop_token and select() timeoutsC++20Stopping is a request, not a canceled thread blocked in accept().
gxSSLkeep gxSSL; certificate checking on (SetCAList + RequireVerifyCert); RAII closeC++11

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_socket/ssl_security/testprog.cpp 449 lines
#include "gxdlcode.h"

#include <stdio.h>
#include <string.h>
#include "gxsocket.h"

#if defined (__UNIX__) && defined (__USE_GX_SSL_EXTENSIONS__) && \
  !defined (__USE_GX_SCHANNEL__)
#include "gxssl.h"
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include "testcerts.h"

static int failures = 0;

static void check(int ok, const char *what)
{
  printf("%s %s\n", ok ? "PASS" : "FAIL", what);
  fflush(stdout);
  if(!ok) failures++;
}

typedef int (*TestFunc)();

static void run(const char *name, TestFunc f, int max_seconds = 20)
// Run one check in a child process. The child returns 0 if it passed.
{
  fflush(stdout);
  pid_t pid = fork();
  if(pid == 0) {
    signal(SIGPIPE, SIG_DFL); // The default, as in most programs
    alarm(max_seconds);       // A hang is a failure
    int rv = f();
    fflush(stdout);
    _exit(rv);
  }
  int status = 0;
  waitpid(pid, &status, 0);
  if(WIFSIGNALED(status)) {
    char sbuf[256];
    snprintf(sbuf, sizeof(sbuf), "%s (killed by signal %d)",
	     name, WTERMSIG(status));
    check(0, sbuf);
    return;
  }
  check(WIFEXITED(status) && WEXITSTATUS(status) == 0, name);
}

static int listen_local(gxSocket &server)
// Listen on 127.0.0.1 and a free port. Returns the port or -1.
{
  if(server.InitSocket(SOCK_STREAM, 0, (char *)"127.0.0.1") < 0) return -1;
  if(server.Bind() < 0) return -1;
  if(server.Listen(4) < 0) return -1;
  if(server.GetSockName() < 0) return -1;
  return server.GetPortNumber();
}

static int connect_local(gxSocket &client, int port)
{
  if(client.InitSocket(SOCK_STREAM, port, (char *)"127.0.0.1") < 0) return -1;
  return client.Connect();
}

enum ServerAction { SEND_AND_WAIT, WAIT, CLOSE_AT_ONCE };

static pid_t fork_tls_server(gxSocket &listener, ServerAction action,
			     gxSSLMethod proto = gxSSL_TLS)
// Accept one TLS client in a child process and do the action
{
  pid_t pid = fork();
  if(pid != 0) return pid;
  alarm(30);
  gxsSocket_t s = listener.Accept();
  if(s < 0) _exit(2);
  gxSSL tls;
  tls.SetSSLProto(proto);
  tls.MakeServer();
  if(!tls.InitCTX(gxTestCertPath("server.pem"),
		  gxTestCertPath("server.key"))) _exit(2);
  if(tls.OpenSSLSocket(s) != 0) _exit(2);
  if(tls.AcceptSSLSocket() != 0) _exit(2);
  if(action == SEND_AND_WAIT) {
    tls.SendSSLSocket("abcdef", 6); // One TLS record
    sleep(30);
  }
  else if(action == WAIT) {
    sleep(30); // Never reads, never answers close_notify
  }
  _exit(0); // CLOSE_AT_ONCE: the socket closes with the process
}

static int client_connect(gxSocket &client, gxSSL &tls, int port,
			  gxSSLMethod proto = gxSSL_TLS)
{
  if(connect_local(client, port) < 0) return -1;
  tls.SetSSLProto(proto);
  tls.MakeClient();
  tls.SetCAList(gxTestCertPath("ca.pem"));
  if(!tls.InitCTX()) return -1;
  if(tls.OpenSSLSocket(client.GetSocket()) != 0) return -1;
  return tls.ConnectSSLSocket();
}

static int test_hs_client()
{
  gxSocket server;
  int port = listen_local(server);
  if(port < 0) return 2;
  gxSocket client; // The kernel completes TCP, nobody answers TLS
  if(connect_local(client, port) < 0) return 2;
  gxSSL tls;
  if(tls.HandshakeTimeout() != gxSSL_DEF_HANDSHAKE_TIMEOUT) return 1;
  tls.MakeClient();
  if(!tls.InitCTX()) return 2;
  if(tls.OpenSSLSocket(client.GetSocket()) != 0) return 2;
  tls.SetHandshakeTimeout(2);
  time_t start = time(0);
  int rv = tls.ConnectSSLSocket();
  time_t took = time(0) - start;
  if(rv == 0 || took > 8) {
    printf("  ConnectSSLSocket() returned %d after %d seconds\n",
	   rv, (int)took);
    return 1;
  }
  return 0;
}

static int test_hs_server()
{
  gxSocket server;
  int port = listen_local(server);
  if(port < 0) return 2;
  gxSocket client;
  if(connect_local(client, port) < 0) return 2; // Says nothing
  gxsSocket_t s = server.Accept();
  if(s < 0) return 2;
  gxSSL tls;
  tls.MakeServer();
  if(!tls.InitCTX(gxTestCertPath("server.pem"),
		  gxTestCertPath("server.key"))) return 2;
  if(tls.OpenSSLSocket(s) != 0) return 2;
  tls.SetHandshakeTimeout(2);
  time_t start = time(0);
  int rv = tls.AcceptSSLSocket();
  time_t took = time(0) - start;
  if(rv == 0 || took > 8) {
    printf("  AcceptSSLSocket() returned %d after %d seconds\n",
	   rv, (int)took);
    return 1;
  }
  return 0;
}

static int test_close()
{
  gxSocket server;
  int port = listen_local(server);
  if(port < 0) return 2;
  pid_t pid = fork_tls_server(server, WAIT);
  gxSocket client;
  gxSSL tls;
  int rc = 0;
  if(client_connect(client, tls, port) != 0) {
    rc = 2;
  }
  else {
    time_t start = time(0);
    tls.CloseSSLSocket();
    time_t took = time(0) - start;
    if(took > 3) {
      printf("  CloseSSLSocket() took %d seconds\n", (int)took);
      rc = 1;
    }
  }
  kill(pid, SIGKILL);
  waitpid(pid, 0, 0);
  return rc;
}

static int test_pending()
{
  gxSocket server;
  int port = listen_local(server);
  if(port < 0) return 2;
  pid_t pid = fork_tls_server(server, SEND_AND_WAIT);
  gxSocket client;
  gxSSL tls;
  int rc = 0;
  if(client_connect(client, tls, port) != 0) {
    rc = 2;
  }
  else {
    char buf[8];
    memset(buf, 0, sizeof(buf));
    int n1 = tls.RecvSSLSocket(buf, 3, 3, 0);
    int n2 = tls.RecvSSLSocket(buf + 3, 3, 3, 0);
    if(n1 != 3 || n2 != 3 || memcmp(buf, "abcdef", 6) != 0) {
      printf("  RecvSSLSocket() returned %d and %d (%s)\n", n1, n2, buf);
      rc = 1;
    }
  }
  kill(pid, SIGKILL);
  waitpid(pid, 0, 0);
  return rc;
}

static int test_verify()
{
  int rc = 0;
  {
    gxSSL none; // No connection: an error, not a crash
    if(none.VerifyCert("localhost") == 0) rc = 1;
  }
  gxSocket server;
  int port = listen_local(server);
  if(port < 0) return 2;
  pid_t pid = fork_tls_server(server, WAIT);
  gxSocket client;
  gxSSL tls;
  if(client_connect(client, tls, port) != 0) {
    rc = 2;
  }
  else {
    long code = -1;
    if(tls.VerifyCert("localhost", &code) != 0 || code != 0) {
      printf("  localhost (alternative name) did not verify: %s\n",
	     tls.SSLExceptionMessage());
      rc = 1;
    }
    if(tls.VerifyCert("LocalHost") != 0) {
      printf("  Host names are not case sensitive\n");
      rc = 1;
    }
    if(tls.VerifyCert("127.0.0.1") != 0) {
      printf("  127.0.0.1 (IP alternative name) did not verify\n");
      rc = 1;
    }
    if(tls.VerifyCert("other.example") != gxSSL_PEERCN_ERROR) {
      printf("  other.example verified\n");
      rc = 1;
    }
    if(tls.VerifyCert("127.0.0.2") != gxSSL_PEERCN_ERROR) {
      printf("  127.0.0.2 verified\n");
      rc = 1;
    }
  }
  kill(pid, SIGKILL);
  waitpid(pid, 0, 0);
  return rc;
}

static int test_sigpipe()
{
  gxSocket server;
  int port = listen_local(server);
  if(port < 0) return 2;
  pid_t pid = fork_tls_server(server, CLOSE_AT_ONCE);
  gxSocket client;
  gxSSL tls;
  if(client_connect(client, tls, port) != 0) return 2;
  waitpid(pid, 0, 0); // The server has gone
  static char buf[65536];
  memset(buf, 'x', sizeof(buf));
  int rv = 0;
  for(int i = 0; i < 20 && rv >= 0; i++) {
    rv = tls.SendSSLSocket(buf, (int)sizeof(buf));
  }
  return rv < 0 ? 0 : 1;
}

// 11/16/2026: TLS settings (DataReel 6.4 beta 2)
static int test_short_timeout()
// A shorter receive timeout set by the caller is kept during the
// handshake (the default handshake timeout is 60 seconds) and is the
// socket's timeout again afterwards
{
  gxSocket server;
  int port = listen_local(server);
  if(port < 0) return 2;
  gxSocket client;
  if(connect_local(client, port) < 0) return 2;
  struct timeval tv;
  tv.tv_sec = 2; tv.tv_usec = 0;
  setsockopt(client.GetSocket(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
  gxSSL tls;
  tls.MakeClient();
  if(!tls.InitCTX()) return 2;
  if(tls.OpenSSLSocket(client.GetSocket()) != 0) return 2;
  time_t start = time(0);
  int rv = tls.ConnectSSLSocket();
  time_t took = time(0) - start;
  if(rv == 0 || took > 8) {
    printf("  ConnectSSLSocket() returned %d after %d seconds\n",
	   rv, (int)took);
    return 1;
  }
  struct timeval after;
  socklen_t len = (socklen_t)sizeof(after);
  memset(&after, 0, sizeof(after));
  getsockopt(client.GetSocket(), SOL_SOCKET, SO_RCVTIMEO, &after, &len);
  if(after.tv_sec != 2) {
    printf("  receive timeout after the handshake: %d seconds\n",
	   (int)after.tv_sec);
    return 1;
  }
  return 0;
}

static int test_old_protocols()
// SSLv2, SSLv3, TLS 1.0, TLS 1.1 and DTLS 1.0 are refused by InitCTX()
{
  gxSSLMethod old[] = { gxSSL_SSLv2, gxSSL_SSLv3, gxSSL_TLSv1,
			gxSSL_TLSv1_1, gxSSL_DTLSv1 };
  int rc = 0;
  for(unsigned i = 0; i < sizeof(old)/sizeof(old[0]); i++) {
    gxSSL tls;
    tls.SetSSLProto(old[i]);
    tls.MakeClient();
    if(tls.InitCTX() || tls.GetSSLError() != gxSSL_PROTOCOL_ERROR) {
      printf("  protocol %d was not refused\n", (int)old[i]);
      rc = 1;
    }
  }
  return rc;
}

static int version_of(gxSocket &listener, int port, gxSSLMethod server_proto,
		      gxSSLMethod client_proto)
// The protocol version a client and a server agree on, or -1 if the
// handshake fails
{
  pid_t pid = fork_tls_server(listener, WAIT, server_proto);
  gxSocket client;
  gxSSL tls;
  int v = -1;
  if(client_connect(client, tls, port, client_proto) == 0) {
    v = SSL_version(tls.GetSSL());
  }
  kill(pid, SIGKILL);
  waitpid(pid, 0, 0);
  return v;
}

static int test_versions()
{
  gxSocket server;
  int port = listen_local(server);
  if(port < 0) return 2;
  int rc = 0;
  int v = version_of(server, port, gxSSL_TLS, gxSSL_TLS);
  if(v != TLS1_3_VERSION) { printf("  TLS and TLS: version %x\n", v); rc = 1; }
  v = version_of(server, port, gxSSL_TLS, gxSSL_TLSv1_3);
  if(v != TLS1_3_VERSION) { printf("  TLS and TLSv1_3: version %x\n", v); rc = 1; }
  v = version_of(server, port, gxSSL_TLS, gxSSL_TLSv1_2);
  if(v != TLS1_2_VERSION) { printf("  TLS and TLSv1_2: version %x\n", v); rc = 1; }
  v = version_of(server, port, gxSSL_SSLv23, gxSSL_SSLv23);
  if(v != TLS1_3_VERSION) { printf("  SSLv23 and SSLv23: version %x\n", v); rc = 1; }
  v = version_of(server, port, gxSSL_TLSv1_3, gxSSL_TLSv1_2);
  if(v != -1) { printf("  TLSv1_3 server and TLSv1_2 client agreed on %x\n", v); rc = 1; }
  v = version_of(server, port, gxSSL_TLSv1_2, gxSSL_TLSv1_3);
  if(v != -1) { printf("  TLSv1_2 server and TLSv1_3 client agreed on %x\n", v); rc = 1; }
  return rc;
}

static int verified_connect(gxSocket &listener, int port, const char *host,
			    int use_ca)
// RequireVerifyCert() client. Returns the ConnectSSLSocket() value.
{
  pid_t pid = fork_tls_server(listener, WAIT);
  gxSocket client;
  gxSSL tls;
  int rv = -1;
  if(connect_local(client, port) == 0) {
    tls.MakeClient();
    tls.RequireVerifyCert();
    if(use_ca) tls.SetCAList(gxTestCertPath("ca.pem"));
    tls.SetHostName(host);
    if(tls.InitCTX() && tls.OpenSSLSocket(client.GetSocket()) == 0) {
      rv = tls.ConnectSSLSocket();
    }
  }
  kill(pid, SIGKILL);
  waitpid(pid, 0, 0);
  return rv;
}

static int test_require_verify()
// With RequireVerifyCert() the handshake checks the chain and the host
{
  gxSocket server;
  int port = listen_local(server);
  if(port < 0) return 2;
  int rc = 0;
  if(verified_connect(server, port, "localhost", 1) != 0) {
    printf("  localhost with the test CA failed\n"); rc = 1;
  }
  if(verified_connect(server, port, "127.0.0.1", 1) != 0) {
    printf("  127.0.0.1 with the test CA failed\n"); rc = 1;
  }
  if(verified_connect(server, port, "other.example", 1) == 0) {
    printf("  other.example connected\n"); rc = 1;
  }
  if(verified_connect(server, port, "localhost", 0) == 0) {
    printf("  the test CA was trusted from the system store\n"); rc = 1;
  }
  return rc;
}

int main()
{
  if(MakeTestCerts() != 0) {
    printf("FAIL could not make the test certificates with openssl\n");
    RemoveTestCerts();
    return 1;
  }
  run("hs_client: ConnectSSLSocket() handshake timeout", test_hs_client);
  run("hs_server: AcceptSSLSocket() handshake timeout", test_hs_server);
  run("close: CloseSSLSocket() does not wait for the peer", test_close);
  run("pending: RecvSSLSocket() returns buffered data", test_pending);
  run("verify: VerifyCert() alternative names and IP addresses",
      test_verify);
  run("sigpipe: SendSSLSocket() to a closed peer returns -1", test_sigpipe);
  run("short_timeout: a shorter socket timeout is kept in the handshake",
      test_short_timeout);
  run("old_protocols: SSLv2/SSLv3/TLS 1.0/TLS 1.1/DTLS 1.0 refused",
      test_old_protocols);
  run("versions: TLS 1.2 minimum, TLSv1_2 and TLSv1_3 only", test_versions, 60);
  run("require_verify: the handshake checks the chain and host name",
      test_require_verify, 60);
  RemoveTestCerts();
  printf("%d failure(s)\n", failures);
  return failures ? 1 : 0;
}

#else // Not UNIX with OpenSSL
int main()
{
  printf("SKIP: the gxSSL security tests need UNIX and OpenSSL\n");
  return 0;
}
#endif
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_socket/ssl_security/testcerts.h 103 lines
#ifndef __GX_TEST_CERTS_HPP__
#define __GX_TEST_CERTS_HPP__

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static char gxTestCertDir[512];

static inline int gxTestRun(const char *cmd)
{
  char sbuf[4096];
  snprintf(sbuf, sizeof(sbuf), "cd '%s' && (%s) >/dev/null 2>&1",
	   gxTestCertDir, cmd);
  return system(sbuf) == 0 ? 0 : -1;
}

static inline const char *gxTestCertPath(const char *fname)
// Path of a file in the certificate directory. Uses a ring of buffers
// so a few paths can be used in one call.
{
  static char sbuf[8][600];
  static int next = 0;
  char *p = sbuf[next++ & 7];
  snprintf(p, 600, "%s/%s", gxTestCertDir, fname);
  return p;
}

static inline int MakeTestCerts()
// Returns 0 if the certificates were made
{
  char tmpl[] = "/tmp/gxtestcerts.XXXXXX";
  const char *tmpdir = getenv("TMPDIR");
  if(tmpdir && *tmpdir && strlen(tmpdir) < 400) {
    snprintf(gxTestCertDir, sizeof(gxTestCertDir), "%s/gxtestcerts.XXXXXX",
	     tmpdir);
  }
  else {
    strcpy(gxTestCertDir, tmpl);
  }
  if(!mkdtemp(gxTestCertDir)) return -1;
  const char *cmds[] = {
    "openssl req -x509 -newkey rsa:2048 -nodes -keyout ca.key -out ca.pem"
    " -days 2 -subj '/CN=DataReel Test CA'",
    "openssl req -x509 -newkey rsa:2048 -nodes -keyout other_ca.key"
    " -out other_ca.pem -days 2 -subj '/CN=DataReel Other CA'",
    "printf 'subjectAltName=DNS:localhost,IP:127.0.0.1\\n"
    "basicConstraints=CA:FALSE\\nextendedKeyUsage=serverAuth\\n' > server.ext",
    "printf 'basicConstraints=CA:FALSE\\nextendedKeyUsage=clientAuth\\n'"
    " > client.ext",
    "openssl req -newkey rsa:2048 -nodes -keyout server.key -out server.csr"
    " -subj '/CN=wrong.example'",
    "openssl x509 -req -in server.csr -CA ca.pem -CAkey ca.key"
    " -CAcreateserial -out server.pem -days 2 -extfile server.ext",
    "openssl req -newkey rsa:2048 -nodes -keyout client1.key -out client1.csr"
    " -subj '/CN=client1'",
    "openssl x509 -req -in client1.csr -CA ca.pem -CAkey ca.key"
    " -CAcreateserial -out client1.pem -days 2 -extfile client.ext",
    "openssl req -newkey rsa:2048 -nodes -keyout client2.key -out client2.csr"
    " -subj '/CN=client2'",
    "openssl x509 -req -in client2.csr -CA ca.pem -CAkey ca.key"
    " -CAcreateserial -out client2.pem -days 2 -extfile client.ext",
    "openssl req -x509 -newkey rsa:2048 -nodes -keyout rogue.key"
    " -out rogue.pem -days 2 -subj '/CN=client1'",
    "openssl x509 -in client1.pem -noout -fingerprint -sha256 > client1.fp",
    0
  };
  for(int i = 0; cmds[i]; i++) {
    if(gxTestRun(cmds[i]) != 0) {
      fprintf(stderr, "Test certificate command failed: %s\n", cmds[i]);
      return -1;
    }
  }
  return 0;
}

static inline int ReadTestFile(const char *fname, char *buf, int size)
// Read the first line of a file in the certificate directory
{
  FILE *fp = fopen(gxTestCertPath(fname), "rb");
  if(!fp) return -1;
  if(!fgets(buf, size, fp)) { fclose(fp); return -1; }
  fclose(fp);
  buf[strcspn(buf, "\r\n")] = 0;
  return 0;
}

static inline void RemoveTestCerts()
{
  if(gxTestCertDir[0]) {
    char sbuf[700];
    snprintf(sbuf, sizeof(sbuf), "rm -rf '%s'", gxTestCertDir);
    if(system(sbuf) != 0) { }
    gxTestCertDir[0] = 0;
  }
}

#endif // __GX_TEST_CERTS_HPP__
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/socket/ssl_security/modern.cpp 77 lines
#include <chrono>
#include <iostream>
#include <string>
#include <thread>

#include "../common/modern_tls.h"

using namespace modern_net;
using namespace std::chrono;

static int failures = 0;
static void check(bool ok, const std::string &what)
{
  std::cout << (ok ? "PASS " : "FAIL ") << what << "\n";
  if(!ok) failures++;
}

int main()
{
  ignore_sigpipe();
  SocketLibrary lib;
  gxSSL::InitSSLibrary();
  if(!make_test_cert("modern_test_key.pem", "modern_test_cert.pem")) return 1;

  { // handshake: a peer that accepts the TCP connection and says nothing
    gxSocket silent;
    int port = listen_loopback(silent);
    std::jthread peer([&](std::stop_token st) {
      if(silent.ReadSelect(silent.GetSocket(), 5, 0) > 0) silent.Accept();
      while(!st.stop_requested()) std::this_thread::sleep_for(50ms);
    });
    gxSocket sock;
    sock.InitSocket(SOCK_STREAM, port, const_cast<char *>("127.0.0.1"));
    sock.Connect();
    gxSSL tls;
    tls.InitCTX();
    tls.SetHandshakeTimeout(2);
    auto start = steady_clock::now();
    int rv = tls.OpenSSLSocket(sock.GetSocket());
    if(rv == gxSSL_NO_ERROR) rv = tls.ConnectSSLSocket();
    auto took = duration_cast<milliseconds>(steady_clock::now() - start);
    check(rv != gxSSL_NO_ERROR && took < 10s,
          "handshake: gave up after " + std::to_string(took.count()) + " ms");
    tls.CloseSSLSocket();
  }

  { // verify: right certificate, wrong host name
    TlsServer server("modern_test_cert.pem", "modern_test_key.pem", "HTTP/1.0 204 x\r\n\r\n");
    int port = server.start();
    gxSocket sock;
    sock.InitSocket(SOCK_STREAM, port, const_cast<char *>("127.0.0.1"));
    sock.Connect();
    gxSSL tls;
    tls.SetCAList("modern_test_cert.pem");
    tls.InitCTX();
    bool up = tls.OpenSSLSocket(sock.GetSocket()) == gxSSL_NO_ERROR &&
              tls.ConnectSSLSocket() == gxSSL_NO_ERROR;
    check(up, "verify: TLS connection to the test server");
    check(up && tls.VerifyCert("localhost") == gxSSL_NO_ERROR, "verify: right host name accepted");
    check(up && tls.VerifyCert("www.example.com") != gxSSL_NO_ERROR, "verify: wrong host name refused");
    tls.CloseSSLSocket();
    // close: a second close
    tls.CloseSSLSocket();
    check(true, "close: CloseSSLSocket() twice");
  }
  {
    gxSSL never_opened;
    never_opened.CloseSSLSocket();
    check(true, "close: CloseSSLSocket() on an object never opened");
  }
  std::cout << (failures ? "FAILED" : "All checks passed") << "\n";
  return failures ? 1 : 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_modern/socket/common/modern_tls.h 82 lines
#ifndef MODERN_TLS_H
#define MODERN_TLS_H

#include <filesystem>
#include <string>
#include <thread>

#include "gxssl.h"
#include "modern_net.h"

namespace modern_net {

inline bool make_test_cert(const std::string &key, const std::string &cert,
                           const char *cn = "localhost")
{
  namespace fs = std::filesystem;
  if(fs::exists(key) && fs::exists(cert)) return true;
  gxSSL ssl;
  if(ssl.InitPRNG() != gxSSL_NO_ERROR) return false;
  if(ssl.MakeRSAPrivateKey(key.c_str(), 2048) != gxSSL_NO_ERROR) return false;
  fs::permissions(key, fs::perms::owner_read | fs::perms::owner_write,
                  fs::perm_options::replace);
  gxCertIssuerInfo ci;
  ci.sn = 1;
  ci.days = 30;
  ci.C = "US"; ci.ST = "State"; ci.L = "City";
  ci.O = "DataReel modern example"; ci.OU = "Test"; ci.CN = cn;
  return ssl.MakeCertReq(key.c_str(), ci, cert.c_str()) == gxSSL_NO_ERROR;
}

class TlsServer {
public:
  TlsServer(std::string cert, std::string key, std::string response)
    : cert_(std::move(cert)), key_(std::move(key)), response_(std::move(response)) {}
  ~TlsServer() { worker_.request_stop(); if(worker_.joinable()) worker_.join(); }

  int start() {                                // Returns the port or -1
    if(!gxSSL::InitSSLibrary()) return -1;
    if(!ctx_.InitCTX(cert_.c_str(), key_.c_str())) return -1;
    int port = listen_loopback(listener_);
    if(port > 0) worker_ = std::jthread([this](std::stop_token st) { run(st); });
    return port;
  }
  const char *error() { return ctx_.SSLExceptionMessage(); }

private:
  void run(std::stop_token st) {
    while(!st.stop_requested()) {
      if(listener_.ReadSelect(listener_.GetSocket(), 0, 100000) <= 0) continue;
      gxsSocketAddress sa{};
      gxsSocket_t c = listener_.Accept(listener_.GetSocket(), &sa);
      if(c < 0) continue;
      {
        gxSSL conn(ctx_.GetCTX());             // Shares the context
        struct Release {                       // RAII, on every path
          gxSSL &s;
          ~Release() { s.CloseSSLSocket(); s.ReleaseCTX(); } // ~gxSSL() must not free the context
        } release{conn};
        conn.SetHandshakeTimeout(5);
        if(conn.OpenSSLSocket(c) == gxSSL_NO_ERROR &&
           conn.AcceptSSLSocket() == gxSSL_NO_ERROR) {
          std::string req(2048, '\0');
          if(conn.RecvSSLSocket(req.data(), int(req.size()) - 1, 5, 0) > 0)
            conn.SendSSLSocket(response_.data(), int(response_.size()));
        }
      }
      listener_.Close(c);
    }
  }
  std::string cert_, key_, response_;
  gxSSL ctx_;
  gxSocket listener_;
  std::jthread worker_;
};

} // namespace modern_net

#endif // MODERN_TLS_H
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=20
cmake --build build-modern --target socket_ssl_security
./build-modern/socket_ssl_security

Output of the modern program

From run_modern_tests.sh on RHEL 10, GCC 14, C++20.

PASS handshake: gave up after 2031 ms
PASS verify: TLS connection to the test server
PASS verify: right host name accepted
PASS verify: wrong host name refused
PASS close: CloseSSLSocket() twice
PASS close: CloseSSLSocket() on an object never opened
All checks passed