DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_https_client

C++20 or laterDataReel 6.4.3Portable C++ (tested on Linux)

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

Modern equivalent of the HTTPS client example. gxsHTTPSClient and gxSSL stay. Certificate checking is on, not left in comments: the client is given a CA list and RequireVerifyCert(), and the test certificate is the CA. The body is read into a MemoryBuffer and copied once into a std::string. With no arguments the example makes a self-signed test certificate and runs a TLS server on 127.0.0.1 (TlsServer in ../common/modern_tls.h, a std::jthread); with "URL [CA_FILE]" it fetches a real page (CA_FILE defaults to the system bundle).

Windows Schannel builds (the default) cannot make keys or certificates: put modern_test_key.pem and modern_test_cert.pem, made with openssl (CN localhost) or by a Linux run of this program, in the folder first.

Legacy calls in this program

LegacyModern C++StandardNotes
gxString / UStringstd::string, std::string_viewC++98 / C++17string_view looks at text without copying it.
gxList, gxListNodestd::list; splice() for MoveBefore()/MoveAfter()C++98The list owns its nodes: no DestroyList()/DestroyArrayList().
DiskFileBstd::fstream (read, write, seekg/seekp, tellg)C++98
gxSSLkeep gxSSL; certificate checking on (SetCAList + RequireVerifyCert); RAII closeC++11

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_socket/https_client/testprog.cpp 328 lines
#include "gxdlcode.h"

#if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library
#include <iostream>
using namespace std; // Use unqualified names for Standard C++ library
#else // Use the old iostream library by default
#include <iostream.h>
#endif // __USE_ANSI_CPP__

#include "gxshttpc.h"
#include "dfileb.h"

#ifdef __MSVC_DEBUG__
#include "leaktest.h"
#endif

// Version number and program name
const double ProgramVersionNumber = 1.1;
const char *ProgramName = "testprog";

// Program globals
int get_doc_header = 0; // True if request a document header only
int get_document = 0;   // True if requesting a document 

void HelpMessage(const char *program_name, const double version_number)
{
  cout << "\n";
  cout.setf(ios::showpoint | ios::fixed);
  cout.precision(1);
  cout << "\n";
  cout << program_name << " version " << version_number  << "\n";
  cout << "Usage: " << program_name << " [switches] URL" << "\n";
  cout << "Example: " << program_name << " -h https://www.yahoo.com"
       << "\n";
  cout << "Switches: " << "\n";
  cout << "          -d = Download the specified file only (default)." << "\n";
  cout << "          -h = Get a document header." << "\n";
  cout << "\n";
}

int ProcessArgs(char *arg)
{
  switch(arg[1]) {
    case 'h':
      get_doc_header = 1;
      get_document = 0;
      break;

    case 'd':
      get_doc_header = 0;
      get_document = 1;
      break;
      
    default:
      cerr << "\n";
      cerr << "Unknown switch " << arg << "\n";
      cerr << "Exiting..." << "\n";
      cerr << "\n";
      return 0;
  }
  arg[0] = '\0';

  return 1; // All command line arguments were valid
}

void PrintHTTPHeader(const gxsHTTPHeader &hdr)
{
  cout << "\n" << flush;  
  cout << "<------ Document Header ------>" << "\n" << flush;
  cout << hdr.http_header.c_str();
  cout << "<----------------------------->" << "\n" << flush;
  cout << "\n" << flush;
  cout << "Press Enter to continue..." << "\n" << flush;
  cin.get();
  
  cout << "Processing the header information..." << "\n" 
	      << flush;
  cout << gxsHTTPStatusCodeMessage(hdr.http_status) << "\n" 
	      << flush;

  cout.setf(ios::showpoint | ios::fixed);
  cout.precision(1);
  cout << "HTTP version: " << hdr.http_version << "\n" << flush;

  cout << "Document status code: " << hdr.http_status << "\n" 
	      << flush;
  if(hdr.current_server.length() > 0) {
    cout << "Current Server: " << hdr.current_server.c_str() << "\n" 
		<< flush;
  }
  if(hdr.location.length() > 0) {
    cout << "Location: " << hdr.location.c_str() << "\n" 
		<< flush;
  }
  if(hdr.http_last_modified.length() > 0) {
    cout << "Date Document Last Modified: " 
		<< hdr.http_last_modified.c_str() << "\n" << flush;
  }
  if(hdr.date.length() > 0) {
    cout << "Date: " << hdr.date.c_str() << "\n" << flush;
  }
  if(hdr.http_expires.length() > 0) {
    cout << "Expires: " << hdr.http_expires.c_str() << "\n" 
		<< flush;
  }
  if(hdr.etag.length() > 0) {
    cout << "Entity tag: " << hdr.etag.c_str() << "\n" << flush;
  }
  if(hdr.authentication_needed) {
    cout << "Authentication required" << "\n" << flush;
  }
  if(hdr.authentication_scheme.length() > 0) {
    cout << "Authentication scheme: " 
		<< hdr.authentication_scheme.c_str() << "\n" << flush;
  }
  if(hdr.realm.length() > 0) {
    cout << "Authentication realm: " << hdr.realm.c_str() << "\n" 
		<< flush;
  }
  if(hdr.auth_cookie.length() > 0) {
    cout << "Authentication cookie: " << hdr.auth_cookie.c_str() 
		<< "\n" << flush;
  }
  if(hdr.content_encoding.length() > 0) {
    cout << "Content encoding: " << hdr.content_encoding.c_str() 
		<< "\n" << flush;
  }
  if(hdr.pragma.length() > 0) {
    cout << "Pragma: " << hdr.pragma.c_str() << "\n" << flush;
  }
  if(hdr.cache_control.length() > 0) {
    cout << "Cache control: " << hdr.cache_control.c_str() << "\n" 
		<< flush;
  }
  
  if(hdr.file_extension.length() > 0) {
    cout << "File extension: " << hdr.file_extension.c_str() << "\n" 
		<< flush;
  }
  if(hdr.length > -1) {
    cout << "Document length: " << hdr.length << "\n" << flush;
  }
  if(hdr.not_found) {
    cout << "The requested document was not found" << "\n" 
		<< flush;
  }
  if(!hdr.no_cache) {
    cout << "Using cached copy of the requested document" << "\n" 
		<< flush;
  }
  if(hdr.accept_ranges) {
    cout << "Accepting ranges" << "\n" << flush;
  }
  if(hdr.timeout > -1) {
    cout << "Timeout: " << hdr.timeout << "\n" << flush;
  }
  if(hdr.max_conns > -1) {
    cout << "Max connects: " << hdr.max_conns << "\n" << flush;
  }
  if(!hdr.keep_alive) {
    cout << "The server has closed this connection" << "\n" 
		<< flush;
  }

  gxListNode<gxsNetscapeCookie> *netscape_cookies = \
    hdr.netscape_cookies.GetHead();
  if(netscape_cookies) {
    cout << "\n" << flush;
    cout << "Cookie information. Press Enter to continue..." 
		<< "\n" << flush;
    cin.get();

    while(netscape_cookies) {
      gxsNetscapeCookie citem(netscape_cookies->data);

      cout << "Hostname: " << citem.host.c_str() << "\n" 
		  << flush;
      cout << "Name: " << citem.name.c_str() << "\n" << flush;
      cout << "Value: " << citem.value.c_str() << "\n" << flush;
      if(citem.expires.length() > 0) {
	cout << "Expires: " << citem.expires.c_str() << "\n" 
		    << flush;
      }
      if(citem.domain.length() > 0) {
	cout << "Domain: " << citem.domain.c_str() << "\n" 
		    << flush;
      }
      if(citem.path.length() > 0) {
	cout << "Path: " << citem.path.c_str() << "\n" << flush;
      }
      if(citem.secure) {
	cout << "This is a secure cookie" << "\n" << flush;
      }

      netscape_cookies = netscape_cookies->next;
      
      if(netscape_cookies) {
	cout << "\n" << flush;
	cout << "Cookie information. Press Enter to continue..." 
		    << "\n" << flush;
	cin.get();
      }
    }
  }
}

void GetDocumentHeader(char *URL)
{
  gxsURL url;
  gxsURLInfo u;
  gxString web_url(URL);
  
  if(!url.ParseURL(web_url, u)) {
    cout << "Error parsing url" << "\n";
    return;
  }

  gxsHTTPSClient httpc;
  gxsHTTPHeader hdr;

  if(httpc.RequestHeader(u, hdr) != 0) {
    cout << httpc.SocketExceptionMessage() << "\n";
    cout << httpc.openssl.SSLExceptionMessage() << "\n";
    return;
  }

  PrintHTTPHeader(hdr);
}

void DownloadFile(const char *URL)
{
  gxsHTTPSClient client;

  gxsURL url;
  gxsURLInfo u;
  if(!url.ParseURL(URL, u)) {
    cout << "Error parsing URL" << "\n";
  }

  // Construct the local file name based on the URL information
  gxString sbuf(u.dir);
  if(u.file == "?") { // Is this a file or directory
    while(sbuf.DeleteBeforeIncluding("/")) ;
    u.file = sbuf;
    u.dir.DeleteAfterIncluding(sbuf.c_str());
  }
  if(!u.file) {
    u.file = "index.html";
  }

  // Open the local file
  DiskFileB outfile(u.file.c_str(), DiskFileB::df_WRITEONLY,
		    DiskFileB::df_CREATE);
  if(!outfile) {
    cout << outfile.df_ExceptionMessage() << "\n";
    return;
  }
  
  cout << "Connecting to: " << u.host << "\n";
  cout << "Downloading: " << u.path << "\n";

  // client.openssl.SetCertFile("client_cert.pem");
  // client.openssl.SetKeyFile("client_key.pem");
  // client.openssl.SetPasswd("keypassphrase");
  // client.openssl.SetRandomFile("random_number_file");

  // Cert verification, requires a trusted CA list 
  // client.openssl.SetCAList("/etc/pki/tls/certs/ca-bundle.crt");
  // client.openssl.RequireVerifyCert();

  gxsHTTPHeader hdr;
  if(client.Request(u, hdr, outfile.df_FileStream()) != 0) {
    cout << client.SocketExceptionMessage() << "\n";
    cout << client.openssl.SSLExceptionMessage() << "\n";
    return;
  }

  client.Flush();
}

// Program's main thread of execution.
// ----------------------------------------------------------- 
int main(int argc, char **argv)
{
#ifdef __MSVC_DEBUG__
  InitLeakTest();
#endif

  if(argc < 2) { 
    HelpMessage(ProgramName, ProgramVersionNumber);
    return 0;
  }
  
  // Process command ling arguments and files 
  int narg;
  char *arg = argv[narg = 1];
  while (narg < argc) {
    if (arg[0] != '\0') {
      if (arg[0] == '-') { // Look for command line arguments
	if(!ProcessArgs(arg)) return 0; // Exit if argument is not valid
      }
      else { 
	if(get_document) {
	  cout << "\n";
	  cout << "Downloading: " << arg << "\n";
	  DownloadFile((const char *)arg);
	}
	else if(get_doc_header) {
	  cout << "\n";
	  cout << "Requesting document header: " << arg << "\n";
	  GetDocumentHeader(arg);
	}
	else { // Default if no argument is specifed
	  cout << "\n";
	  cout << "Downloading: " << arg << "\n";
	  DownloadFile((const char *)arg);
	}
      }
      arg = argv[++narg];
    }
  }
  
  return 0;
}
// ----------------------------------------------------------- //
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/socket/https_client/modern.cpp 54 lines
#include <iostream>
#include <string>

#include "../common/modern_tls.h"
#include "gxshttpc.h"
#include "gxsurl.h"
#include "membuf.h"

using namespace modern_net;

int main(int argc, char **argv)
{
  SocketLibrary lib;
  std::string url_text, ca;
  std::unique_ptr<TlsServer> server;
  if(argc > 1) {
    url_text = argv[1];
    ca = argc > 2 ? argv[2] : "/etc/pki/tls/certs/ca-bundle.crt";
  }
  else {
    if(!make_test_cert("modern_test_key.pem", "modern_test_cert.pem")) {
      std::cout << "Cannot make a test certificate\n";
      return 1;
    }
    server = std::make_unique<TlsServer>("modern_test_cert.pem", "modern_test_key.pem",
      "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 18\r\n\r\nHello over TLS 1.3");
    int port = server->start();
    if(port < 0) { std::cout << "TLS server: " << server->error() << "\n"; return 1; }
    url_text = "https://localhost:" + std::to_string(port) + "/";
    ca = "modern_test_cert.pem";                 // Trust only the test cert
  }
  gxsURL url;
  gxsURLInfo u;
  if(!url.ParseURL(url_text.c_str(), u)) { std::cout << "Bad URL\n"; return 1; }

  gxsHTTPSClient client;
  client.openssl.SetCAList(ca.c_str());
  client.openssl.RequireVerifyCert();            // Check the server's certificate
  gxsHTTPHeader hdr;
  MemoryBuffer mbuf;
  if(client.Request(u, hdr, mbuf) != 0) {
    std::cout << client.SocketExceptionMessage() << "\n"
              << client.openssl.SSLExceptionMessage() << "\n";
    return 1;
  }
  std::string body(reinterpret_cast<const char *>(mbuf.m_buf()), mbuf.length());
  std::cout << "Status " << hdr.http_status << ", " << body.size() << " bytes: "
            << body.substr(0, 200) << "\n";
  return hdr.http_status == 200 ? 0 : 1;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- 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_https_client
./build-modern/socket_https_client

Output of the modern program

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

Status 200, 18 bytes: Hello over TLS 1.3