DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_comm_security

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

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

Modern equivalent of the serial port, telnet and ping checks. Only local resources are used.

  serial  A pseudo terminal (posix_openpt) stands in for a serial port.
          The terminal settings are saved and restored by an RAII
          guard (TermiosGuard), so they come back on every path, which
          is what gxSerialComm::Close() was fixed to do; data written
          on one side is read on the other with a poll() timeout.
  telnet  gxsTelnetClient::RecvString() into a std::string sized
          buffer from a scripted server that never sends the pattern:
          it must stop at the buffer size (guard bytes after the
          buffer stay untouched) and report an error.
  ping    An ICMP echo reply parser over std::span refuses short and
          malformed packets and replies to other identifiers.

Returns 0 if every check passes.

Legacy calls in this program

LegacyModern C++StandardNotes
new / deleteautomatic objects, containers, std::unique_ptr / std::make_uniqueC++11 / C++14Ownership is in the type, and release() shows a hand-over.
strcpy(), strncpy(), memmove() into char arraysstd::string; std::array<char, N> + string_view::copy()C++11 / C++17
gxsPing (raw socket, root)unprivileged ICMP socket (SOCK_DGRAM, IPPROTO_ICMP) on LinuxPOSIX
gxsHTTPClient, gxsSMTPClient, gxsPOP3Client, gxsIMAPClient, gxsFTPClient, gxsTelnetClientkeep them; std::string buffers; reply parsing with std::string_view and std::from_charsC++17

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_socket/comm_security/testprog.cpp 626 lines
#include "gxdlcode.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <new>
#include <time.h>

#if defined (__UNIX__)
#include <fcntl.h>
#include <signal.h>
#include <unistd.h>
#include <dirent.h>
#include <termios.h>
#endif

#include "scomserv.h"
#include "gxtelnet.h"
#include "gxsping.h"

#if defined (__UNIX__)
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <poll.h>
#endif

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++;
}

#if defined (__UNIX__)
static const char *alarm_test = "";

static void on_alarm(int)
{
  printf("FAIL %s (still running after the time limit)\n", alarm_test);
  fflush(stdout);
  _exit(1);
}

static void on_sigio(int)
{
  const char msg[] = "FAIL serial: SIGIO raised by data arriving on the port\n";
  if(write(1, msg, sizeof(msg) - 1) < 0) { }
  _exit(1);
}

static void limit(const char *what, int secs)
{
  alarm_test = what;
  alarm(secs);
}

static int open_fds()
{
  DIR *d = opendir("/proc/self/fd");
  if(!d) return -1;
  int n = 0;
  while(readdir(d)) n++;
  closedir(d);
  return n;
}

static int open_pty(int &master, char *slave_name, size_t len)
{
  master = posix_openpt(O_RDWR | O_NOCTTY);
  if(master < 0) return 0;
  if(grantpt(master) != 0 || unlockpt(master) != 0) return 0;
  const char *n = ptsname(master);
  if(!n || strlen(n) >= len) return 0;
  strcpy(slave_name, n);
  return 1;
}

static void test_serial()
{
  int master;
  char slave[256];
  if(!open_pty(master, slave, sizeof(slave))) {
    printf("SKIP serial: no pseudo terminal\n");
    return;
  }

  // Data arriving on an initialized port must not raise SIGIO (the
  // default action ends the program); see the handler for the FAIL
  signal(SIGIO, on_sigio);
  {
    gxSerialCommServer s;
    check(s.InitCommServer(slave, 9600) == gxSerialComm::scomm_NO_ERROR, "serial: open and initialize the pty");
    int fl = fcntl(s.DeviceHandle(), F_GETFL);
    check(fl != -1 && !(fl & O_ASYNC), "serial: the port is not set to O_ASYNC");
    check(fl != -1 && !(fl & O_NONBLOCK), "serial: reads block after InitSerialPort()");
    int fd_fl = fcntl(s.DeviceHandle(), F_GETFD);
    check(fd_fl != -1 && (fd_fl & FD_CLOEXEC), "serial: the port is close-on-exec");

    // A block sent from the other end
    gxBlockHeader gx;
    s.SetBlockStatus(gx, gxSendBlock);
    char data[32];
    memset(data, 'x', sizeof(data));
    gx.block_length = sizeof(data);
    limit("serial: block over the pty", 10);
    // 11/16/2026: the header in its canonical wire form (gxheader.h)
    unsigned char wgx[gxWireBlockHeaderSize];
    gxWirePackBlockHeader(gx, wgx);
    if(write(master, wgx, sizeof(wgx)) != (ssize_t)sizeof(wgx) ||
       write(master, data, sizeof(data)) != (ssize_t)sizeof(data)) {
      check(0, "serial: write to the pty master");
    }
    usleep(100000);
    gxBlockHeader rx;
    check(s.ReadHeader(rx) == gxSerialComm::scomm_NO_ERROR && rx.block_length == sizeof(data),
	  "serial: block header read over the pty");
    char small[16];
    check(s.ReadBlock(small, sizeof(small), rx) == gxSerialComm::scomm_BUFFER_OVERFLOW,
	  "serial: ReadBlock() with a buffer too small is refused");
    char big[64];
    memset(big, 0, sizeof(big));
    check(s.ReadBlock(big, sizeof(big), rx) == gxSerialComm::scomm_NO_ERROR &&
	  memcmp(big, data, sizeof(data)) == 0, "serial: ReadBlock() into a buffer large enough");

    // 11/16/2026: a header with 4-byte words (a 64-bit Windows or 32-bit
    // build before the canonical form) is refused, not misread
    {
      unsigned char oldh[24 + 32];
      memset(oldh, 0, sizeof(oldh));
      oldh[0] = 0xfe; oldh[1] = 0xfe; oldh[4] = 32; oldh[8] = 'N'; oldh[9] = 'S';
      limit("serial: a header with 4-byte words", 10);
      if(write(master, oldh, sizeof(oldh)) != (ssize_t)sizeof(oldh)) check(0, "serial: write the old header");
      usleep(100000);
      gxBlockHeader orx;
      check(s.ReadHeader(orx) == gxSerialComm::scomm_BLOCKHEADER_ERROR,
	    "serial: a header with 4-byte words is refused");
      alarm(0);
      tcflush(s.DeviceHandle(), TCIOFLUSH);
    }
    // The old overload refuses a length a small buffer cannot hold
    gxBlockHeader huge;
    s.SetBlockStatus(huge, gxSendBlock);
    huge.block_length = 0x100000;
    char *p = new char[0x100000];
    alarm_test = "serial: ReadBlock(buf, gx) refuses a block over 64 KB";
    check(s.ReadBlock(p, huge) == gxSerialComm::scomm_BUFFER_OVERFLOW,
	  "serial: ReadBlock(buf, gx) refuses a block over 64 KB");
    delete[] p;
    alarm(0);
    s.Close();
  }
  signal(SIGIO, SIG_DFL);

  // Recv() ends on a 0-byte read (end of file) instead of looping
  {
    gxSerialComm c;
    int fd = open("/dev/null", O_RDONLY);
    char buf[8];
    limit("serial: Recv() on end of file", 5);
    int rv = c.Recv(fd, buf, sizeof(buf));
    alarm(0);
    check(rv == -1 && c.GetSerialCommError() == gxSerialComm::scomm_TIMEOUT_ERROR,
	  "serial: Recv() returns a timeout error on end of file");
    check(c.RawRead(fd, buf, -1) == -1 && c.RawWrite(fd, 0, 4) == -1,
	  "serial: RawRead()/RawWrite() refuse a negative count and a null buffer");
    close(fd);
  }

  // Error message table bounds
  {
    gxSerialComm c;
    c.SetSerialCommError(gxSerialComm::scomm_TIMEOUT_ERROR);
    const char *m = c.SerialCommExceptionMessage();
    check(m && strstr(m, "timeout") != 0, "serial: the last error code has a message");
    c.SetSerialCommError(-3);
    m = c.SerialCommExceptionMessage();
    check(m && strstr(m, "Invalid error code") != 0, "serial: a negative error code reads as invalid");
    c.SetSerialCommError(1000);
    m = c.SerialCommExceptionMessage();
    check(m && strstr(m, "Invalid error code") != 0, "serial: a large error code reads as invalid");
  }

  // An object that never opened a port must not close descriptor 0 (the
  // handle was left uninitialized; zeroed memory made it 0)
  {
    int saved = dup(0);
    int nul = open("/dev/null", O_RDONLY);
    dup2(nul, 0);
    close(nul);
    void *mem = malloc(sizeof(gxSerialComm));
    memset(mem, 0, sizeof(gxSerialComm));
    gxSerialComm *c = new(mem) gxSerialComm;
    c->~gxSerialComm();
    free(mem);
    check(fcntl(0, F_GETFD) != -1, "serial: destroying an unopened object leaves descriptor 0 open");
    dup2(saved, 0);
    close(saved);
  }

  // Opening twice does not leak the first descriptor; Close() restores
  // the settings saved at open
  {
    struct termios t;
    int sfd = open(slave, O_RDWR | O_NOCTTY);
    tcgetattr(sfd, &t);
    cfsetispeed(&t, B38400);
    cfsetospeed(&t, B38400);
    tcsetattr(sfd, TCSANOW, &t);
    int before = open_fds();
    gxSerialComm c;
    c.OpenSerialPort(slave);
    c.OpenSerialPort(slave);
    check(open_fds() == before + 1, "serial: a second OpenSerialPort() does not leak a descriptor");
    c.SetBaudRate(9600);
    c.InitSerialPort();
    c.Close();
    tcgetattr(sfd, &t);
    check(cfgetospeed(&t) == B38400, "serial: Close() restores the saved settings");
    close(sfd);
  }
  close(master);
}
#else
static void test_serial()
{
  printf("SKIP serial: UNIX only (pseudo terminal)\n");
}
#endif


#if defined (__UNIX__)
// Fake telnet server: a forked process accepts one connection, runs a
// script, then collects what the client sent (until EOF or 1 second of
// silence) and passes it back through a pipe.
typedef void (*server_script)(int fd);

struct fake_server {
  int port;
  pid_t pid;
  int pipe_rd;
};

static void put(int fd, const void *p, size_t n)
{
  if(write(fd, p, n) != (ssize_t)n) { }
}

static int start_server(fake_server &fs, server_script script)
{
  int ls = socket(AF_INET, SOCK_STREAM, 0);
  if(ls < 0) return 0;
  int on = 1;
  setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
  struct sockaddr_in sa;
  memset(&sa, 0, sizeof(sa));
  sa.sin_family = AF_INET;
  sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  sa.sin_port = 0;
  if(bind(ls, (struct sockaddr *)&sa, sizeof(sa)) != 0 || listen(ls, 1) != 0) {
    close(ls);
    return 0;
  }
  socklen_t len = sizeof(sa);
  getsockname(ls, (struct sockaddr *)&sa, &len);
  fs.port = ntohs(sa.sin_port);
  int pfd[2];
  if(pipe(pfd) != 0) { close(ls); return 0; }
  fflush(stdout);
  fs.pid = fork();
  if(fs.pid == 0) {
    close(pfd[0]);
    alarm(30);
    int c = accept(ls, 0, 0);
    close(ls);
    if(c < 0) _exit(1);
    script(c);
    char buf[4096];
    for(;;) {
      struct pollfd p;
      p.fd = c; p.events = POLLIN; p.revents = 0;
      if(poll(&p, 1, 1000) <= 0) break;
      ssize_t n = read(c, buf, sizeof(buf));
      if(n <= 0) break;
      put(pfd[1], buf, (size_t)n);
    }
    close(c);
    close(pfd[1]);
    _exit(0);
  }
  close(ls);
  close(pfd[1]);
  fs.pipe_rd = pfd[0];
  return fs.pid > 0;
}

static int finish_server(fake_server &fs, unsigned char *got, int max)
// Returns the number of bytes the client sent
{
  int n = 0;
  for(;;) {
    ssize_t r = read(fs.pipe_rd, got + n, (size_t)(max - n));
    if(r <= 0) break;
    n += (int)r;
    if(n >= max) break;
  }
  close(fs.pipe_rd);
  int st;
  waitpid(fs.pid, &st, 0);
  return n;
}

static int count_seq(const unsigned char *p, int n, const unsigned char *seq, int len)
{
  int c = 0;
  for(int i = 0; i + len <= n; i++) if(memcmp(p + i, seq, len) == 0) c++;
  return c;
}

static void script_flood(int fd)
{
  char a[3000];
  memset(a, 'A', sizeof(a));
  put(fd, a, sizeof(a));
  put(fd, "$ ", 2);
  usleep(300000);
}

static void script_overlap(int fd)
{
  put(fd, "xaaab", 5);
  usleep(1500000);
}

static void script_short(int fd)
{
  put(fd, "lo", 2);
  usleep(2500000);
}

static void script_hi(int fd)
{
  put(fd, "hi", 2);
}

static void script_sb(int fd)
{
  // A NAWS sub-negotiation holding 1 bytes, then TERMINAL-TYPE SEND
  // twice, then data
  const unsigned char naws[] = { 255, 250, 31, 1, 1, 1, 1, 255, 240 };
  const unsigned char ttype[] = { 255, 250, 24, 1, 255, 240 };
  put(fd, naws, sizeof(naws));
  put(fd, ttype, sizeof(ttype));
  put(fd, ttype, sizeof(ttype));
  put(fd, "ok$", 3);
  usleep(300000);
}

static void script_loop(int fd)
{
  const unsigned char will_echo[] = { 255, 251, 1 };
  const unsigned char do_x[] = { 255, 253, 99 };
  for(int i = 0; i < 50; i++) put(fd, will_echo, sizeof(will_echo));
  for(int i = 0; i < 50; i++) put(fd, do_x, sizeof(do_x));
  put(fd, "$", 1);
  usleep(300000);
}

static void script_none(int fd)
{
  (void)fd;
  usleep(300000);
}

static void script_trickle(int fd)
{
  for(int i = 0; i < 20; i++) {
    put(fd, "z", 1);
    usleep(400000);
  }
}

static void test_telnet()
{
  fake_server fs;
  unsigned char got[8192];

  // RecvString() stores at most bytes-1 characters
  if(start_server(fs, script_flood)) {
    gxsTelnetClient t;
    t.SetTimeOut(2, 0);
    t.ConnectClient("127.0.0.1", fs.port);
    char *mem = new char[8192];
    memset(mem, 0x5a, 8192);
    limit("telnet: RecvString() buffer bounds", 20);
    gxSocketError e = t.RecvString(mem, 64, "$ ");
    alarm(0);
    int guard_ok = 1;
    for(int i = 64; i < 8192; i++) if(mem[i] != 0x5a) { guard_ok = 0; break; }
    check(guard_ok, "telnet: RecvString() does not write past the buffer");
    check(e == gxSOCKET_BUFOVER_ERROR && strlen(mem) == 63, "telnet: a full buffer holds 63 characters and is terminated");
    delete[] mem;
    t.Close();
    finish_server(fs, got, sizeof(got));
  }

  // Overlapping match
  if(start_server(fs, script_overlap)) {
    gxsTelnetClient t;
    t.SetTimeOut(1, 0);
    t.ConnectClient("127.0.0.1", fs.port);
    char buf[64];
    limit("telnet: overlapping match", 20);
    gxSocketError e = t.RecvString(buf, sizeof(buf), "aab");
    alarm(0);
    check(e == gxSOCKET_NO_ERROR, "telnet: \"aab\" is found in \"xaaab\"");
    t.Close();
    finish_server(fs, got, sizeof(got));
  }

  // No match on stale bytes past the received data
  if(start_server(fs, script_short)) {
    gxsTelnetClient t;
    t.SetTimeOut(1, 0);
    t.ConnectClient("127.0.0.1", fs.port);
    char buf[64];
    strcpy(buf, "login: from an earlier call");
    limit("telnet: stale bytes", 20);
    gxSocketError e = t.RecvString(buf, sizeof(buf), "login:");
    alarm(0);
    check(e == gxSOCKET_REQUEST_TIMEOUT && strcmp(buf, "lo") == 0,
	  "telnet: stale bytes in the buffer are not matched");
    t.Close();
    finish_server(fs, got, sizeof(got));
  }

  // A null pattern and a disconnect: no crash, buffer terminated
  if(start_server(fs, script_hi)) {
    gxsTelnetClient t;
    t.SetTimeOut(2, 0);
    t.ConnectClient("127.0.0.1", fs.port);
    char buf[64];
    memset(buf, 'q', sizeof(buf));
    limit("telnet: null pattern", 20);
    gxSocketError e = t.RecvString(buf, sizeof(buf), 0);
    alarm(0);
    check(e == gxSOCKET_DISCONNECTED_ERROR && strcmp(buf, "hi") == 0,
	  "telnet: a null pattern does not crash; the buffer is terminated on disconnect");
    t.Close();
    finish_server(fs, got, sizeof(got));
  }

  // Sub-negotiation: only TERMINAL-TYPE SEND is answered, once per SB,
  // and SB bytes are not output
  if(start_server(fs, script_sb)) {
    gxsTelnetClient t;
    t.SetTimeOut(2, 0);
    t.ConnectClient("127.0.0.1", fs.port);
    char buf[64];
    limit("telnet: sub-negotiation", 20);
    gxSocketError e = t.RecvString(buf, sizeof(buf), "$");
    alarm(0);
    check(e == gxSOCKET_NO_ERROR && strcmp(buf, "ok$") == 0, "telnet: sub-negotiation bytes are not output");
    t.Close();
    int n = finish_server(fs, got, sizeof(got));
    const unsigned char reply[] = { 255, 250, 24, 0, 'N', 'V', 'T', 255, 240 };
    check(count_seq(got, n, reply, sizeof(reply)) == 2, "telnet: one terminal type reply per TERMINAL-TYPE SEND");
    const unsigned char sb[] = { 255, 250, 24, 0 };
    check(count_seq(got, n, sb, sizeof(sb)) == 2, "telnet: a NAWS sub-negotiation holding 1 bytes gets no reply");
  }

  // Repeated option requests are acknowledged once
  if(start_server(fs, script_loop)) {
    gxsTelnetClient t;
    t.SetTimeOut(2, 0);
    t.ConnectClient("127.0.0.1", fs.port);
    char buf[64];
    limit("telnet: option loops", 20);
    t.RecvString(buf, sizeof(buf), "$");
    alarm(0);
    t.Close();
    int n = finish_server(fs, got, sizeof(got));
    const unsigned char do_echo[] = { 255, 253, 1 };
    const unsigned char wont_x[] = { 255, 252, 99 };
    check(count_seq(got, n, do_echo, 3) == 1 && count_seq(got, n, wont_x, 3) == 1,
	  "telnet: 50 repeated WILL ECHO and DO requests are answered once each");
  }

  // The init sequence has no lone IAC; a Windows server line ends CR LF
  if(start_server(fs, script_none)) {
    gxsTelnetClient t;
    t.ConnectClient("127.0.0.1", fs.port);
    t.SendInitSeq();
    t.SetServerTypeWindows();
    t.SendString("cmd", 3);
    t.Close();
    int n = finish_server(fs, got, sizeof(got));
    check(n == 20 && got[14] == 31 && memcmp(got + 15, "cmd\r\n", 5) == 0,
	  "telnet: SendInitSeq() sends 15 bytes; SendString() to a Windows server ends with CR LF");
  }

  // Terminal type names are cut to fit
  {
    gxsTelnetClient t;
    char name[200];
    memset(name, 'T', sizeof(name) - 1);
    name[sizeof(name) - 1] = 0;
    t.SetTermType(name);
    check(strlen(t.GetTermType()) == 15 && t.GetMaxTotalTime() == 0, "telnet: a long terminal type is cut to 15 characters");
    setenv("TERM", name, 1);
    t.SetTermType(gxsTEL_ENV_TERM);
    check(strlen(t.GetTermType()) == 15, "telnet: a long TERM variable is cut to 15 characters");
  }

  // Total time limit against a server that trickles one byte at a time
  if(start_server(fs, script_trickle)) {
    gxsTelnetClient t;
    t.SetTimeOut(2, 0);
    t.SetMaxTotalTime(2);
    t.ConnectClient("127.0.0.1", fs.port);
    char buf[256];
    time_t t0 = time(0);
    limit("telnet: total time limit", 20);
    gxSocketError e = t.RecvString(buf, sizeof(buf), "never");
    alarm(0);
    check(e == gxSOCKET_REQUEST_TIMEOUT && (time(0) - t0) <= 4, "telnet: SetMaxTotalTime() ends RecvString()");
    t.Close();
    kill(fs.pid, SIGKILL);
    finish_server(fs, got, sizeof(got));
  }
}
#else
static void test_telnet()
{
  printf("SKIP telnet: UNIX only (fork)\n");
}
#endif

static int make_reply(unsigned char *p, unsigned char ver_ihl, unsigned char type,
		      u_short id, u_short seq, int ttl)
// IPv4 header (ver_ihl), then an ICMP message; returns the length
{
  int ihl = (ver_ihl & 0x0f) * 4;
  memset(p, 0, 128);
  p[0] = ver_ihl;
  p[8] = (unsigned char)ttl;
  p[9] = 1; // ICMP
  unsigned char *icmp = p + (ihl < 20 ? 20 : ihl);
  icmp[0] = type;
  icmp[1] = 0;
  memcpy(icmp + 4, &id, 2);
  memcpy(icmp + 6, &seq, 2);
  return (int)(icmp - p) + 8 + 36;
}

static void test_ping()
{
  unsigned char p[128];
  int ttl = 0;
  u_short id = 0x1234, seq = 7;
  int n = make_reply(p, 0x45, 0, id, seq, 57);
  check(gxsPing::ParseEchoReply(p, n, id, seq, ttl) == 1 && ttl == 57, "ping: a matching echo reply is accepted");
  check(gxsPing::ParseEchoReply(p, 27, id, seq, ttl) == 0 && ttl == -1, "ping: a reply too short for the ICMP header is refused");
  check(gxsPing::ParseEchoReply(p, 10, id, seq, ttl) == 0, "ping: a packet shorter than an IP header is refused");
  check(gxsPing::ParseEchoReply(0, n, id, seq, ttl) == 0, "ping: a null buffer is refused");
  check(gxsPing::ParseEchoReply(p, n, id, (u_short)(seq + 1), ttl) == 0, "ping: a reply to another sequence number is refused");
  check(gxsPing::ParseEchoReply(p, n, (u_short)(id + 1), seq, ttl) == 0, "ping: a reply to another program (identifier) is refused");
  n = make_reply(p, 0x45, 8, id, seq, 57);
  check(gxsPing::ParseEchoReply(p, n, id, seq, ttl) == 0, "ping: our own echo request is not taken as the reply");
  n = make_reply(p, 0x45, 3, id, seq, 57);
  check(gxsPing::ParseEchoReply(p, n, id, seq, ttl) == 0, "ping: an ICMP error is not taken as the reply");
  n = make_reply(p, 0x4f, 0, id, seq, 57); // 60 byte IP header
  check(gxsPing::ParseEchoReply(p, n, id, seq, ttl) == 1, "ping: a reply after IP options is accepted");
  check(gxsPing::ParseEchoReply(p, 60, id, seq, ttl) == 0, "ping: an IP header length past the data is refused");
  n = make_reply(p, 0x43, 0, id, seq, 57);
  check(gxsPing::ParseEchoReply(p, n, id, seq, ttl) == 0, "ping: an IP header length under 20 is refused");
  n = make_reply(p, 0x65, 0, id, seq, 57);
  check(gxsPing::ParseEchoReply(p, n, id, seq, ttl) == 0, "ping: a packet that is not IPv4 is refused");

  gxsSocketAddress a, b;
  memset(&a, 0, sizeof(a));
  memset(&b, 0, sizeof(b));
  a.sin_family = b.sin_family = AF_INET;
  a.sin_addr.s_addr = htonl(0x7f000001);
  b.sin_addr.s_addr = htonl(0x7f000001);
  b.sin_port = htons(9);
  check(gxsPing::SameAddress(&a, &b) == 1, "ping: a reply from the host pinged is accepted");
  b.sin_addr.s_addr = htonl(0x7f000002);
  check(gxsPing::SameAddress(&a, &b) == 0 && gxsPing::SameAddress(0, &b) == 0,
	"ping: a reply from another host is refused");
}

int main(int argc, char **argv)
{
#if defined (__UNIX__)
  signal(SIGALRM, on_alarm);
  signal(SIGPIPE, SIG_IGN);
#endif
  const char *names[] = { "serial", "telnet", "ping", 0 };
  void (*tests[])() = { test_serial, test_telnet, test_ping };
  int all = (argc < 2);
  for(int i = 1; i < argc; i++) {
    int known = 0;
    for(int t = 0; names[t]; t++) if(strcmp(argv[i], names[t]) == 0) known = 1;
    if(!known) {
      printf("Unknown test %s\n", argv[i]);
      return 2;
    }
  }
  for(int t = 0; names[t]; t++) {
    int run = all;
    for(int i = 1; i < argc; i++) if(strcmp(argv[i], names[t]) == 0) run = 1;
    if(run) tests[t]();
  }
  if(failures) printf("%d check(s) FAILED\n", failures);
  else printf("All checks passed\n");
  return failures ? 1 : 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/socket/comm_security/modern.cpp 119 lines
#include <array>
#include <cstdint>
#include <cstring>
#include <fcntl.h>
#include <iostream>
#include <optional>
#include <poll.h>
#include <span>
#include <string>
#include <termios.h>
#include <unistd.h>

#include "../common/modern_net.h"
#include "gxtelnet.h"

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

class TermiosGuard {                           // Restores the settings
public:
  explicit TermiosGuard(int fd) : fd_(fd) { ok_ = ::tcgetattr(fd_, &saved_) == 0; }
  ~TermiosGuard() { if(ok_) ::tcsetattr(fd_, TCSANOW, &saved_); }
  TermiosGuard(const TermiosGuard &) = delete;
  TermiosGuard &operator=(const TermiosGuard &) = delete;
  const termios &saved() const { return saved_; }
private:
  int fd_;
  termios saved_{};
  bool ok_ = false;
};

struct EchoReply { std::uint16_t id, seq; };

std::optional<EchoReply> parse_echo_reply(std::span<const std::uint8_t> pkt, std::uint16_t my_id)
{
  if(pkt.size() < 20) return std::nullopt;     // IPv4 header
  std::size_t ihl = std::size_t(pkt[0] & 0x0f) * 4;
  if((pkt[0] >> 4) != 4 || ihl < 20 || pkt.size() < ihl + 8) return std::nullopt;
  auto icmp = pkt.subspan(ihl);
  if(icmp[0] != 0 || icmp[1] != 0) return std::nullopt;  // Not an echo reply
  EchoReply r{std::uint16_t(icmp[4] << 8 | icmp[5]), std::uint16_t(icmp[6] << 8 | icmp[7])};
  if(r.id != my_id) return std::nullopt;        // Someone else's ping
  return r;
}

int main()
{
  SocketLibrary lib;
  { // serial
    int master = ::posix_openpt(O_RDWR | O_NOCTTY);
    bool ok = master >= 0 && ::grantpt(master) == 0 && ::unlockpt(master) == 0;
    int slave = ok ? ::open(::ptsname(master), O_RDWR | O_NOCTTY) : -1;
    if(slave < 0) {
      std::cout << "SKIP serial: no pseudo terminals here\n";
    }
    else {
      termios before{};
      ::tcgetattr(slave, &before);
      {
        TermiosGuard guard(slave);
        termios raw = guard.saved();
        ::cfmakeraw(&raw);
        ::cfsetspeed(&raw, B115200);
        ::tcsetattr(slave, TCSANOW, &raw);
        const char msg[] = "AT\r";
        ::write(master, msg, sizeof msg - 1);
        pollfd p{slave, POLLIN, 0};
        std::array<char, 16> buf{};
        ssize_t n = ::poll(&p, 1, 2000) == 1 ? ::read(slave, buf.data(), buf.size()) : -1;
        check(n == 3 && std::string_view(buf.data(), 3) == "AT\r", "serial: data crosses the line in raw mode");
      }
      termios after{};
      ::tcgetattr(slave, &after);
      check(std::memcmp(&before.c_lflag, &after.c_lflag, sizeof before.c_lflag) == 0 &&
            ::cfgetospeed(&before) == ::cfgetospeed(&after),
            "serial: settings restored by the RAII guard");
      ::close(slave);
    }
    if(master >= 0) ::close(master);
  }
  { // telnet
    FakeServer fs;
    fs.send(std::string(3000, 'z'));            // Never sends "login"
    int port = fs.start();
    gxsTelnetClient telnet;
    telnet.SetTimeOut(2, 0);
    std::string area(64 + 16, 'G');             // 64 bytes plus guard bytes
    int rv = -1;
    if(telnet.ConnectClient("127.0.0.1", gxsPort_t(port)) == 0)
      rv = telnet.RecvString(area.data(), 64, "login");
    check(rv != 0, "telnet: no match in a full buffer is an error");
    check(area.substr(64) == std::string(16, 'G'), "telnet: nothing written past the buffer");
    telnet.Close();
    fs.join();
  }
  { // ping
    std::array<std::uint8_t, 28> good{0x45};
    good[24] = 0x12; good[25] = 0x34; good[27] = 7;     // id 0x1234, seq 7
    auto r = parse_echo_reply(good, 0x1234);
    check(r && r->seq == 7, "ping: a good echo reply");
    check(!parse_echo_reply(std::span(good).first(25), 0x1234), "ping: a short packet is refused");
    check(!parse_echo_reply(good, 0x9999), "ping: another program's reply is ignored");
    auto bad_ihl = good; bad_ihl[0] = 0x4f;               // Header longer than the packet
    check(!parse_echo_reply(bad_ihl, 0x1234), "ping: a bad header length is refused");
    auto unreach = good; unreach[20] = 3;                  // Destination unreachable
    check(!parse_echo_reply(unreach, 0x1234), "ping: an ICMP error is not a reply");
  }
  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_comm_security
./build-modern/socket_comm_security

Output of the modern program

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

PASS serial: data crosses the line in raw mode
PASS serial: settings restored by the RAII guard
PASS telnet: no match in a full buffer is an error
PASS telnet: nothing written past the buffer
PASS ping: a good echo reply
PASS ping: a short packet is refused
PASS ping: another program's reply is ignored
PASS ping: a bad header length is refused
PASS ping: an ICMP error is not a reply
All checks passed