DataReelDataReelC++ Transition Guide

Examples › General Examples

general_security_sweep

C++17 or laterC++ standard library onlyPortable C++ (tested on Linux)

Legacy: examples_general/security_sweep/testprog.cpp · Modern: examples_modern/general/security_sweep/modern.cpp

Modern equivalent of the 6.3 security sweep checks. The legacy program checks that DataReel's own string, buffer, Base64, number and file code stays in bounds. With the standard library most of those bugs cannot be written: containers know their size, at() and substr() check their arguments, and std::from_chars/std::to_chars report errors instead of writing past a buffer. This program checks those properties, and the one place where the standard behaves differently from gxString (rfind of an empty pattern), so code moved from one to the other stays right.

  config    Whole-name match of a setting; values with line breaks refused.
  logfile   A new file made owner-only with std::filesystem::permissions.
  base64    RFC 4648 encode/decode, bytes of 0x80 and more, bad input.
  findlast  rfind("") returns size(), not -1 (gxString::FindLast()).
  buffers   vector::at() and string::substr() throw past the end; a
            count past the end is clamped by substr() and erase().
  numbers   from_chars: overflow, junk and a minus sign for unsigned are
            errors; to_chars reports a buffer that is too small.
  dfile     A read at the end of a file reads 0 bytes and sets eof.
  parsers   IPv4 strings with extra groups or big numbers are refused.

Returns 0 if every check passes.

Legacy calls in this program

LegacyModern C++StandardNotes
gxString / UStringstd::string, std::string_viewC++98 / C++17string_view looks at text without copying it.
Find(), IFind(), FindLast()find(), a std::search with a case-folding predicate, rfind()C++98Watch out: rfind("") returns size(), where FindLast("") returns -1.
DeleteAt(), InsertAt(), ReplaceAt(), ReplaceString()erase(), insert(), replace(); std::replace for charactersC++98A count past the end is clamped; a position past the end throws std::out_of_range.
Left(), Mid(), Right()substr() on std::string or std::string_viewC++98 / C++17
gxsBase64Encode()/Decode()a short RFC 4648 function over std::string_view returning std::optionalC++17No standard Base64.
gxList, gxListNodestd::list; splice() for MoveBefore()/MoveAfter()C++98The list owns its nodes: no DestroyList()/DestroyArrayList().
MemoryBufferstd::vector<unsigned char> or std::vector<std::byte>; std::span for viewsC++98 / C++17 / C++20std::search finds a byte pattern; std::fill for MemSet().
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
DiskFileBstd::fstream (read, write, seekg/seekp, tellg)C++98
futils_*(), df_mkdir(), df_copy() ...std::filesystem (directory_iterator, create_directory, file_size, copy_file, rename, remove, current_path)C++17Errors through std::error_code or std::filesystem_error.
LogFilestd::ofstream + std::chrono::system_clock + std::formatC++11 / C++20Keep LogFile's 6.3 rules: owner-only file, no write through a symbolic link.
gxConfigstd::getline() into a std::map; std::optional lookups; std::from_charsC++17A rewrite through a temporary file and rename().
gxDeviceCache, gxDeviceBucketCachestreams buffer themselves: std::filesystem::copy_file(), out << in.rdbuf()C++17
CDatestd::chrono::year_month_day, sys_daysC++20An impossible date is !ok().
gxSSLkeep gxSSL; certificate checking on (SetCAList + RequireVerifyCert); RAII closeC++11

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_general/security_sweep/testprog.cpp 375 lines
#include "gxdlcode.h"

#include <stdio.h>
#include <string.h>
#include "gxconfig.h"
#include "logfile.h"
#include "dfileb.h"
#include "gxs_b64.h"
#include "gxstring.h"
#include "membuf.h"
#include "strutil.h"
#include "futils.h"
#include "devcache.h"
#include "ehandler.h"
#include "gxip32.h"
#include "gxmac48.h"
#include "cdate.h"
#include "gxshtml.h"
#include "gxrdbhdr.h"
#include "memblock.h"
#if defined (__USE_GX_SSL_EXTENSIONS__)
#include "gxssl.h"
#endif

#if defined (__UNIX__)
#include <sys/stat.h>
#endif

static int failures = 0;

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

static int owner_only(const char *fname)
// 1 if only the owner can read or write the file, -1 if not checked
{
#if defined (__UNIX__)
  struct stat st;
  if(stat(fname, &st) != 0) return 0;
  return (st.st_mode & (S_IRWXG|S_IRWXO)) == 0;
#else
  (void)fname;
  return -1;
#endif
}

static int file_has(const char *fname, const char *s)
{
  FILE *fp = fopen(fname, "rb");
  if(!fp) return 0;
  char buf[4096];
  size_t n = fread(buf, 1, sizeof(buf) - 1, fp);
  fclose(fp);
  buf[n] = 0;
  return strstr(buf, s) != 0;
}

int main()
{
#if defined (__UNIX__)
  umask(022); // The usual umask: new files readable by every user
#endif

  // config
  const char *cfg_name = "sweep.cfg";
  FILE *fp = fopen(cfg_name, "wb");
  fputs("# Port = 1 is a comment\n", fp);
  fputs("ServerPort = 100\n", fp);
  fputs("Note = the Port = 2 text\n", fp);
  fputs("Port = 3\n", fp);
  fclose(fp);
  {
    gxConfig cfg(cfg_name);
    check(cfg.ChangeConfigValue("Port", "4") == 1, "config: one setting changed");
  }
  check(file_has(cfg_name, "# Port = 1 is a comment") &&
	file_has(cfg_name, "ServerPort = 100") &&
	file_has(cfg_name, "Note = the Port = 2 text") &&
	file_has(cfg_name, "\nPort=4") && !file_has(cfg_name, "Port = 3"),
	"config: only the setting named Port changed");
  {
    gxConfig cfg(cfg_name);
    check(cfg.ChangeConfigValue("Port", "5\nAdmin = yes") == 0, "config: a value with a line break is refused");
    check(cfg.WriteConfigLine("New", "x\rAdmin = yes") == 0, "config: a new value with a line break is refused");
    check(cfg.WriteConfigLine("Bad\nName", "x") == 0, "config: a name with a line break is refused");
    check(cfg.WriteCommentLine("comment\nAdmin = yes") == 0, "config: a comment with a line break is refused");
    check(cfg.ChangeConfigValue("Timeout", "30") == 1, "config: a new setting is added");
  }
  check(!file_has(cfg_name, "Admin") && file_has(cfg_name, "Timeout=30"), "config: no line was injected");
  remove(cfg_name);

  // logfile
  {
    const char *log_name = "sweep_logfile.log"; // Not sweep.log: run_db_tests.bat writes the output there
    remove(log_name);
    LogFile log;
    check(log.Open(log_name) == 0, "logfile: open");
    log << "test" << "\n";
    log.Close();
    int o = owner_only(log_name);
    check(o != 0, o < 0 ? "logfile: owner-only (not checked on this system)" : "logfile: a new log file is mode 0600");
    LogFile log2;
    remove("sweep_logfile2.log");
    log2.OverWrite("sweep_logfile2.log");
    log2.Close();
    o = owner_only("sweep_logfile2.log");
    check(o != 0, "logfile: OverWrite() of a new file is owner-only");
    remove(log_name);
    remove("sweep_logfile2.log");
  }

  // findlast
  {
    gxString a("hello world"), b("aab"), c("abc");
    gxString e;
    check(a.FindLast("") == -1 && e.FindLast("x") == -1 && c.FindLast("abcd") == -1,
	  "findlast: empty pattern, empty string and long pattern return -1");
    check(a.FindLast("o") == 8 && a.FindLast("world") == 7 && b.FindLast("ab") == 2 &&
	  c.FindLast("a") == 1 && c.FindLast("x") == -1, "findlast: positions as in 6.2");
    gxString d("abaab");
    check(d.FindLast("aab") == 3, "findlast: a failed partial match does not hide the last match");
  }

  // membuf
  {
    MemoryBuffer empty, a("abc", 3);
    MemoryBuffer b = empty;  // Copy of an empty buffer
    a = empty;               // Assign an empty buffer (memmove from null)
    check(a.length() == 0 && b.length() == 0, "membuf: copy and assign of an empty buffer");
    a.Load(0, 0); a.Cat(0, 0); a += empty;
    check(a.length() == 0, "membuf: load and append of nothing");
    MemoryBlock blk; blk.Load(0, 0);
    check(blk.length() == 0, "membuf: MemoryBlock load of nothing");

    MemoryBuffer c("ab", 2);  // Exact size: no slack after the data
    check(c.Find((void *)"bc") == __MEMBUF_NO_MATCH__ &&
	  c.Find((const void *)"bc", 2) == __MEMBUF_NO_MATCH__, "membuf: a partial match at the end is not a match");
    check(c.Find((void *)"b") == 1 && c.Find((const void *)"b", 1) == 1 && c.Find((const void *)"ab", 2) == 0 &&
	  c.Find((void *)"ab", 1) == __MEMBUF_NO_MATCH__, "membuf: Find() positions");
    check(c.Find((void *)"a", 100) == __MEMBUF_NO_MATCH__ && c.Find((const void *)"a", 1, 100) == __MEMBUF_NO_MATCH__ &&
	  c.Find((const void *)"abc", 3) == __MEMBUF_NO_MATCH__, "membuf: offset or pattern past the end");
    MemoryBuffer f("aab", 3);
    check(f.Find((void *)"ab") == 1 && f.Find((const void *)"ab", 2) == 1, "membuf: match after a failed partial match");

    MemoryBuffer d("xy", 2);
    __MEMBUF_INT__ n = d.InsertAt(10, "1234", 4); // Position past the end
    check(n == 4 && d.length() == 6 && memcmp(d.m_buf(), "xy1234", 6) == 0,
	  "membuf: InsertAt() past the end appends");
    n = d.DeleteAt(2, 0xFFFFFFFF); // position + bytes wraps
    check(n == 4 && d.length() == 2 && memcmp(d.m_buf(), "xy", 2) == 0,
	  "membuf: DeleteAt() with a size that wraps");
    MemoryBuffer e(8);
    check(e.MemSet('z', 4, 0xFFFFFFFE) == 0 && e.MemSet('z', 4, 4) == 1, "membuf: MemSet() with a size that wraps is refused");
    MemoryBuffer g("ab", 2);
    check(g[(__MEMBUF_INT__)100] == 0 && g[(__MEMBUF_INT__)1] == 'b', "membuf: operator[] past the end of a full buffer");
  }

  // gxstring
  {
    gxString a("hello world"), e, z("");
    check(a.Mid(6, 0xFFFFFFF0) == "world" && a.Mid(0, 5) == "hello" && a.Mid(6, 0) == "world" &&
	  a.Left(0xFFFFFFFF) == "hello world" && a.Left(5) == "hello" &&
	  a.Right(0xFFFFFFFF) == "hello world" && a.Right(5) == "world" &&
	  a.Mid(100, 3) == "d", "gxstring: Mid/Left/Right clamp counts past the end");
    check(e.Mid(3, 4).length() == 0 && e.Left(2).length() == 0 && e.Right(2).length() == 0 &&
	  z.Mid(1, 0xFFFFFFFF).length() == 0, "gxstring: substrings of an empty string");
    gxString b("ab");
    b.InsertAt(100, "XYZ");
    check(b == "abXYZ" && b.length() == 5, "gxstring: InsertAt() past the end appends");
    gxString c("abcdef");
    c.DeleteAt(2, 0xFFFFFFFF);
    check(c == "ab" && c.length() == 2, "gxstring: DeleteAt() with a count that wraps");
    gxString d("aaaa");
    check(d.ReplaceChar('a', 'b', 2) == 2 && d == "aabb" && d.ReplaceChar('a', 'c', 10) == 0,
	  "gxstring: ReplaceChar() with an offset stays in the string");
    gxString f("");
    f.SetLength(10);
    check(f.length() == 10 && f.dlength() >= 10, "gxstring: SetLength() on an empty string resizes it");
    gxString g("ab%4");
    g.ConvertEscapeSeq('%', 80); // Octets past the end of the string
    check(g.length() == 3 && g[2] == 4, "gxstring: ConvertEscapeSeq() at the end of the string");
    gxString h("x%41y%");
    check(h.ConvertEscapeSeq('%', 81) >= 1, "gxstring: ConvertEscapeSeq() with 81 octets");
    gxString k("%41%42");
    check(k.ConvertEscapeSeq('%', 2) == 2 && k == "AB", "gxstring: ConvertEscapeSeq() as before");
    gxString m;
    m << 1e300;
    check(m.length() > 300 && m[0] == '1', "gxstring: operator<< of 1e300");
    gxString q;
    q << 2.5;
    check(q == "2.5", "gxstring: operator<< of 2.5");
  }

  // strutil
  {
    char *ab = new char[2]; ab[0] = 'a'; ab[1] = 'b'; // Not null-terminated
    check(FindMatch(ab, "bc", 0, 2, 2) == -1 && FindMatch(ab, "b", 0, 2, 1) == 1 &&
	  IFindMatch(ab, "BC", 0, 2, 2) == -1 && IFindMatch(ab, "AB", 0, 2, 2) == 0,
	  "strutil: a partial match at the end of the source is not a match");
    delete[] ab;
    check(FindMatch("abab", "ab", 1, 0, 0) == 2 && FindMatch("aab", "ab", 0, 0, 0) == 1 &&
	  FindMatch("abc", "", 0, 0, 0) == -1 && IFindMatch("xAaB", "ab", 0, 0, 0) == 2, "strutil: FindMatch() positions as before");
#if defined (__64_BIT_DATABASE_ENGINE__) || defined (__ENABLE_64_BIT_INTEGERS__)
    StringToLLWORD("99999999999999999999999");
    StringToLLWORD("-99999999999999999999999");
    check(StringToLLWORD("-42") == -42 && StringToLLWORD("123") == 123,
	  "strutil: StringToLLWORD() with too many digits (UBSan) and as before");
    char nb[100];
    check(strcmp(LLWORDToString(nb, (__ULLWORD__)(__LLWORD__)-5, 10), "-5") == 0 &&
	  strcmp(LLWORDToString(nb, 255, 16), "FF") == 0, "strutil: LLWORDToString() of a negative value");
    check(strcmp(ULLWORDToString(nb, 5, 1), "5") == 0 && strcmp(ULLWORDToString(nb, 12, 0), "12") == 0,
	  "strutil: a bad radix gives base 10");
#endif
  }

  // strutil: StringANCompare
  {
    check(StringANCompare("1", "12", 1) < 0 && StringANCompare("12", "1", 1) > 0 &&
	  StringANCompare("a2", "a10", 0) < 0 && StringANCompare("abc", "abc", 1) == 0,
	  "strutil: StringANCompare() with digits to the end of a string");
  }

  // dfile
  {
    const char *fn = "sweep_dfile.txt";
    FILE *fp = fopen(fn, "wb"); fputs("abc", fp); fclose(fp);
    DiskFileB f;
    check(f.df_Open(fn, DiskFileB::df_READONLY) == DiskFileB::df_NO_ERROR, "dfile: open");
    char buf[16];
    memset(buf, 'x', sizeof(buf));
    check(f.df_Read(buf, 3) == DiskFileB::df_NO_ERROR && f.df_gcount() == 3 && memcmp(buf, "abc", 3) == 0,
	  "dfile: a full read as before");
    check(f.df_Read(buf, 4) == DiskFileB::df_EOF_ERROR && f.df_gcount() == 0,
	  "dfile: a read at the end of the file is an EOF error with no bytes");
    check(f.df_Read(buf, 2, (FAU_t)1) == DiskFileB::df_NO_ERROR && f.df_gcount() == 2 &&
	  f.df_Read(buf, 8, (FAU_t)1) == DiskFileB::df_EOF_ERROR && f.df_gcount() == 2,
	  "dfile: a short read as before");
    f.df_Rewind();
    char *one = new char[1];
    check(f.df_GetLine(one, 0) != DiskFileB::df_NO_ERROR, "dfile: df_GetLine() with no room is refused");
    delete[] one;
    f.df_Close();
    DiskFileB g;
    g.df_Create(fn);
    g.df_Text();
    g << 1e300;
    g.df_Close();
    check(futils_filelength(fn) > 300, "dfile: text output of 1e300");
    remove(fn);

    char np[1024];
    futils_pathsimplify("./a//b/../c/./d/", np, '/');
    check(strcmp(np, "a/c/d") == 0, "futils: path simplify (overlapping copies)");
    char longname[600], out[futils_MAX_NAME_LENGTH + 8];
    memset(longname, 'n', sizeof(longname) - 1); longname[sizeof(longname)-1] = 0;
    check(futils_genoutputfilename(longname, out, (char *)".x") != 0 &&
	  futils_genoutputfilename("file.txt", out, (char *)".out") == 0 && strcmp(out, "file.out") == 0,
	  "futils: output file name of a long name");
    char mode[200];
    memset(mode, '7', sizeof(mode) - 1); mode[sizeof(mode)-1] = 0;
    check(futils_chmod("sweep_no_such_file", mode) != 0, "futils: chmod with a long mode string");
  }

  // devcache
  {
    gxDeviceBucketCache cache(4);
    check(cache.ConstructCache(0) != 0 && cache.BucketsInUse() == 0, "devcache: a cache of 0 buckets gets one");
    EHandler eh;
    eh.Message("security sweep: ", 0, 0);
    eh.DisplayException(0);
    check(1, "ehandler: null messages");
  }

  // parsers
  {
    char sbuf[300];
    memset(sbuf, '1', 299); sbuf[299] = 0;
    gxIP32 ip(sbuf);
    gxIP32 ip2("192.168.1.20");
    check(ip2.c_str(sbuf) && strcmp(sbuf, "192.168.1.20") == 0, "parsers: gxIP32 of a long digit string and as before");
    memset(sbuf, 'a', 299); sbuf[299] = 0;
    gxMAC48 mac(sbuf);
    gxMAC48 mac4("0060.B0F9.B895.1234.5678", '.', 4); // Extra groups
    gxMAC48 mac2("00:60:B0:F9:B8:95");
    check(strcmp(mac2.c_str(sbuf), "00:60:B0:F9:B8:95") == 0, "parsers: gxMAC48 with extra groups and as before");
    gxMAC48 mac5("0060.B0F9.B895", '.', 4);
    check(mac5 == mac2, "parsers: gxMAC48 four digit groups as before");
    memset(sbuf, '1', 299); sbuf[299] = 0;
    CDate d1(sbuf);
    CDate d2("12/31/2026");
    CDate d3("//");
    check(d2.GetMonth() == 12 && d2.GetDay() == 31 && d2.GetYear() == 2026 && d3.GetYear() == 0,
	  "parsers: CDate of a long string, empty groups, and as before");
    const char *pages[] = { "&#12;", "</SCRIPT>", "</STYLE><b>", "<a href=x>&#", 0 };
    int ok = 1;
    for(int i = 0; pages[i]; i++) {
      MemoryBuffer mb(pages[i], (unsigned)strlen(pages[i]));
      gxsHTML html;
      html.LoadMemoryBuffer(mb);
      gxListNode<gxsScriptInfo> *sp = html.GetScriptList()->GetHead();
      for(; sp; sp = sp->next) if(sp->data.script_length > 100) ok = 0;
    }
    check(ok, "parsers: gxsHTML tags at the start and closing tags without opening tags");
  }

  // rdbms
  {
    gxrdDatabaseRecord r;
    check(r.CreateRecord("T,CHAR[8],INT32") == gxDBASE_NO_ERROR, "rdbms: record created");
    MemoryBuffer shortrec("abc", 3);
    check(r.LoadDiskRecord(shortrec) == gxDBASE_BAD_RECORD, "rdbms: a disk record shorter than its header is refused");
    MemoryBuffer disk;
    r.CreateDiskRecord(disk);
    check(r.LoadDiskRecord(disk) == gxDBASE_NO_ERROR, "rdbms: a disk record loads as before");
    gxrdDatabaseRecord r2;
    check(r2.CreateRecord("T,CHAR[-1],INT32[-2],CHAR[4]") == gxDBASE_NO_ERROR &&
	  r2.FieldLength(0) == 1 && r2.FieldLength(1) == sizeof(gxINT32) && r2.FieldLength(2) == 4,
	  "rdbms: negative array lengths get one element");
  }

  // base64
  {
    const char *plain[] = { "", "f", "fo", "foo", "foob", "fooba", "foobar",
			    "\xc3\xa9", "\xff\xfe\xfd\x80", 0 };
    const char *coded[] = { "", "Zg==", "Zm8=", "Zm9v", "Zm9vYg==", "Zm9vYmE=",
			    "Zm9vYmFy", "w6k=", "//79gA==", 0 };
    int ok = 1;
    for(int i = 0; plain[i]; i++) {
      char enc[64], dec[64];
      memset(enc, 0x55, sizeof(enc));
      gxsBase64Encode(plain[i], enc, (int)strlen(plain[i]));
      if(strcmp(enc, coded[i]) != 0) {
	printf("     base64: \"%s\" encoded as \"%s\", expected \"%s\"\n", plain[i], enc, coded[i]);
	ok = 0;
      }
      gxsBase64Decode(coded[i], dec);
      if(strcmp(dec, plain[i]) != 0) ok = 0;
    }
    check(ok, "base64: RFC 4648 vectors and bytes over 0x7f encode and decode");
    unsigned char all[256];
    for(int i = 0; i < 256; i++) all[i] = (unsigned char)(255 - i);
    char enc[400], dec[300];
    gxsBase64Encode((const char *)all, enc, 255); // Without a 0 byte to stop the decode
    gxsBase64Decode(enc, dec);
    check(memcmp(dec, all, 255) == 0, "base64: every byte value round trips");
  }

#if defined (__USE_GX_SSL_EXTENSIONS__) && !defined (__USE_GX_SCHANNEL__)
  // rsa_key
  {
    const char *key_name = "sweep_key.pem";
    remove(key_name);
    gxSSL ssl;
    int rv = ssl.MakeRSAPrivateKey(key_name, 2048);
    check(rv == 0, "rsa_key: key written");
    int o = owner_only(key_name);
    check(o != 0, "rsa_key: the private key file is mode 0600");
    remove(key_name);
  }
#endif

  if(failures) {
    printf("%d security sweep tests failed\n", failures);
    return 1;
  }
  printf("All security sweep tests passed\n");
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++17)

examples_modern/general/security_sweep/modern.cpp 191 lines
#include <array>
#include <charconv>
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <optional>
#include <stdexcept>
#include <string>
#include <string_view>
#include <vector>

namespace fs = std::filesystem;
static int failures = 0;

static void check(bool ok, const char *what)
{
  std::cout << (ok ? "PASS: " : "FAIL: ") << what << "\n";
  if(!ok) failures++;
}

// ---- base64 (RFC 4648) ------------------------------------------ //
static const char b64[] =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

std::string base64_encode(std::string_view in)
{
  std::string out;
  std::uint32_t acc = 0;
  int bits = 0;
  for(unsigned char c : in) {        // unsigned: bytes >= 0x80 are safe
    acc = (acc << 8) | c;
    bits += 8;
    while(bits >= 6) { bits -= 6; out += b64[(acc >> bits) & 0x3f]; }
  }
  if(bits) out += b64[(acc << (6 - bits)) & 0x3f];
  while(out.size() % 4) out += '=';
  return out;
}

std::optional<std::string> base64_decode(std::string_view in)
{
  if(in.size() % 4) return std::nullopt;
  std::string out;
  std::uint32_t acc = 0;
  int bits = 0;
  std::size_t pad = 0;
  for(std::size_t i = 0; i < in.size(); i++) {
    char c = in[i];
    if(c == '=') { if(i + 2 < in.size()) return std::nullopt; pad++; continue; }
    if(pad) return std::nullopt;
    const char *p = std::char_traits<char>::find(b64, 64, c);
    if(!p) return std::nullopt;      // Not a base64 character
    acc = (acc << 6) | std::uint32_t(p - b64);
    bits += 6;
    if(bits >= 8) { bits -= 8; out += char((acc >> bits) & 0xff); }
  }
  return out;
}

// ---- config whole-name match ------------------------------------ //
bool set_value(std::vector<std::string> &lines, std::string_view name,
               std::string_view value)
{
  if(value.find_first_of("\r\n") != std::string_view::npos) return false;
  for(auto &line : lines) {
    auto eq = line.find('=');
    if(line.empty() || line[0] == '#' || eq == std::string::npos) continue;
    if(std::string_view(line).substr(0, eq) == name) {
      line = std::string(name) + "=" + std::string(value);
      return true;
    }
  }
  return false;
}

// ---- IPv4 parser ------------------------------------------------- //
std::optional<std::array<std::uint8_t, 4>> parse_ipv4(std::string_view s)
{
  std::array<std::uint8_t, 4> ip{};
  for(std::size_t i = 0; i < 4; i++) {
    unsigned v = 0;
    auto [p, ec] = std::from_chars(s.data(), s.data() + s.size(), v);
    if(ec != std::errc() || v > 255 || p == s.data()) return std::nullopt;
    ip[i] = std::uint8_t(v);
    s.remove_prefix(std::size_t(p - s.data()));
    if(i < 3) {
      if(s.empty() || s[0] != '.') return std::nullopt;
      s.remove_prefix(1);
    }
  }
  if(!s.empty()) return std::nullopt;  // Extra groups or text
  return ip;
}

int main()
{
  // config
  std::vector<std::string> cfg = {"# Name=commented", "LongName=1", "Name=2"};
  check(set_value(cfg, "Name", "3") && cfg[1] == "LongName=1" &&
        cfg[2] == "Name=3", "config: only the whole name is changed");
  check(!set_value(cfg, "Name", "a\nInjected=1"), "config: line break refused");

  // logfile
  {
    const fs::path f = "modern_sweep.log";
    std::ofstream(f) << "log\n";
    fs::permissions(f, fs::perms::owner_read | fs::perms::owner_write,
                    fs::perm_options::replace);
    auto p = fs::status(f).permissions();
#if defined(_WIN32)
    check(true, "logfile: permissions (POSIX bits not used on Windows)");
#else
    check((p & (fs::perms::group_all | fs::perms::others_all)) == fs::perms::none,
          "logfile: owner-only");
#endif
    fs::remove(f);
  }

  // base64
  check(base64_encode("foobar") == "Zm9vYmFy" && base64_encode("fo") == "Zm8=",
        "base64: RFC 4648 test vectors");
  std::string high("\x80\xff\xfe\x81", 4);
  check(base64_decode(base64_encode(high)) == high, "base64: bytes >= 0x80");
  check(!base64_decode("Zm9v!mFy") && !base64_decode("Zm9") &&
        !base64_decode("Z=9v"), "base64: bad input refused");

  // findlast
  std::string s = "abcabc";
  check(s.rfind("bc") == 4, "findlast: rfind finds the last match");
  check(s.rfind("") == s.size(),
        "findlast: rfind(\"\") is size() (gxString::FindLast gives -1)");

  // buffers
  std::vector<unsigned char> v(4);
  bool threw = false;
  try { v.at(4) = 1; } catch(const std::out_of_range &) { threw = true; }
  check(threw, "buffers: vector::at() past the end throws");
  threw = false;
  try { (void)s.substr(7); } catch(const std::out_of_range &) { threw = true; }
  check(threw, "buffers: substr() with a start past the end throws");
  check(s.substr(2, std::string::npos - 1) == "cabc",
        "buffers: substr() count past the end is clamped");
  std::string e = s;
  e.erase(1, std::size_t(-1));
  check(e == "a", "buffers: erase() count that would wrap is clamped");
  std::vector<unsigned char> empty, copy(empty);
  check(copy.empty(), "buffers: copy of an empty buffer");

  // numbers
  int iv = 0;
  std::string_view big = "99999999999";
  check(std::from_chars(big.data(), big.data() + big.size(), iv).ec ==
        std::errc::result_out_of_range, "numbers: int overflow reported");
  std::uint64_t u = 0;
  std::string_view neg = "-5";
  check(std::from_chars(neg.data(), neg.data() + neg.size(), u).ec ==
        std::errc::invalid_argument, "numbers: minus sign refused for unsigned");
  std::string_view junk = "12ab";
  auto r = std::from_chars(junk.data(), junk.data() + junk.size(), iv);
  check(r.ptr == junk.data() + 2, "numbers: parse stops at junk (caller checks ptr)");
  char small[4];                     // "1e+300" needs 6
  check(std::to_chars(small, small + sizeof small, 1e300).ec ==
        std::errc::value_too_large, "numbers: to_chars reports a short buffer");

  // dfile
  {
    const fs::path f = "modern_sweep.dat";
    std::ofstream(f, std::ios::binary) << "1234";
    std::ifstream in(f, std::ios::binary);
    char buf[8];
    in.read(buf, 4);
    in.read(buf, 8);
    check(in.eof() && in.gcount() == 0, "dfile: read at the end reads 0 bytes");
    in.close();
    fs::remove(f);
  }

  // parsers
  check(parse_ipv4("192.168.1.10").has_value(), "parsers: good IPv4");
  check(!parse_ipv4("1.2.3.4.5") && !parse_ipv4("1.2.3.256") &&
        !parse_ipv4("1.2.3") && !parse_ipv4("99999999999.1.1.1"),
        "parsers: bad IPv4 refused");

  std::cout << (failures ? "FAILED" : "All checks passed") << "\n";
  return failures ? 1 : 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=17
cmake --build build-modern --target general_security_sweep
./build-modern/general_security_sweep
# or without CMake:
g++ -std=c++17 -pthread -o general_security_sweep examples_modern/general/security_sweep/modern.cpp

Output of the modern program

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

PASS: config: only the whole name is changed
PASS: config: line break refused
PASS: logfile: owner-only
PASS: base64: RFC 4648 test vectors
PASS: base64: bytes >= 0x80
PASS: base64: bad input refused
PASS: findlast: rfind finds the last match
PASS: findlast: rfind("") is size() (gxString::FindLast gives -1)
PASS: buffers: vector::at() past the end throws
PASS: buffers: substr() with a start past the end throws
PASS: buffers: substr() count past the end is clamped
PASS: buffers: erase() count that would wrap is clamped
PASS: buffers: copy of an empty buffer
PASS: numbers: int overflow reported
PASS: numbers: minus sign refused for unsigned
PASS: numbers: parse stops at junk (caller checks ptr)
PASS: numbers: to_chars reports a short buffer
PASS: dfile: read at the end reads 0 bytes
PASS: parsers: good IPv4
PASS: parsers: bad IPv4 refused
All checks passed