Examples › Socket Examples
socket_ssl_server
Legacy: examples_socket/ssl_server/m_thread.cpp, examples_socket/ssl_server/server.cpp · Modern: examples_modern/socket/ssl_server/modern.cpp
Modern equivalent of the multi-threaded HTTPS server. The legacy server is a gxThread subclass with a console thread that waits for "quit", and it stops by canceling the thread blocked in accept(). Here:
- One std::jthread accepts connections, waiting in select() with a timeout and checking its std::stop_token; each connection is served by its own std::jthread kept in a std::vector.
- Each connection's gxSSL shares the server's SSL context and is cleaned up by an RAII guard on every path.
- The number of requests served is a std::atomic.
- The key and self-signed certificate are made once with gxSSL (no prompts), and the server runs until the requests are done: main() sends several HTTPS requests at the same time with std::async and gxsHTTPSClient, with certificate checking on.
Usage: modern (self test) modern PORT (serve until Enter is pressed)
Windows Schannel builds (the default) cannot make keys or certificates: put modern_server_key.pem and modern_server_cert.pem, made with openssl (CN localhost) or by a Linux run of this program, in the folder first.
Legacy calls in this program
| Legacy | Modern C++ | Standard | Notes |
|---|---|---|---|
| gxThread subclass, CreateThread() | std::thread t(callable, args...) | C++11 | Any function, lambda or functor runs in the thread; arguments are copied with their types (no void *). |
| JoinThread() | t.join(); std::future::get() | C++11 | join() waits; a std::async future's get() also returns the result. |
| CancelThread(), ThreadCleanupHandler() | std::jthread::request_stop() + std::stop_token; cleanup in a destructor | C++20 | Cancellation is cooperative: the thread checks stop_requested() or waits on a condition_variable_any with the token. |
| thrPool, CreateThreadPool() | a small pool: std::thread workers, std::queue, std::condition_variable, std::packaged_task | C++11 (C++17 invoke_result) | submit() returns a std::future; the destructor joins the workers. |
| gxMutex, MutexLock()/MutexUnlock() | std::mutex + std::scoped_lock / std::lock_guard / std::unique_lock | C++11 / C++17 | The lock is released by a destructor on every path, so a return cannot leave it locked. |
| gxCondition, ConditionWait()/ConditionSignal() | std::condition_variable wait(lock, predicate) / notify_one() | C++11 | The predicate form handles spurious wake ups. |
| gxString / UString | std::string, std::string_view | C++98 / C++17 | string_view looks at text without copying it. |
| Atoi(), Atol(), Atof(), atoi() | std::from_chars() into std::optional<T>; std::stoi() | C++17 | Overflow and junk are reported, not turned into 0. |
| new / delete | automatic objects, containers, std::unique_ptr / std::make_unique | C++11 / C++14 | Ownership is in the type, and release() shows a hand-over. |
| strcpy(), strncpy(), memmove() into char arrays | std::string; std::array<char, N> + string_view::copy() | C++11 / C++17 | |
| futils_*(), df_mkdir(), df_copy() ... | std::filesystem (directory_iterator, create_directory, file_size, copy_file, rename, remove, current_path) | C++17 | Errors through std::error_code or std::filesystem_error. |
| gxSocket | keep gxSocket (C++ has no sockets); servers in std::jthread with std::stop_token and select() timeouts | C++20 | Stopping is a request, not a canceled thread blocked in accept(). |
| gxSSL | keep gxSSL; certificate checking on (SetCAList + RequireVerifyCert); RAII close | C++11 |
From the transition tables.
Side by side
DataReel 6.4 (legacy)
examples_socket/ssl_server/m_thread.cpp 344 lines
#include "gxdlcode.h" #if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library #include <iostream> #else // Use the old iostream library by default #include <iostream.h> #endif // __USE_ANSI_CPP__ #include <string.h> #include "m_thread.h" // -------------------------------------------------------------- // Globals variable initialzation // -------------------------------------------------------------- ServerConfig ServerConfigSruct; ServerConfig *servercfg = &ServerConfigSruct; // -------------------------------------------------------------- void ClientSocket_t::FreeSSL() { if(openssl) { openssl->ReleaseCTX(); // Do not free Context by ~gxSSL() call delete openssl; openssl = 0; } } int CheckSocketError(gxSocket *s, const char *mesg, int report_error) // Test the socket for an error condition and report the message // if the "report_error" variable is true. The "mesg" string is used // display a message with the reported error. Returns true if an // error was detected for false of no errors where detected. { if(s->GetSocketError() == gxSOCKET_NO_ERROR) { // No socket errors reported return 0; } if(report_error) { // Reporting the error to an output device if(mesg) { PrintMessage(mesg, "\n", s->SocketExceptionMessage()); } else { PrintMessage(s->SocketExceptionMessage()); } } return 1; } int CheckThreadError(gxThread_t *thread, const char *mesg, int report_error) // Test the thread for an error condition and report the message // if the "report_error" variable is true. The "mesg" string is used // display a message with the reported error. Returns true if an // error was detected for false of no errors where detected. { if(thread->GetThreadError() == gxTHREAD_NO_ERROR) { // No thread errors reported return 0; } if(report_error) { // Reporting the error to an output device if(mesg) { PrintMessage(mesg, "\n", thread->ThreadExceptionMessage()); } else { PrintMessage(thread->ThreadExceptionMessage()); } } return 1; } void ReportError(const char *s1, const char *s2, const char *s3) // Thread safe error reporting function. { PrintMessage(s1, s2, s3); } void PrintMessage(const char *s1, const char *s2, const char *s3) // Thread safe write function that will not allow access to // the critical section until the write operation is complete. { servercfg->display_lock.MutexLock(); // Ensure that all threads have finished writing to the device int num_try = 0; while(servercfg->display_is_locked != 0) { // Block this thread from its own execution if a another thread // is writing to the device if(++num_try < DISPLAY_THREAD_RETRIES) { servercfg->display_cond.ConditionWait(&servercfg->display_lock); } else { return; // Could not write string to the device } } // Tell other threads to wait until write is complete servercfg->display_is_locked = 1; // ********** Enter Critical Section ******************* // GXSTD::cout << "\n"; if(s1) GXSTD::cout << s1; if(s2) GXSTD::cout << s2; if(s3) GXSTD::cout << s3; GXSTD::cout << "\n"; GXSTD::cout.flush(); // Flush the ostream buffer to the stdio // ********** Leave Critical Section ******************* // // Tell other threads that this write is complete servercfg->display_is_locked = 0; // Wake up the next thread waiting on this condition servercfg->display_cond.ConditionSignal(); servercfg->display_lock.MutexUnlock(); } ServerConfig::ServerConfig() { port = 80; accept_clients = 1; display_is_locked = 0; client_request_pool = new thrPool; } ServerConfig::~ServerConfig() { if(client_request_pool) delete client_request_pool; } int ServerThread::InitServer(int max_connections) // Initialize the server. Returns a non-zero value if any // errors ocurr. { if(InitSocketLibrary() == 0) { if(InitSocket(SOCK_STREAM, servercfg->port) < 0) return 1; } else { return 1; } int val = 1; if(SetSockOpt(gxsocket, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0) { CheckSocketError((gxSocket *)this, "Error initializing server"); Close(); return 1; } // Bind the name to the socket if(Bind() < 0) { CheckSocketError((gxSocket *)this, "Error initializing server"); Close(); return 1; } // Listen for connections with a specified backlog if(Listen(max_connections) < 0) { CheckSocketError((gxSocket *)this, "Error initializing server"); Close(); return 1; } return 0; } void *ServerThread::ThreadEntryRoutine(gxThread_t *thread) { while(servercfg->accept_clients) { // Loop accepting client connections // Block the server until a client requests service if(Accept() < 0) { PrintMessage("Error accepting client connections"); return 0; } // NOTE: Getting client info for statistical purposes only char client_name[gxsMAX_NAME_LEN]; int r_port = -1; GetClientInfo(client_name, r_port); PrintMessage("Received client request from ", client_name); ClientSocket_t *s = new ClientSocket_t; if(!s) { ReportError("A fatal memory allocation error occurred\n \ Shutting down the server"); CloseSocket(); return (void *)0; } #if !defined (__USE_GX_SCHANNEL__) // Schannel uses the cipher suites set by the Windows TLS policy SSL_CTX_set_cipher_list(openssl.GetCTX(), "ALL"); #endif // Record the file descriptor assigned by the Operating System s->client_socket = GetRemoteSocket(); s->openssl = new gxSSL(openssl.GetCTX()); if(!s->openssl) { PrintMessage("A fatal memory allocation error occurred\n \ Shutting down the server"); delete s; return (void *)0; } // Destroy all the client threads that have exited RebuildThreadPool(servercfg->client_request_pool); // Create thread per cleint gxThread_t *rthread = \ request_thread.CreateThread(servercfg->client_request_pool, (void *)s); if(CheckThreadError(rthread, "Error starting client request thread")) { delete s; return (void *)0; } } return (void *)0; } void ServerThread::ThreadExitRoutine(gxThread_t *thread) // Thread exit function used to close the server thread. { CloseSocket(); // Close the server side socket } void ServerThread::ThreadCleanupHandler(gxThread_t *thread) // Thread cleanup handler used in the event that the thread is // canceled. { CloseSocket(); // Close the server side socket } void *ClientRequestThread::ThreadEntryRoutine(gxThread_t *thread) { // Extract the client socket from the thread parameter ClientSocket_t *s = (ClientSocket_t *)thread->GetThreadParm(); // Process the client request HandleClientRequest(s); return (void *)0; } void ClientRequestThread::ThreadExitRoutine(gxThread_t *thread) // Thread exit function used to close the client thread. { // Extract the client socket from the thread parameter ClientSocket_t *s = (ClientSocket_t *)thread->GetThreadParm(); // Close the client socket and free its resources s->openssl->CloseSSLSocket(); Close(s->client_socket); delete s; } void ClientRequestThread::ThreadCleanupHandler(gxThread_t *thread) // Thread cleanup handler used in the event that the thread is // canceled. { // Extract the client socket from the thread parameter ClientSocket_t *s = (ClientSocket_t *)thread->GetThreadParm(); // Close the client socket and free its resources s->openssl->CloseSSLSocket(); Close(s->client_socket); delete s; } void ClientRequestThread::HandleClientRequest(ClientSocket_t *s) // Function used to handle a client request. { if(s->openssl->OpenSSLSocket(s->client_socket) != gxSSL_NO_ERROR) { PrintMessage("Error opening SSL socket"); PrintMessage(s->openssl->SSLErrorMessage()); socket_error = gxSOCKET_SSL_ERROR; return; } if(s->openssl->AcceptSSLSocket() != gxSSL_NO_ERROR) { PrintMessage("Error accepting SSL socket"); PrintMessage(s->openssl->SSLErrorMessage()); socket_error = gxSOCKET_SSL_ERROR; gxString err; gxSSL::GlobalSSLError(err); PrintMessage(err.c_str()); return; } // NOTE: The demo processes a single HTTP GET request per client const int rxbuf = 1024; char request[rxbuf]; // Block until the client sends some data // 10/31/2026: Leave room for the null; a full read wrote past the end int rv = s->openssl->RawReadSSLSocket(request, rxbuf - 1); // A socket error occurred if(rv <= 0) { PrintMessage("Error reading SSL socket"); PrintMessage(s->openssl->SSLErrorMessage()); socket_error = gxSOCKET_RECEIVE_ERROR; return; } request[rv] = 0; // Null terminate the request string // At this point we need to parse the client request and process it. // For simplicity sake these operations have been omitted. // ... (parsing operation) // ... (processing operation) // Simply send a test page (with a header) back to the client. const char *test_page = "HTTP/1.0 200 OK\r\nServer: gxThread\r\nConnection: \ close\r\n\r\n<HTML>\n<HEAD>\n<TITLE> gxThread Test Page </TITLE>\n</HEAD>\ <BODY><CENTER><H1>gxThread Test Page</H1></CENTER><HR><PRE>Response from the \ multi-threaded HTTP server</PRE><HR><CENTER>End of document</CENTER>\n</BODY>\ \n</HTML>"; // Blocking send that will not return until all bytes are written // Send(s->client_socket, test_page, strlen(test_page)); // CheckSocketError((gxSocket *)this, "Error sending page to client"); rv = s->openssl->SendSSLSocket(test_page, strlen(test_page)); if(s->openssl->HasError()) { if(s->openssl->GetSSLError() == gxSSL_DISCONNECTED_ERROR) { PrintMessage("Error writing to SSL socket"); PrintMessage(s->openssl->SSLErrorMessage()); socket_error = gxSOCKET_DISCONNECTED_ERROR; } else { PrintMessage("Error writing to SSL socket"); PrintMessage(s->openssl->SSLErrorMessage()); socket_error = gxSOCKET_TRANSMIT_ERROR; } } if(rv != (int)strlen(test_page)) { PrintMessage("Error writing to SSL socket"); PrintMessage(s->openssl->SSLErrorMessage()); socket_error = gxSOCKET_TRANSMIT_ERROR; } CheckSocketError((gxSocket *)this, "Error sending page to client"); } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
examples_socket/ssl_server/server.cpp 252 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 <string.h> #include <stdlib.h> #include "m_thread.h" class ConsoleThread : public gxThread { public: ConsoleThread() { } ~ConsoleThread() { } private: void *ThreadEntryRoutine(gxThread_t *thread); }; void *ConsoleThread::ThreadEntryRoutine(gxThread_t *thread) { const int cmd_len = 255; char sbuf[cmd_len]; while(1) { for(int i = 0; i < cmd_len; i++) sbuf[i] = 0; // 10/14/2026: Limit the read to the buffer size and stop at the end of // input (the loop used to overflow sbuf on long input and spin forever // when stdin was closed) cin.width(cmd_len); if(!(cin >> sbuf)) break; if(strcmp(sbuf, "quit") == 0) break; if(strcmp(sbuf, "exit") == 0) break; cout << "Invalid command" << "\n" << flush; cout << "Enter quit to exit" << "\n" << flush; } return (void *)0; } void KeyGenCallback(int p, int n, void *arg) { char c = 'B'; if (p == 0) c = '.'; if (p == 1) c = '+'; if (p == 2) c = '*'; if (p == 3) c = '\n'; cout << c << flush; } void nt_SSL_error_print(gxSSL *ssl) // Non-thread safe error message print { if(!ssl) return; gxString err; cout << ssl->SSLExceptionMessage() << "\n" << flush; gxSSL::GlobalSSLError(err); cout << err.c_str() << "\n" << flush; } void InputData(const char *prompt, gxString &data) // Function used to read a string from the input stream. { data.Clear(); if(!prompt) return; char buf[1024]; memset(buf, 0, 1024); cout << prompt << ": " << flush; cin.getline(buf, sizeof(buf)); data << buf; } int main(int argc, char **argv) { // Check arguments. Should be only one: the port number to bind to. if(argc != 2) { cerr << "Usage: " << argv[0] << " port" << "\n" << flush; return 1; } ServerThread server; gxSSL *ssl = &server.openssl; gxRandom rand_num; servercfg->port = (gxsPort_t) atoi(argv[1]); const char *private_key_fname = "server_private_key.pem"; const char *cert_req_fname = "server_cert.pem"; const char *dh_fname = "dhparms.pem"; #if defined (__USE_GX_SCHANNEL__) // 11/14/2026: Schannel picks its own key exchange groups (no DH // parameter file) and cannot make keys or certificates: the example // stopped here on every Schannel build. Make the files with openssl. if(!futils_exists(private_key_fname) || !futils_exists(cert_req_fname)) { cout << "Schannel build: put a server key and certificate in " << private_key_fname << " and " << cert_req_fname << " (for example with openssl req -x509 -newkey rsa:2048 -nodes)" << "\n" << flush; return 1; } #else if(!futils_exists(dh_fname)) { cout << "Generating Diffie-Hellman parameters file" << "\n" << flush; if(ssl->InitPRNG() != gxSSL_NO_ERROR) { nt_SSL_error_print(ssl); return 1; } if(ssl->MakeDHParms(dh_fname) != gxSSL_NO_ERROR) { nt_SSL_error_print(ssl); return 1; } } if(!futils_exists(private_key_fname)) { cout << "Generating private RSA key" << "\n" << flush; if(ssl->InitPRNG() != gxSSL_NO_ERROR) { nt_SSL_error_print(ssl); return 1; } if(ssl->MakeRSAPrivateKey(private_key_fname, 2048, KeyGenCallback, 0) != gxSSL_NO_ERROR) { nt_SSL_error_print(ssl); return 1; } cout << "\n" << flush; cout << "Generating and self-signing certificate request" << "\n" << flush; gxCertIssuerInfo ci; ci.sn = rand_num.RandomNumber(); ci.days = 365; InputData("Country Name XX", ci.C); if(ci.C.is_null()) ci.C = "US"; InputData("State or Province", ci.ST); if(ci.ST.is_null()) ci.ST = "MyState"; InputData("City or Locality", ci.L); if(ci.L.is_null()) ci.L = "MyCity"; InputData("Organization Name", ci.O); if(ci.O.is_null()) ci.O = "My Org. Name"; InputData("Organizational Unit", ci.OU); if(ci.OU.is_null()) ci.OU = "My Org. Unit"; InputData("Common Name (or site name)", ci.CN); if(ci.CN.is_null()) ci.CN = "my.server.com"; // Add standard extensions if needed by application // ci.basic_constraints = "critical,CA:TRUE"; // ci.key_usage = "critical,keyCertSign,cRLSign"; // ci.subject_key_identifier = "hash"; // Add Netscape specific extensions if needed by application // ci.netscape_cert_type = "sslCA"; // ci.netscape_comment = "my comment extension"; if(ssl->MakeCertReq(private_key_fname, ci, cert_req_fname)!= gxSSL_NO_ERROR) { nt_SSL_error_print(ssl); return 1; } } #endif // __USE_GX_SCHANNEL__ cout << "Initializing HTTPS server..." << "\n" << flush; int rv = server.InitServer(servercfg->port); if(rv != 0) { cout << server.SocketExceptionMessage() << "\n" << flush; return 1; } if(!gxSSL::InitSSLibrary()) { cout << "Error initializing SSL library" << "\n" << flush; nt_SSL_error_print(ssl); return 1; } cout << "Initializing SSL context object..." << "\n" << flush; if(!ssl->InitCTX(cert_req_fname, private_key_fname)) { nt_SSL_error_print(ssl); return 1; } cout << "Loading Diffie-Hellman parameters..." << "\n" << flush; if(ssl->LoadDHParms(dh_fname) != gxSSL_NO_ERROR) { nt_SSL_error_print(ssl); return 1; } // Get the host name assigned to this machine char hostname[gxsMAX_NAME_LEN]; rv = server.GetHostName(hostname); if(rv != 0) { cout << server.SocketExceptionMessage() << "\n" << flush; return 1; } cout << "Opening HTTPS server on host " << hostname << "\n" << flush; cout << "Enter quit to exit" << "\n" << flush; cout << "\n" << flush; cout << "Listening on port " << servercfg->port << "\n" << flush; cout.flush(); gxThread_t *server_thread = server.CreateThread(); if(server_thread->GetThreadError() != gxTHREAD_NO_ERROR) { cout << server_thread->ThreadExceptionMessage() << "\n" << flush; return 1; } ConsoleThread console; gxThread_t *console_thread = console.CreateThread(); if(console_thread->GetThreadError() != gxTHREAD_NO_ERROR) { cout << console_thread->ThreadExceptionMessage() << "\n" << flush; return 1; } if(console.JoinThread(console_thread) != 0) { cout << "Could not join the console thread" << "\n" << flush; } // Destroy the serial port receiver thread cout << "Stopping the server thread..." << "\n" << flush; servercfg->accept_clients = 0; // Cannot the server thread due to the blocking accept() function, so // cancel the thread before it is destroyed server.CancelThread(server_thread); if(server_thread->GetThreadState() == gxTHREAD_STATE_CANCELED) { cout << "The server thread was stopped" << "\n" << flush; } else { cout << "Could not cancel the server thread" << "\n" << flush; } if(server.JoinThread(server_thread) != 0) { cout << "Could not join the server thread" << "\n" << flush; } delete server_thread; delete console_thread; cout << "Exiting..." << "\n" << flush; return 0; } // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
examples_socket/ssl_server/m_thread.h 112 lines
#ifndef __GX_S_MTHREAD_SERVER_HPP__ #define __GX_S_MTHREAD_SERVER_HPP__ #include "gxdlcode.h" #include "gxmutex.h" #include "gxcond.h" #include "gxthread.h" #include "gxsocket.h" #include "futils.h" #include "gxssl.h" // -------------------------------------------------------------- // Constants // -------------------------------------------------------------- // Thread constants const int DISPLAY_THREAD_RETRIES = 3; // -------------------------------------------------------------- // Server configuration struct ServerConfig { ServerConfig(); ~ServerConfig(); // Server configuration variables gxsPort_t port; // Server's port number int accept_clients; // True while accepting // gxThread variables thrPool *client_request_pool; // Worker threads processing client requests // gxThread synchronization interface gxMutex display_lock; // Mutex object used to lock the display gxCondition display_cond; // Condition variable used with the display lock int display_is_locked; // Display lock Boolean predicate }; // Client socket type used to associate client sockets other // data types. struct ClientSocket_t { ClientSocket_t() { client_socket = -1; openssl = 0; } ~ClientSocket_t() { FreeSSL(); } void FreeSSL(); gxsSocket_t client_socket; // Client socket gxSSL *openssl; // Open SSL object }; class ClientRequestThread : public gxSocket, public gxThread { public: ClientRequestThread() { } ~ClientRequestThread() { } public: // Client routines void HandleClientRequest(ClientSocket_t *s); private: // gxThread Interface void *ThreadEntryRoutine(gxThread_t *thread); void ThreadExitRoutine(gxThread_t *thread); void ThreadCleanupHandler(gxThread_t *thread); }; class ServerThread : public gxSocket, public gxThread { public: ServerThread() { } ~ServerThread() { } public: // Server functions int InitServer(int max_connections = SOMAXCONN); private: // gxThread Interface void *ThreadEntryRoutine(gxThread_t *thread); void ThreadExitRoutine(gxThread_t *thread); void ThreadCleanupHandler(gxThread_t *thread); public: // Server data members ClientRequestThread request_thread; gxSSL openssl; }; // -------------------------------------------------------------- // Standalone functions // -------------------------------------------------------------- void PrintMessage(const char *s1 = " ", const char *s2 = " ", const char *s3 = " "); void ReportError(const char *s1 = " ", const char *s2 = " ", const char *s3 = " "); int CheckSocketError(gxSocket *s, const char *mesg = 0, int report_error = 1); int CheckThreadError(gxThread_t *thread, const char *mesg = 0, int report_error = 1); // -------------------------------------------------------------- // -------------------------------------------------------------- // Globals configuration variables // -------------------------------------------------------------- extern ServerConfig ServerConfigSruct; extern ServerConfig *servercfg; // -------------------------------------------------------------- #endif // __GX_S_MTHREAD_SERVER_HPP__ // ----------------------------------------------------------- // // ------------------------------- // // --------- End of File --------- // // ------------------------------- //
Modern C++ (C++20)
examples_modern/socket/ssl_server/modern.cpp 111 lines
#include <atomic> #include <cstdlib> #include <future> #include <iostream> #include <string> #include <thread> #include <vector> #include "../common/modern_tls.h" #include "gxshttpc.h" #include "gxsurl.h" #include "membuf.h" using namespace modern_net; class HttpsServer { public: HttpsServer(const std::string &cert, const std::string &key) : cert_(cert), key_(key) {} int start(int port = 0) { if(!gxSSL::InitSSLibrary() || !ctx_.InitCTX(cert_.c_str(), key_.c_str())) return -1; if(port == 0) port = listen_loopback(listener_, 16); else if(listener_.InitSocket(SOCK_STREAM, port) < 0 || listener_.Bind() < 0 || listener_.Listen(16) < 0) port = -1; if(port > 0) acceptor_ = std::jthread([this](std::stop_token st) { accept_loop(st); }); return port; } int served() const { return served_; } ~HttpsServer() { acceptor_.request_stop(); if(acceptor_.joinable()) acceptor_.join(); } private: void accept_loop(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) workers_.emplace_back([this, c] { serve(c); }); } } void serve(gxsSocket_t c) { gxSSL tls(ctx_.GetCTX()); struct Cleanup { gxSSL &t; gxSocket &l; gxsSocket_t fd; ~Cleanup() { t.CloseSSLSocket(); t.ReleaseCTX(); l.Close(fd); } } cleanup{tls, listener_, c}; tls.SetHandshakeTimeout(10); if(tls.OpenSSLSocket(c) != gxSSL_NO_ERROR || tls.AcceptSSLSocket() != gxSSL_NO_ERROR) return; std::string request(4096, '\0'); int n = tls.RecvSSLSocket(request.data(), int(request.size()) - 1, 10, 0); if(n <= 0) return; request.resize(std::size_t(n)); std::string first = request.substr(0, request.find("\r\n")); std::string body = "You asked for: " + first + "\n"; std::string reply = "HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\nContent-Length: " + std::to_string(body.size()) + "\r\n\r\n" + body; tls.SendSSLSocket(reply.data(), int(reply.size())); served_++; } std::string cert_, key_; gxSSL ctx_; gxSocket listener_; std::atomic<int> served_{0}; std::vector<std::jthread> workers_; std::jthread acceptor_; }; int main(int argc, char **argv) { ignore_sigpipe(); SocketLibrary lib; if(!make_test_cert("modern_server_key.pem", "modern_server_cert.pem")) { std::cout << "Cannot make the server key and certificate\n"; return 1; } HttpsServer server("modern_server_cert.pem", "modern_server_key.pem"); if(argc > 1) { if(server.start(std::atoi(argv[1])) < 0) return 1; std::cout << "Serving HTTPS on port " << argv[1] << "; press Enter to stop\n"; std::cin.get(); return 0; // ~HttpsServer() stops it } int port = server.start(); if(port < 0) { std::cout << "Cannot start the server\n"; return 1; } const int NUM_CLIENTS = 4; std::vector<std::future<int>> clients; for(int i = 0; i < NUM_CLIENTS; i++) { clients.push_back(std::async(std::launch::async, [port, i] { gxsURL url; gxsURLInfo u; std::string text = "https://localhost:" + std::to_string(port) + "/page" + std::to_string(i); url.ParseURL(text.c_str(), u); gxsHTTPSClient client; client.openssl.SetCAList("modern_server_cert.pem"); client.openssl.RequireVerifyCert(); gxsHTTPHeader hdr; MemoryBuffer mbuf; if(client.Request(u, hdr, mbuf) != 0) return 0; std::cout << std::string(reinterpret_cast<const char *>(mbuf.m_buf()), mbuf.length()); return hdr.http_status; })); } int ok = 0; for(auto &f : clients) ok += f.get() == 200; std::cout << ok << " of " << NUM_CLIENTS << " HTTPS requests answered, " << server.served() << " served\n"; return ok == NUM_CLIENTS ? 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_ssl_server ./build-modern/socket_ssl_server
Output of the modern program
From run_modern_tests.sh on RHEL 10, GCC 14, C++20.
You asked for: GET /page0 HTTP/1.0 You asked for: GET /page2 HTTP/1.0 You asked for: GET /page3 HTTP/1.0 You asked for: GET /page1 HTTP/1.0 4 of 4 HTTPS requests answered, 4 served