DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_socket_security

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

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

Modern equivalent of the gxSocket security checks. The properties are the legacy ones; the modern C++ is in how they are guaranteed and checked:

  close      A move-only RAII owner (UniqueFd) closes a descriptor
             exactly once: after a move or a reset() the old owner has
             nothing to close, so it cannot close a descriptor the
             program opened later (the gxSocket double Close() bug).
  poll       poll() has no FD_SETSIZE limit, so a descriptor numbered
             above 1024 can be waited on (select() wrote past its
             fd_set); the check dup()s a socket to a high number.
  sigpipe    A Send() to a closed peer returns -1 instead of killing
             the program (MSG_NOSIGNAL in gxSocket on Linux).
  iotimeout  SetIOTimeout(): a Recv() from a silent peer returns after
             the timeout, measured with std::chrono::steady_clock.
  cloexec    Sockets from gxSocket are close-on-exec.

Returns 0 if every check passes.

Legacy calls in this program

LegacyModern C++StandardNotes
SetWidth(), SetFill(), Precision(), sprintf()std::format("{:*>10} {:.3f}", ...)C++20C++17 and older: <iomanip> setw, setfill, setprecision.
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().

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_socket/socket_security/testprog.cpp 287 lines
#include "gxdlcode.h"

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

#if defined (__UNIX__)
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
#include <sys/wait.h>
#include <sys/resource.h>
#include <sys/socket.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];
    sprintf(sbuf, "%s (killed by signal %d)", name, WTERMSIG(status));
    check(0, sbuf);
    return;
  }
  check(WIFEXITED(status) && WEXITSTATUS(status) == 0, name);
}

static int test_close()
{
  int rv = 0;
  {
    gxSocket a;
    if(a.InitSocket(SOCK_STREAM, 0) < 0) return 2;
    int fd = a.GetSocket();
    a.Close();
    if(a.GetSocket() != -1) {
      printf("  Close() left the descriptor %d set\n", fd);
      rv = 1;
    }
    // The lowest free number is the one Close() just freed
    int fd2 = open("/dev/null", O_RDONLY);
    if(fd2 < 0) return 2;
    a.Close(); // Must not close fd2
    if(fcntl(fd2, F_GETFD) == -1) {
      printf("  The second Close() closed descriptor %d\n", fd2);
      rv = 1;
    }
    // The destructor must not close it either
  }
  return rv;
}

static int test_select()
{
  struct rlimit rl;
  if(getrlimit(RLIMIT_NOFILE, &rl) != 0) return 2;
  const int high_fd = 1500;
  if(rl.rlim_cur <= (rlim_t)high_fd) {
    if(rl.rlim_max <= (rlim_t)high_fd) {
      printf("  SKIP: RLIMIT_NOFILE hard limit is too low\n");
      return 0;
    }
    rl.rlim_cur = high_fd + 1;
    if(setrlimit(RLIMIT_NOFILE, &rl) != 0) return 2;
  }
  int sv[2];
  if(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return 2;
  if(dup2(sv[0], high_fd) != high_fd) return 2;
  gxSocket s;
  int rv = 0;
  if(s.ReadSelect(high_fd, 0, 200000) != 0) {
    printf("  ReadSelect() with no data did not time out\n");
    rv = 1;
  }
  if(write(sv[1], "xy", 2) != 2) return 2;
  if(s.ReadSelect(high_fd, 2, 0) != 1) {
    printf("  ReadSelect() did not see the data\n");
    rv = 1;
  }
  char buf[2];
  if(s.Recv(high_fd, buf, 2, 2, 0) != 2 || memcmp(buf, "xy", 2) != 0) {
    printf("  Recv() with a timeout failed\n");
    rv = 1;
  }
  return rv;
}

static int test_sigpipe()
{
#if defined (__LINUX__)
  int sv[2];
  if(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return 2;
  close(sv[1]);
  gxSocket s;
  char buf[4096];
  memset(buf, 'x', sizeof(buf));
  int n = s.Send(sv[0], buf, (int)sizeof(buf));
  if(n != -1) {
    printf("  Send() to a closed peer returned %d\n", n);
    return 1;
  }
  n = s.RawWrite(sv[0], buf, (int)sizeof(buf));
  if(n != -1) {
    printf("  RawWrite() to a closed peer returned %d\n", n);
    return 1;
  }
  return 0;
#else
  printf("  SKIP: MSG_NOSIGNAL is Linux only\n");
  return 0;
#endif
}

static int test_iotimeout()
{
  int sv[2];
  if(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return 2;
  gxSocket s;
  if(s.SetIOTimeout(sv[0], 1) != 0) {
    printf("  SetIOTimeout() failed\n");
    return 1;
  }
  time_t start = time(0);
  char buf[16];
  int n = s.Recv(sv[0], buf, (int)sizeof(buf)); // No select() timeout
  time_t took = time(0) - start;
  if(n != -1 || took > 5) {
    printf("  Recv() returned %d after %d seconds\n", n, (int)took);
    return 1;
  }
  // 0 removes the limit again
  if(s.SetIOTimeout(sv[0], 0) != 0) return 1;
  return 0;
}

static int test_loopback()
{
  gxSocket server;
  if(server.InitSocket(SOCK_STREAM, 0, (char *)"127.0.0.1") < 0) return 2;
  int on = 1;
  server.SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  if(server.Bind() < 0) return 2;
  if(server.Listen(1) < 0) return 2;
  if(server.GetSockName() < 0) return 2;
  int port = server.GetPortNumber();

  gxSocket client;
  if(client.InitSocket(SOCK_STREAM, port, (char *)"127.0.0.1") < 0) return 2;
  if(client.Connect() < 0) return 2;
  if(server.Accept() < 0) return 2;

  char out[100000], in[100000];
  for(int i = 0; i < (int)sizeof(out); i++) out[i] = (char)(i * 7);
  if(client.Send(out, (int)sizeof(out)) != (int)sizeof(out)) return 1;
  if(server.RemoteRecv(in, (int)sizeof(in), 5, 0) != (int)sizeof(in)) return 1;
  if(memcmp(in, out, sizeof(in)) != 0) return 1;
  if(server.RemoteSend("ok", 2) != 2) return 1;
  if(client.Recv(in, 2, 5, 0) != 2 || memcmp(in, "ok", 2) != 0) return 1;
  client.Close();
  // The peer closed: a timed Recv() reports it instead of waiting
  if(server.RemoteRecv(in, 1, 5, 0) != -1) return 1;
  if(server.GetSocketError() != gxSOCKET_DISCONNECTED_ERROR) return 1;
  return 0;
}

static int test_address()
{
  int rv = 0;
  gxSocket s;
  gxsSocketAddress sa;
  memset(&sa, 0xff, sizeof(sa));
  if(s.InitSIN(&sa, AF_INET, 4321, (char *)"127.0.0.1") != 0) return 1;
  if(sa.sin_addr.s_addr != htonl(0x7f000001) || ntohs(sa.sin_port) != 4321) {
    printf("  InitSIN() did not fill in the structure passed to it\n");
    rv = 1;
  }
  s.SetRemoteIPAddress((char *)"127.0.0.1");
  if(s.remote_sin.sin_addr.s_addr != htonl(0x7f000001)) {
    printf("  SetRemoteIPAddress() did not set the address\n");
    rv = 1;
  }
  // Out of range error codes give the invalid code message. (An
  // out of range gxSocketError cannot be made without undefined
  // behaviour, so SocketExceptionMessage()'s check is not tested.)
  const char *msg = s.TestExceptionMessage(-5);
  if(!msg || strcmp(msg, s.TestExceptionMessage(1)) != 0) {
    printf("  TestExceptionMessage() with a negative code\n");
    rv = 1;
  }
  return rv;
}

static int has_cloexec(int fd)
{
  int flags = fcntl(fd, F_GETFD);
  return flags >= 0 && (flags & FD_CLOEXEC);
}

static int test_cloexec()
{
  int rv = 0;
  gxSocket server;
  if(server.InitSocket(SOCK_STREAM, 0, (char *)"127.0.0.1") < 0) return 2;
  if(!has_cloexec(server.GetSocket())) {
    printf("  Socket() did not set FD_CLOEXEC\n");
    rv = 1;
  }
  int on = 1;
  server.SetSockOpt(SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  if(server.Bind() < 0) return 2;
  if(server.Listen(2) < 0) return 2;
  if(server.GetSockName() < 0) return 2;
  int port = server.GetPortNumber();

  // Accept(): the object's remote socket
  gxSocket c1;
  if(c1.InitSocket(SOCK_STREAM, port, (char *)"127.0.0.1") < 0) return 2;
  if(c1.Connect() < 0) return 2;
  if(server.Accept() < 0) return 2;
  if(!has_cloexec(server.GetRemoteSocket())) {
    printf("  Accept() did not set FD_CLOEXEC\n");
    rv = 1;
  }

  // Accept(s, sa): a descriptor returned to the caller
  gxSocket c2;
  if(c2.InitSocket(SOCK_STREAM, port, (char *)"127.0.0.1") < 0) return 2;
  if(c2.Connect() < 0) return 2;
  gxsSocketAddress sa;
  gxsSocket_t cfd = server.Accept(server.GetSocket(), &sa);
  if(cfd < 0) return 2;
  if(!has_cloexec(cfd)) {
    printf("  Accept(s, sa) did not set FD_CLOEXEC\n");
    rv = 1;
  }
  server.Close(cfd);
  return rv;
}

int main()
{
  run("close: a second Close() does not close a reused descriptor",
      test_close);
  run("select: ReadSelect()/Recv() on a descriptor above FD_SETSIZE",
      test_select);
  run("sigpipe: Send() to a closed peer returns -1", test_sigpipe);
  run("iotimeout: SetIOTimeout() ends a blocking Recv()", test_iotimeout);
  run("loopback: TCP Send()/Recv() round trip", test_loopback);
  run("address: InitSIN() and SetRemoteIPAddress()", test_address);
  run("cloexec: Socket() and Accept() set FD_CLOEXEC", test_cloexec);
  printf("%d failure(s)\n", failures);
  return failures ? 1 : 0;
}

#else // Not UNIX
int main()
{
  printf("SKIP: the gxSocket security tests use fork() and socketpair()\n");
  return 0;
}
#endif
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/socket/socket_security/modern.cpp 103 lines
#include <chrono>
#include <fcntl.h>
#include <iostream>
#include <poll.h>
#include <string>
#include <sys/resource.h>
#include <sys/socket.h>
#include <unistd.h>
#include <utility>

#include "../common/modern_net.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++;
}

class UniqueFd {                               // Like std::unique_ptr, for a descriptor
public:
  explicit UniqueFd(int fd = -1) : fd_(fd) {}
  UniqueFd(UniqueFd &&o) noexcept : fd_(std::exchange(o.fd_, -1)) {}
  UniqueFd &operator=(UniqueFd &&o) noexcept { reset(std::exchange(o.fd_, -1)); return *this; }
  UniqueFd(const UniqueFd &) = delete;
  UniqueFd &operator=(const UniqueFd &) = delete;
  ~UniqueFd() { reset(); }
  void reset(int fd = -1) { if(fd_ >= 0) ::close(fd_); fd_ = fd; }
  int get() const { return fd_; }
private:
  int fd_;
};

int main()
{
  SocketLibrary lib;
  { // close
    UniqueFd a(::socket(AF_INET, SOCK_STREAM, 0));
    UniqueFd b(std::move(a));                  // a owns nothing now
    b.reset();                                 // Closed once
    UniqueFd later(::socket(AF_INET, SOCK_STREAM, 0));  // May reuse the number
    a.reset(); b.reset();                      // Nothing to close: later survives
    check(::fcntl(later.get(), F_GETFD) != -1, "close: a moved-from owner cannot close a reused descriptor");
  }
  { // poll above FD_SETSIZE
    rlimit rl{};
    getrlimit(RLIMIT_NOFILE, &rl);
    int sv[2];
    ::socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
    UniqueFd r(sv[0]), w(sv[1]);
    int high = rl.rlim_cur > 2000 ? ::fcntl(r.get(), F_DUPFD, 1500) : -1;
    if(high < 0) {
      std::cout << "SKIP poll: cannot get a descriptor above 1024 here\n";
    }
    else {
      UniqueFd h(high);
      ::write(w.get(), "x", 1);
      pollfd p{h.get(), POLLIN, 0};
      check(::poll(&p, 1, 1000) == 1 && (p.revents & POLLIN), "poll: descriptor " +
            std::to_string(high) + " (above FD_SETSIZE) waited on");
    }
  }
  { // sigpipe
    ignore_sigpipe();                          // Belt and braces
    gxSocket server;
    int port = listen_loopback(server);
    gxSocket client(SOCK_STREAM, gxsPort_t(port), const_cast<char *>("127.0.0.1"));
    client.Connect();
    server.Accept();
    server.CloseRemoteSocket();                // The peer goes away
    std::string data(65536, 'x');
    int rv = 0;
    for(int i = 0; i < 20 && rv >= 0; i++) rv = client.Send(data.data(), int(data.size()));
    check(rv < 0, "sigpipe: Send() to a closed peer returns -1");
  }
  { // iotimeout
    gxSocket server;
    int port = listen_loopback(server);
    gxSocket client(SOCK_STREAM, gxsPort_t(port), const_cast<char *>("127.0.0.1"));
    client.Connect();
    server.Accept();                           // Accepted, never writes
    client.SetIOTimeout(1);
    char c;
    auto start = steady_clock::now();
    int rv = client.RawRead(&c, 1);
    auto took = duration_cast<milliseconds>(steady_clock::now() - start);
    check(rv < 0 && took >= 900ms && took < 5s, "iotimeout: Recv() returned after " +
          std::to_string(took.count()) + " ms");
    // cloexec
    check((::fcntl(client.GetSocket(), F_GETFD) & FD_CLOEXEC) != 0 &&
          (::fcntl(server.GetRemoteSocket(), F_GETFD) & FD_CLOEXEC) != 0,
          "cloexec: Socket() and Accept() descriptors are close-on-exec");
  }
  std::cout << (failures ? "FAILED" : "All checks passed") << "\n";
  return failures ? 1 : 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //
examples_modern/socket/common/modern_net.h 142 lines
#ifndef MODERN_NET_H
#define MODERN_NET_H

#include <chrono>
#include <cstdio>
#include <string>
#include <thread>
#include <vector>
#if !defined(_WIN32)
#include <arpa/inet.h>
#include <csignal>
#endif

#include "gxsocket.h"

namespace modern_net {

inline void ignore_sigpipe()
{
#if !defined(_WIN32)
  std::signal(SIGPIPE, SIG_IGN);
#endif
}

class SocketLibrary {                    // RAII for Winsock and friends
public:
  SocketLibrary() { ok_ = probe_.InitSocketLibrary() == 0; }
  ~SocketLibrary() { probe_.ReleaseSocketLibrary(); }
  SocketLibrary(const SocketLibrary &) = delete;
  SocketLibrary &operator=(const SocketLibrary &) = delete;
  explicit operator bool() const { return ok_; }
private:
  gxSocket probe_;
  bool ok_ = false;
};

inline int bound_port(gxSocket &s)       // After Bind() to port 0
{
  if(s.GetSockName() < 0) return -1;
  return int(ntohs(s.sin.sin_port));
}

// Opens a listening socket on 127.0.0.1 and a free port. Returns the
// port or -1.
inline int listen_loopback(gxSocket &s, int backlog = 5)
{
  if(s.InitSocket(SOCK_STREAM, 0, const_cast<char *>("127.0.0.1")) < 0) return -1;
  if(s.Bind() < 0 || s.Listen(backlog) < 0) return -1;
  return bound_port(s);
}

class FakeServer {
public:
  enum class Kind { Send, Sleep, ReadLine, ReadHeader, ReadData, DataListen, DataSend };
  struct Step { Kind kind; std::string data; };

  FakeServer &send(std::string s) { steps_.push_back({Kind::Send, std::move(s)}); return *this; }
  FakeServer &sleep(int ms) { steps_.push_back({Kind::Sleep, std::to_string(ms)}); return *this; }
  FakeServer &read_line() { steps_.push_back({Kind::ReadLine, {}}); return *this; }
  FakeServer &read_header() { steps_.push_back({Kind::ReadHeader, {}}); return *this; }
  FakeServer &read_data() { steps_.push_back({Kind::ReadData, {}}); return *this; }
  FakeServer &reply(std::string s) { read_line(); return send(std::move(s)); }
  FakeServer &data_listen() { steps_.push_back({Kind::DataListen, {}}); return *this; }
  FakeServer &data_send(std::string s) { steps_.push_back({Kind::DataSend, std::move(s)}); return *this; }

  // Starts the script; returns the port or -1
  int start() {
    port_ = listen_loopback(listener_, 1);
    if(port_ > 0) worker_ = std::jthread([this](std::stop_token st) { run(st); });
    return port_;
  }
  void join() { if(worker_.joinable()) worker_.join(); }
  const std::string &received() const { return received_; } // After join()
  ~FakeServer() { join(); }

private:
  bool wait_read(gxSocket &s, gxsSocket_t fd, std::stop_token &st) {
    for(int i = 0; i < 50 && !st.stop_requested(); i++)  // Up to 5 s
      if(s.ReadSelect(fd, 0, 100000) > 0) return true;
    return false;
  }
  void run(std::stop_token st) {
    if(!wait_read(listener_, listener_.GetSocket(), st) || listener_.Accept() < 0) {
      listener_.Close();
      return;
    }
    gxsSocket_t c = listener_.GetRemoteSocket();
    for(const Step &step : steps_) {
      if(step.kind == Kind::Send) {
        std::string d = step.data;
        if(auto p = d.find("%PORT%"); p != std::string::npos)
          d.replace(p, 6, std::to_string(data_port_ / 256) + "," + std::to_string(data_port_ % 256));
        if(listener_.Send(c, d.data(), int(d.size())) < 0) break;
      }
      else if(step.kind == Kind::Sleep) {
        std::this_thread::sleep_for(std::chrono::milliseconds(std::stoi(step.data)));
      }
      else if(step.kind == Kind::DataListen) {
        data_port_ = listen_loopback(data_, 1);
      }
      else if(step.kind == Kind::DataSend) {
        if(wait_read(data_, data_.GetSocket(), st) && data_.Accept() >= 0) {
          gxsSocket_t d = data_.GetRemoteSocket();
          data_.Send(d, step.data.data(), int(step.data.size()));
          data_.Close(d);
        }
        data_.Close();
      }
      else {                                // One of the reads
        std::string got;
        auto ends_with = [&got](std::string_view e) { return got.ends_with(e); };
        while(wait_read(listener_, c, st)) {
          char ch;
          if(listener_.RawRead(c, &ch, 1) != 1) break;
          got += ch;
          if(step.kind == Kind::ReadLine && ch == '\n') break;
          if(step.kind == Kind::ReadHeader && ends_with("\r\n\r\n")) break;
          if(step.kind == Kind::ReadData && ends_with("\r\n.\r\n")) break;
        }
        received_ += got;
        if(got.empty()) break;              // The client closed
      }
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
    listener_.Close(c);
    listener_.Close();
  }

  gxSocket listener_, data_;
  std::vector<Step> steps_;
  std::string received_;
  int port_ = -1, data_port_ = 0;
  std::jthread worker_;
};

} // namespace modern_net

#endif // MODERN_NET_H
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

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

Output of the modern program

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

PASS close: a moved-from owner cannot close a reused descriptor
PASS poll: descriptor 1500 (above FD_SETSIZE) waited on
PASS sigpipe: Send() to a closed peer returns -1
PASS iotimeout: Recv() returned after 1034 ms
PASS cloexec: Socket() and Accept() descriptors are close-on-exec
All checks passed