libhomegear-base  0.7
Base library for Homegear and Homegear family modules.
BaseLib::TcpSocket Class Reference

Class to easily create a TCP server or client. More...

#include <TcpSocket.h>

Inheritance diagram for BaseLib::TcpSocket:
BaseLib::IQueue BaseLib::IQueueBase

Classes

struct  AverageMeanData
 
class  CertificateCredentials
 
struct  CertificateInfo
 
class  QueueEntry
 
struct  TcpClientData
 
struct  TcpServerInfo
 

Public Types

typedef std::vector< uint8_t > TcpPacket
 
typedef std::shared_ptr< TcpClientDataPTcpClientData
 
typedef std::shared_ptr< CertificateInfoPCertificateInfo
 

Public Member Functions

 TcpSocket (BaseLib::SharedObjects *baseLib)
 Constructor to create an empty socket object. More...
 
 TcpSocket (BaseLib::SharedObjects *baseLib, std::shared_ptr< FileDescriptor > socketDescriptor)
 Constructor to just wrap an existing socket descriptor. More...
 
 TcpSocket (BaseLib::SharedObjects *baseLib, std::string hostname, std::string port)
 Constructor to create a TCP client socket. More...
 
 TcpSocket (BaseLib::SharedObjects *baseLib, std::string hostname, std::string port, bool useSsl, std::string caFile, bool verifyCertificate)
 Constructor to create a TCP client socket with SSL enabled. More...
 
 TcpSocket (BaseLib::SharedObjects *baseLib, std::string hostname, std::string port, bool useSsl, bool verifyCertificate, std::string caData)
 Constructor to create a TCP client socket with SSL enabled. More...
 
 TcpSocket (BaseLib::SharedObjects *baseLib, std::string hostname, std::string port, bool useSsl, std::string caFile, bool verifyCertificate, std::string clientCertFile, std::string clientKeyFile)
 Constructor to create a TCP client socket with SSL enabled using certificate login. More...
 
 TcpSocket (BaseLib::SharedObjects *baseLib, std::string hostname, std::string port, bool useSsl, bool verifyCertificate, std::string caData, std::string clientCertData, const std::shared_ptr< Security::SecureVector< uint8_t >> &clientKeyData)
 Constructor to create a TCP client socket with SSL enabled using certificate login. More...
 
 TcpSocket (BaseLib::SharedObjects *baseLib, std::string hostname, std::string port, bool useSsl, bool verifyCertificate, std::string caFile, std::string caData, std::string clientCertFile, std::string clientCertData, std::string clientKeyFile, const std::shared_ptr< Security::SecureVector< uint8_t >> &)
 Constructor to create a TCP client socket with SSL enabled using certificate login. More...
 
 TcpSocket (BaseLib::SharedObjects *baseLib, TcpServerInfo &serverInfo)
 Constructor to create a TCP server. More...
 
virtual ~TcpSocket ()
 
PFileDescriptor getFileDescriptor ()
 
std::string getIpAddress ()
 
int32_t getPort ()
 
bool getRequireClientCert ()
 
void setConnectionRetries (int32_t retries)
 
void setReadTimeout (int64_t timeout)
 
void setWriteTimeout (int64_t timeout)
 
void setAutoConnect (bool autoConnect)
 
void setHostname (std::string hostname)
 
void setPort (std::string port)
 
void setUseSSL (bool useSsl)
 
void setCertificates (std::unordered_map< std::string, PCertificateInfo > &certificates)
 
void reloadCertificates ()
 
void setVerifyCertificate (bool verifyCertificate)
 
void setVerifyHostname (bool verifyHostname)
 
void setVerificationHostname (const std::string &hostname)
 Only relevant for TLS connections. More...
 
std::unordered_map< std::string, std::shared_ptr< CertificateCredentials > > getCredentials ()
 
bool connected ()
 Tests in this order and returns false if one of the tests fails: More...
 
double GetPacketsPerMinuteReceived ()
 
double GetPacketsPerMinuteSent ()
 
double GetServerThreadLoad ()
 Returns the current server thread load. More...
 
double GetProcessingThreadLoad ()
 Returns the current processing thread load. More...
 
double GetProcessingThreadLoadMax ()
 Returns the maximum load of the last minute. More...
 
int32_t proofread (char *buffer, int32_t bufferSize)
 Use this overload when there are no socket operations outside of this class. More...
 
int32_t proofread (char *buffer, int32_t bufferSize, bool &moreData, bool skip_poll=false)
 Use this overload of proofread when select is called outside of this class. More...
 
int32_t proofwrite (const std::shared_ptr< std::vector< char >> &data)
 Writes data to a socket. More...
 
int32_t proofwrite (const std::vector< char > &data)
 Writes data to a socket. More...
 
int32_t proofwrite (const std::string &data)
 Writes data to a socket. More...
 
int32_t proofwrite (const char *buffer, int32_t bytesToWrite)
 Writes data to a socket. More...
 
void open ()
 
void close ()
 
void bindServerSocket (std::string address, std::string port, std::string &listenAddress)
 Binds a socket to an IP address and a port. More...
 
void startPreboundServer (std::string &listenAddress, size_t processingThreads=0)
 Starts listening on the already bound socket (created with bindServerSocket()). More...
 
void startServer (std::string address, std::string port, std::string &listenAddress, size_t processingThreads=0)
 Starts listening. More...
 
void startServer (std::string address, std::string &listenAddress, int32_t &listenPort, size_t processingThreads=0)
 Starts listening on a dynamically assigned port. More...
 
void stopServer ()
 Starts stopping the server and returns immediately. More...
 
void waitForServerStopped ()
 Waits until the server is stopped. More...
 
bool sendToClient (int32_t clientId, const TcpPacket &packet, bool closeConnection=false)
 Sends a response to a TCP client connected to the server. More...
 
bool sendToClient (int32_t clientId, const std::vector< char > &packet, bool closeConnection=false)
 Sends a response to a TCP client connected to the server. More...
 
void closeClientConnection (int32_t clientId)
 Closes the connection to a connected client. More...
 
int32_t clientCount ()
 Returns the number of clients connected to the TCP server. More...
 
uint32_t processingQueueSize ()
 Returns the size of the packet processing queue. More...
 
std::string getClientCertDn (int32_t clientId)
 Returns the distinguished name of the client certificate. More...
 
std::string getClientCertSerial (int32_t clientId)
 
int64_t getClientCertExpiration (int32_t clientId)
 
- Public Member Functions inherited from BaseLib::IQueue
 IQueue (SharedObjects *baseLib, uint32_t queueCount, uint32_t bufferSize)
 Constructor. More...
 
virtual ~IQueue ()
 
void startQueue (int32_t index, bool waitWhenFull, uint32_t processingThreadCount, int32_t threadPriority=0, int32_t threadPolicy=SCHED_OTHER)
 Starts the threads of a queue. More...
 
void startQueue (int32_t index, bool waitWhenFull, uint32_t initialProcessingThreadCount, uint32_t maxProcessingThreadCount)
 Starts the threads of a queue using a thread count that can be increased later. More...
 
void stopQueue (int32_t index)
 Stops the threads of a queue previously started with startQueue(). More...
 
bool queueIsStarted (int32_t index)
 Checks if the specified queue has been started. More...
 
bool addThread (int32_t index)
 Start an additional thread. More...
 
bool enqueue (int32_t index, std::shared_ptr< IQueueEntry > &entry, bool waitWhenFull=false)
 Enqueues an item. More...
 
virtual void processQueueEntry (int32_t index, std::shared_ptr< IQueueEntry > &entry)=0
 This method is called by the processing threads for each item to process. More...
 
bool queueEmpty (int32_t index)
 Checks if a queue is empty. More...
 
uint32_t processingThreadCount (int32_t index)
 Returns the number of processing threads. More...
 
uint32_t maxProcessingThreadCount (int32_t index)
 Returns the maximum number of processing threads. More...
 
int32_t queueSize (int32_t index)
 Returns the number of items queued in a queue. More...
 
double threadLoad (int32_t index)
 
double maxThreadLoad (int32_t index)
 
double maxThreadLoad1m (int32_t index)
 
double maxThreadLoad10m (int32_t index)
 
double maxThreadLoad1h (int32_t index)
 
int64_t maxWait (int32_t index)
 
int64_t maxWait1m (int32_t index)
 
int64_t maxWait10m (int32_t index)
 
int64_t maxWait1h (int32_t index)
 
- Public Member Functions inherited from BaseLib::IQueueBase
 IQueueBase (SharedObjects *baseLib, uint32_t queueCount)
 
virtual ~IQueueBase ()
 
void printQueueFullError (BaseLib::Output &out, const std::string &message)
 Prints a rate limited (1 output per 10 seconds) error message and keeps count of error messages. More...
 

Static Public Member Functions

static PFileDescriptor bindAndReturnSocket (FileDescriptorManager &fileDescriptorManager, const std::string &address, const std::string &port, uint32_t connectionBacklogSize, std::string &listenAddress, int32_t &listenPort)
 

Protected Member Functions

void getSocketDescriptor ()
 
void getConnection ()
 
void getSsl ()
 
void initSsl ()
 
void initTlsPriorityCache ()
 
void autoConnect ()
 
void bindSocket ()
 
void serverThread (uint32_t thread_index)
 
void processQueueEntry (int32_t index, std::shared_ptr< BaseLib::IQueueEntry > &entry) override
 
void collectGarbage ()
 
void collectGarbage (std::unordered_map< int32_t, PTcpClientData > &clients)
 
void initClientSsl (PTcpClientData &clientData)
 
void readClient (const PTcpClientData &client_data, std::unordered_map< int32_t, PTcpClientData > &backlog_clients)
 

Protected Attributes

BaseLib::SharedObjects_bl = nullptr
 
int32_t _connectionRetries = 3
 
int64_t _readTimeout = 15000000
 
int64_t _writeTimeout = 15000000
 
std::atomic_bool _connecting
 
bool _autoConnect = true
 
std::string _ipAddress
 
std::string _hostname
 
std::string _verificationHostname
 
std::string _port
 
std::mutex _readMutex
 
std::mutex _writeMutex
 
std::unordered_map< std::string, PCertificateInfo_certificates
 
bool _verifyCertificate = true
 
bool _verifyHostname = true
 
bool _isServer = false
 
uint32_t _backlogSize = 100
 
uint32_t _maxConnections = 10
 
std::string _dhParamFile
 
std::string _dhParamData
 
bool _requireClientCert = false
 
std::atomic< uint32_t > server_threads_in_use_ {0}
 
std::vector< AverageMeanDataaverage_packets_per_minute_received_
 
std::vector< AverageMeanDataaverage_packets_per_minute_sent_
 
std::function< void(int32_t clientId, std::string address, uint16_t port)> _newConnectionCallback
 
std::function< void(int32_t clientId)> _connectionClosedCallback
 
std::function< void(int32_t clientId, int32_t errorCode, const std::string &errorString)> _connectionClosedCallbackEx
 
std::function< void(int32_t clientId, TcpPacket &packet)> _packetReceivedCallback
 
std::string _listenAddress
 
std::string _listenPort
 
int32_t _boundListenPort = -1
 
gnutls_priority_t _tlsPriorityCache = nullptr
 
std::atomic_bool _stopServer
 
std::vector< std::thread > server_threads_
 
int64_t _lastGarbageCollection = 0
 
std::mutex _clientsMutex
 
std::map< int32_t, PTcpClientData_clients
 
std::mutex _socketDescriptorMutex
 
PFileDescriptor _socketDescriptor
 
bool _useSsl = false
 
std::mutex _certificateCredentialsMutex
 
std::shared_ptr< CertificateCredentials_currentClientCertificateCredentials
 Contains a copy of the current credentials in case the credentials are replaced while the connection is open. More...
 
std::unordered_map< std::string, std::shared_ptr< CertificateCredentials > > _certificateCredentials
 Stores the certificate credentials so that they can be replaced at any time. More...
 
- Protected Attributes inherited from BaseLib::IQueueBase
SharedObjects_bl = nullptr
 
int32_t _queueCount = 2
 
std::unique_ptr< std::atomic_bool[]> _stopProcessingThread
 
std::atomic< uint32_t > _droppedEntries {0}
 
std::atomic< int64_t > _lastQueueFullError {0}
 

Detailed Description

Class to easily create a TCP server or client.

TCP Server Example Code

Save the example below in main.cpp and compile with:

g++ -o main -std=c++11 main.cpp -lhomegear-base -lgcrypt -lgnutls

Start and connect using e. g. telnet:

./main
telnet localhost 8082

Example code:

#include <homegear-base/BaseLib.h>

std::shared_ptr<BaseLib::SharedObjects> _bl;
std::shared_ptr<BaseLib::TcpSocket> _tcpServer;

void newConnection(int32_t clientId, std::string address, uint16_t port)
{
    std::cout << "New connection from " << address << " on port " << port << ". Client ID: " << clientId << std::endl;
}

void packetReceived(int32_t clientId, BaseLib::TcpSocket::TcpPacket& packet)
{
    std::string data((char*)packet.data(), packet.size());
    BaseLib::HelperFunctions::trim(data);
    std::cout << "Packet received from client " << clientId << ": " << data << std::endl;
    std::vector<uint8_t> response;
    response.push_back('R');
    response.push_back(':');
    response.push_back(' ');
    response.insert(response.end(), packet.begin(), packet.end());
    _tcpServer->sendToClient(clientId, response);
}

void connectionClosed(int32_t clientId)
{
 std::cout << "Connection to client " << clientId << " closed." << std::endl;
}

int main()
{
    _bl.reset(new BaseLib::SharedObjects(false));

    BaseLib::TcpSocket::TcpServerInfo serverInfo;
    serverInfo.newConnectionCallback = std::bind(&newConnection, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
    //For class methods add `this` as first parameter:
    //serverInfo.newConnectionCallback = std::bind(&MyClass::newConnection, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
    serverInfo.packetReceivedCallback = std::bind(&packetReceived, std::placeholders::_1, std::placeholders::_2);
    serverInfo.connectionClosedCallback = std::bind(&connectionClosed, std::placeholders::_1);

    _tcpServer = std::make_shared<BaseLib::TcpSocket>(_bl.get(), serverInfo);

    std::string listenAddress;
    _tcpServer->startServer("::", "8082", listenAddress);
    std::cout << "Started listening on " + listenAddress << std::endl;

    //Alternatively you can call `bindServerSocket()` as root first, then drop privileges and start the server:
    //_tcpServer->bindServerSocket("::", "8082", listenAddress);
    //...
    //Drop privileges
    //...
    //_tcpServer->startPreboundServer(listenAddress);

    for(int32_t i = 0; i < 300; i++) //Run for 300 seconds
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }

    _tcpServer->stopServer();
    _tcpServer->waitForServerStopped();
}

Member Typedef Documentation

§ PCertificateInfo

§ PTcpClientData

§ TcpPacket

typedef std::vector<uint8_t> BaseLib::TcpSocket::TcpPacket

Constructor & Destructor Documentation

§ TcpSocket() [1/9]

BaseLib::TcpSocket::TcpSocket ( BaseLib::SharedObjects baseLib)
explicit

Constructor to create an empty socket object.

Parameters
baseLibThe base library object.

§ TcpSocket() [2/9]

BaseLib::TcpSocket::TcpSocket ( BaseLib::SharedObjects baseLib,
std::shared_ptr< FileDescriptor socketDescriptor 
)

Constructor to just wrap an existing socket descriptor.

Parameters
baseLibThe base library object.
socketDescriptorThe socket descriptor to wrap.

§ TcpSocket() [3/9]

BaseLib::TcpSocket::TcpSocket ( BaseLib::SharedObjects baseLib,
std::string  hostname,
std::string  port 
)

Constructor to create a TCP client socket.

Parameters
baseLibThe base library object.
hostnameThe host name or IP address to connect to.
portThe port to connect to.

§ TcpSocket() [4/9]

BaseLib::TcpSocket::TcpSocket ( BaseLib::SharedObjects baseLib,
std::string  hostname,
std::string  port,
bool  useSsl,
std::string  caFile,
bool  verifyCertificate 
)

Constructor to create a TCP client socket with SSL enabled.

Parameters
baseLibThe base library object.
hostnameThe host name or IP address to connect to.
portThe port to connect to.
useSslSet to true to enable SSL.
caFilePath to a file containing the PEM-encoded CA certificate used to sign the server certificate. If empty, the system's certificate store is used.
verifyCertificateEnable certificate verification. Only set to false for testing.

§ TcpSocket() [5/9]

BaseLib::TcpSocket::TcpSocket ( BaseLib::SharedObjects baseLib,
std::string  hostname,
std::string  port,
bool  useSsl,
bool  verifyCertificate,
std::string  caData 
)

Constructor to create a TCP client socket with SSL enabled.

Parameters
baseLibThe base library object.
hostnameThe host name or IP address to connect to.
portThe port to connect to.
useSslSet to true to enable SSL.
verifyCertificateEnable certificate verification. Only set to false for testing.
caDataThe PEM-encoded CA certificate (not the path) used to sign the server certificate. If empty, the system's certificate store is used.

§ TcpSocket() [6/9]

BaseLib::TcpSocket::TcpSocket ( BaseLib::SharedObjects baseLib,
std::string  hostname,
std::string  port,
bool  useSsl,
std::string  caFile,
bool  verifyCertificate,
std::string  clientCertFile,
std::string  clientKeyFile 
)

Constructor to create a TCP client socket with SSL enabled using certificate login.

Parameters
baseLibThe base library object.
hostnameThe host name or IP address to connect to.
portThe port to connect to.
useSslSet to true to enable SSL.
caFilePath to a file containing the PEM-encoded CA certificate used to sign the server certificate.
verifyCertificateEnable certificate verification. Only set to false for testing.
clientCertFilePath to a file containing the PEM-encoded client certificate.
clientKeyFilePath to a file containing the PEM-encoded client key file.

§ TcpSocket() [7/9]

BaseLib::TcpSocket::TcpSocket ( BaseLib::SharedObjects baseLib,
std::string  hostname,
std::string  port,
bool  useSsl,
bool  verifyCertificate,
std::string  caData,
std::string  clientCertData,
const std::shared_ptr< Security::SecureVector< uint8_t >> &  clientKeyData 
)

Constructor to create a TCP client socket with SSL enabled using certificate login.

Parameters
baseLibThe base library object.
hostnameThe host name or IP address to connect to.
portThe port to connect to.
useSslSet to true to enable SSL.
verifyCertificateEnable certificate verification. Only set to false for testing.
caDataThe PEM-encoded CA certificate (not the path) used to sign the server certificate.
clientCertDataThe PEM-encoded client certificate (not the path).
clientKeyDataThe PEM-encoded client key (not the path).

§ TcpSocket() [8/9]

BaseLib::TcpSocket::TcpSocket ( BaseLib::SharedObjects baseLib,
std::string  hostname,
std::string  port,
bool  useSsl,
bool  verifyCertificate,
std::string  caFile,
std::string  caData,
std::string  clientCertFile,
std::string  clientCertData,
std::string  clientKeyFile,
const std::shared_ptr< Security::SecureVector< uint8_t >> &  clientKeyData 
)

Constructor to create a TCP client socket with SSL enabled using certificate login.

Parameters
baseLibThe base library object.
hostnameThe host name or IP address to connect to.
portThe port to connect to.
useSslSet to true to enable SSL.
verifyCertificateEnable certificate verification. Only set to false for testing.
caFilePath to a file containing the PEM-encoded CA certificate used to sign the server certificate.
caDataThe PEM-encoded CA certificate (not the path) used to sign the server certificate.
clientCertFilePath to a file containing the PEM-encoded client certificate.
clientCertDataThe PEM-encoded client certificate (not the path).
clientKeyFilePath to a file containing the PEM-encoded client key file.
clientKeyDataThe PEM-encoded client key (not the path).

§ TcpSocket() [9/9]

BaseLib::TcpSocket::TcpSocket ( BaseLib::SharedObjects baseLib,
TcpServerInfo serverInfo 
)

Constructor to create a TCP server.

§ ~TcpSocket()

BaseLib::TcpSocket::~TcpSocket ( )
virtual

Member Function Documentation

§ autoConnect()

void BaseLib::TcpSocket::autoConnect ( )
protected

§ bindAndReturnSocket()

PFileDescriptor BaseLib::TcpSocket::bindAndReturnSocket ( FileDescriptorManager fileDescriptorManager,
const std::string &  address,
const std::string &  port,
uint32_t  connectionBacklogSize,
std::string &  listenAddress,
int32_t &  listenPort 
)
static

§ bindServerSocket()

void BaseLib::TcpSocket::bindServerSocket ( std::string  address,
std::string  port,
std::string &  listenAddress 
)

Binds a socket to an IP address and a port.

This splits up the start process to be able to listen on ports lower than 1024 and do a privilege drop. Call startPreboundServer() to start listening. Don't call startServer() when using pre-binding as this recreates the socket.

See also
startPreboundServer
Parameters
addressThe address to bind the server to (e. g. :: or 0.0.0.0).
portThe port number to bind the server to.
[out]listenAddressThe IP address the server was bound to (e. g. 192.168.0.152).

§ bindSocket()

void BaseLib::TcpSocket::bindSocket ( )
protected

§ clientCount()

int32_t BaseLib::TcpSocket::clientCount ( )

Returns the number of clients connected to the TCP server.

Returns
The number of connected clients.

§ close()

void BaseLib::TcpSocket::close ( )

§ closeClientConnection()

void BaseLib::TcpSocket::closeClientConnection ( int32_t  clientId)

Closes the connection to a connected client.

Parameters
clientIdThe ID of the client to close as passed to TcpSocket::TcpServerServer::packetReceivedCallback.

§ collectGarbage() [1/2]

void BaseLib::TcpSocket::collectGarbage ( )
protected

§ collectGarbage() [2/2]

void BaseLib::TcpSocket::collectGarbage ( std::unordered_map< int32_t, PTcpClientData > &  clients)
protected

§ connected()

bool BaseLib::TcpSocket::connected ( )

Tests in this order and returns false if one of the tests fails:

  1. Tests if there is a valid socket (!= -1)
  2. If we are currently connecting
  3. Calls recv with the MSG_PEEK flag set and checks for an error return.
Returns
Returns true if the socket is connected.

§ getClientCertDn()

std::string BaseLib::TcpSocket::getClientCertDn ( int32_t  clientId)

Returns the distinguished name of the client certificate.

This method only returns a non empty string if the client certificate is valid.

Parameters
clientIdThe ID of the client to get the distinguished name for.
Returns
Returns the DN when the client certificate verification was successful.

§ getClientCertExpiration()

int64_t BaseLib::TcpSocket::getClientCertExpiration ( int32_t  clientId)

§ getClientCertSerial()

std::string BaseLib::TcpSocket::getClientCertSerial ( int32_t  clientId)

§ getConnection()

void BaseLib::TcpSocket::getConnection ( )
protected

§ getCredentials()

std::unordered_map<std::string, std::shared_ptr<CertificateCredentials> > BaseLib::TcpSocket::getCredentials ( )
inline

§ getFileDescriptor()

PFileDescriptor BaseLib::TcpSocket::getFileDescriptor ( )

§ getIpAddress()

std::string BaseLib::TcpSocket::getIpAddress ( )

§ GetPacketsPerMinuteReceived()

double BaseLib::TcpSocket::GetPacketsPerMinuteReceived ( )

§ GetPacketsPerMinuteSent()

double BaseLib::TcpSocket::GetPacketsPerMinuteSent ( )

§ getPort()

int32_t BaseLib::TcpSocket::getPort ( )
inline

§ GetProcessingThreadLoad()

double BaseLib::TcpSocket::GetProcessingThreadLoad ( )

Returns the current processing thread load.

A load of 1.0 means all threads are in use. (Queue backlog / thread count) is added to this load, so the load can be greater than 1.0.

Returns

§ GetProcessingThreadLoadMax()

double BaseLib::TcpSocket::GetProcessingThreadLoadMax ( )

Returns the maximum load of the last minute.

Returns

§ getRequireClientCert()

bool BaseLib::TcpSocket::getRequireClientCert ( )
inline

§ GetServerThreadLoad()

double BaseLib::TcpSocket::GetServerThreadLoad ( )

Returns the current server thread load.

A load of 1.0 means all threads are in use. (Queue backlog / thread count) is added to this load, so the load can be greater than 1.0.

Returns

§ getSocketDescriptor()

void BaseLib::TcpSocket::getSocketDescriptor ( )
protected

§ getSsl()

void BaseLib::TcpSocket::getSsl ( )
protected

§ initClientSsl()

void BaseLib::TcpSocket::initClientSsl ( PTcpClientData clientData)
protected

§ initSsl()

void BaseLib::TcpSocket::initSsl ( )
protected

§ initTlsPriorityCache()

void BaseLib::TcpSocket::initTlsPriorityCache ( )
protected

§ open()

void BaseLib::TcpSocket::open ( )

§ processingQueueSize()

uint32_t BaseLib::TcpSocket::processingQueueSize ( )

Returns the size of the packet processing queue.

Returns
Returns the size of the packet processing queue.

§ processQueueEntry()

void BaseLib::TcpSocket::processQueueEntry ( int32_t  index,
std::shared_ptr< BaseLib::IQueueEntry > &  entry 
)
overrideprotected

§ proofread() [1/2]

int32_t BaseLib::TcpSocket::proofread ( char *  buffer,
int32_t  bufferSize 
)

Use this overload when there are no socket operations outside of this class.

Parameters
bufferThe buffer to fill.
bufferSizeThe size of the buffer.
Returns
The number of bytes read. The returned value is always greater than 0 (in all other cases exceptions are thrown).
Exceptions
SocketOperationExceptionThrown when socket is nullptr.
SocketTimeOutExceptionThrown when reading times out.
SocketClosedExceptionThrown when socket is closed.

§ proofread() [2/2]

int32_t BaseLib::TcpSocket::proofread ( char *  buffer,
int32_t  bufferSize,
bool &  moreData,
bool  skip_poll = false 
)

Use this overload of proofread when select is called outside of this class.

Parameters
bufferThe buffer to fill.
bufferSizeThe size of the buffer.
[out]moreDataIf true, call proofread immediately again (without calling e. g. select first).
skip_pollSkips the call to select. Set this to true when you know, that data is available.
Returns
The number of bytes read. The returned value is always greater than 0 (in all other cases exceptions are thrown).
Exceptions
SocketOperationExceptionThrown when socket is nullptr.
SocketTimeOutExceptionThrown when reading times out.
SocketClosedExceptionThrown when socket is closed.

§ proofwrite() [1/4]

int32_t BaseLib::TcpSocket::proofwrite ( const std::shared_ptr< std::vector< char >> &  data)

Writes data to a socket.

Returns
Returns the number of bytes written. Never returns a negative number.
Exceptions
SocketOperationExceptionThrown when socket is nullptr.
SocketDataLimitExceptionThrown when trying to send more than 104857600 bytes of data.
SocketTimeOutExceptionThrown when writing times out.
SocketClosedExceptionThrown when socket is closed.

§ proofwrite() [2/4]

int32_t BaseLib::TcpSocket::proofwrite ( const std::vector< char > &  data)

Writes data to a socket.

Returns
Returns the number of bytes written. Never returns a negative number.
Exceptions
SocketOperationExceptionThrown when socket is nullptr.
SocketDataLimitExceptionThrown when trying to send more than 104857600 bytes of data.
SocketTimeOutExceptionThrown when writing times out.
SocketClosedExceptionThrown when socket is closed.

§ proofwrite() [3/4]

int32_t BaseLib::TcpSocket::proofwrite ( const std::string &  data)

Writes data to a socket.

Returns
Returns the number of bytes written. Never returns a negative number.
Exceptions
SocketOperationExceptionThrown when socket is nullptr.
SocketDataLimitExceptionThrown when trying to send more than 104857600 bytes of data.
SocketTimeOutExceptionThrown when writing times out.
SocketClosedExceptionThrown when socket is closed.

§ proofwrite() [4/4]

int32_t BaseLib::TcpSocket::proofwrite ( const char *  buffer,
int32_t  bytesToWrite 
)

Writes data to a socket.

Returns
Returns the number of bytes written. Never returns a negative number.
Exceptions
SocketOperationExceptionThrown when socket is nullptr.
SocketDataLimitExceptionThrown when trying to send more than 104857600 bytes of data.
SocketTimeOutExceptionThrown when writing times out.
SocketClosedExceptionThrown when socket is closed.

§ readClient()

void BaseLib::TcpSocket::readClient ( const PTcpClientData client_data,
std::unordered_map< int32_t, PTcpClientData > &  backlog_clients 
)
protected

§ reloadCertificates()

void BaseLib::TcpSocket::reloadCertificates ( )

§ sendToClient() [1/2]

bool BaseLib::TcpSocket::sendToClient ( int32_t  clientId,
const TcpPacket packet,
bool  closeConnection = false 
)

Sends a response to a TCP client connected to the server.

Parameters
clientIdThe ID of the client as passed to TcpSocket::TcpServerServer::packetReceivedCallback.
packetThe data to send.
closeConnectionClose the connection after sending the packet.

§ sendToClient() [2/2]

bool BaseLib::TcpSocket::sendToClient ( int32_t  clientId,
const std::vector< char > &  packet,
bool  closeConnection = false 
)

Sends a response to a TCP client connected to the server.

Parameters
clientIdThe ID of the client as passed to TcpSocket::TcpServerServer::packetReceivedCallback.
packetThe data to send.
closeConnectionClose the connection after sending the packet.

§ serverThread()

void BaseLib::TcpSocket::serverThread ( uint32_t  thread_index)
protected

§ setAutoConnect()

void BaseLib::TcpSocket::setAutoConnect ( bool  autoConnect)
inline

§ setCertificates()

void BaseLib::TcpSocket::setCertificates ( std::unordered_map< std::string, PCertificateInfo > &  certificates)

§ setConnectionRetries()

void BaseLib::TcpSocket::setConnectionRetries ( int32_t  retries)
inline

§ setHostname()

void BaseLib::TcpSocket::setHostname ( std::string  hostname)
inline

§ setPort()

void BaseLib::TcpSocket::setPort ( std::string  port)
inline

§ setReadTimeout()

void BaseLib::TcpSocket::setReadTimeout ( int64_t  timeout)
inline

§ setUseSSL()

void BaseLib::TcpSocket::setUseSSL ( bool  useSsl)
inline

§ setVerificationHostname()

void BaseLib::TcpSocket::setVerificationHostname ( const std::string &  hostname)
inline

Only relevant for TLS connections.

Sets the hostname the certificate's common name is verified against.

Parameters
hostnameThe compare the certificate's common name to.

§ setVerifyCertificate()

void BaseLib::TcpSocket::setVerifyCertificate ( bool  verifyCertificate)
inline

§ setVerifyHostname()

void BaseLib::TcpSocket::setVerifyHostname ( bool  verifyHostname)
inline

§ setWriteTimeout()

void BaseLib::TcpSocket::setWriteTimeout ( int64_t  timeout)
inline

§ startPreboundServer()

void BaseLib::TcpSocket::startPreboundServer ( std::string &  listenAddress,
size_t  processingThreads = 0 
)

Starts listening on the already bound socket (created with bindServerSocket()).

This splits up the start process to be able to listen on ports lower than 1024 and do a privilege drop. Don't call startServer() when using pre-binding as this recreates the socket.

See also
bindServerSocket
Parameters
[out]listenAddressThe IP address the server was bound to (e. g. 192.168.0.152).
processingThreadsThe number of processing threads to start. By default no threads are started.

§ startServer() [1/2]

void BaseLib::TcpSocket::startServer ( std::string  address,
std::string  port,
std::string &  listenAddress,
size_t  processingThreads = 0 
)

Starts listening.

Parameters
addressThe address to bind the server to (e. g. :: or 0.0.0.0).
portThe port number to bind the server to.
[out]listenAddressThe IP address the server was bound to (e. g. 192.168.0.152).
processingThreadsThe number of processing threads to start. By default no threads are started.

§ startServer() [2/2]

void BaseLib::TcpSocket::startServer ( std::string  address,
std::string &  listenAddress,
int32_t &  listenPort,
size_t  processingThreads = 0 
)

Starts listening on a dynamically assigned port.

Parameters
addressThe address to bind the server to (e. g. :: or 0.0.0.0).
[out]listenAddressThe IP address the server was bound to (e. g. 192.168.0.152).
[out]listenPortThe port the server was bound to (e. g. 45735).
processingThreadsThe number of processing threads to start. By default no threads are started.

§ stopServer()

void BaseLib::TcpSocket::stopServer ( )

Starts stopping the server and returns immediately.

§ waitForServerStopped()

void BaseLib::TcpSocket::waitForServerStopped ( )

Waits until the server is stopped.

Member Data Documentation

§ _autoConnect

bool BaseLib::TcpSocket::_autoConnect = true
protected

§ _backlogSize

uint32_t BaseLib::TcpSocket::_backlogSize = 100
protected

§ _bl

BaseLib::SharedObjects* BaseLib::TcpSocket::_bl = nullptr
protected

§ _boundListenPort

int32_t BaseLib::TcpSocket::_boundListenPort = -1
protected

§ _certificateCredentials

std::unordered_map<std::string, std::shared_ptr<CertificateCredentials> > BaseLib::TcpSocket::_certificateCredentials
protected

Stores the certificate credentials so that they can be replaced at any time.

§ _certificateCredentialsMutex

std::mutex BaseLib::TcpSocket::_certificateCredentialsMutex
protected

§ _certificates

std::unordered_map<std::string, PCertificateInfo> BaseLib::TcpSocket::_certificates
protected

§ _clients

std::map<int32_t, PTcpClientData> BaseLib::TcpSocket::_clients
protected

§ _clientsMutex

std::mutex BaseLib::TcpSocket::_clientsMutex
protected

§ _connecting

std::atomic_bool BaseLib::TcpSocket::_connecting
protected

§ _connectionClosedCallback

std::function<void(int32_t clientId)> BaseLib::TcpSocket::_connectionClosedCallback
protected

§ _connectionClosedCallbackEx

std::function<void(int32_t clientId, int32_t errorCode, const std::string &errorString)> BaseLib::TcpSocket::_connectionClosedCallbackEx
protected

§ _connectionRetries

int32_t BaseLib::TcpSocket::_connectionRetries = 3
protected

§ _currentClientCertificateCredentials

std::shared_ptr<CertificateCredentials> BaseLib::TcpSocket::_currentClientCertificateCredentials
protected

Contains a copy of the current credentials in case the credentials are replaced while the connection is open.

§ _dhParamData

std::string BaseLib::TcpSocket::_dhParamData
protected

§ _dhParamFile

std::string BaseLib::TcpSocket::_dhParamFile
protected

§ _hostname

std::string BaseLib::TcpSocket::_hostname
protected

§ _ipAddress

std::string BaseLib::TcpSocket::_ipAddress
protected

§ _isServer

bool BaseLib::TcpSocket::_isServer = false
protected

§ _lastGarbageCollection

int64_t BaseLib::TcpSocket::_lastGarbageCollection = 0
protected

§ _listenAddress

std::string BaseLib::TcpSocket::_listenAddress
protected

§ _listenPort

std::string BaseLib::TcpSocket::_listenPort
protected

§ _maxConnections

uint32_t BaseLib::TcpSocket::_maxConnections = 10
protected

§ _newConnectionCallback

std::function<void(int32_t clientId, std::string address, uint16_t port)> BaseLib::TcpSocket::_newConnectionCallback
protected

§ _packetReceivedCallback

std::function<void(int32_t clientId, TcpPacket &packet)> BaseLib::TcpSocket::_packetReceivedCallback
protected

§ _port

std::string BaseLib::TcpSocket::_port
protected

§ _readMutex

std::mutex BaseLib::TcpSocket::_readMutex
protected

§ _readTimeout

int64_t BaseLib::TcpSocket::_readTimeout = 15000000
protected

§ _requireClientCert

bool BaseLib::TcpSocket::_requireClientCert = false
protected

§ _socketDescriptor

PFileDescriptor BaseLib::TcpSocket::_socketDescriptor
protected

§ _socketDescriptorMutex

std::mutex BaseLib::TcpSocket::_socketDescriptorMutex
protected

§ _stopServer

std::atomic_bool BaseLib::TcpSocket::_stopServer
protected

§ _tlsPriorityCache

gnutls_priority_t BaseLib::TcpSocket::_tlsPriorityCache = nullptr
protected

§ _useSsl

bool BaseLib::TcpSocket::_useSsl = false
protected

§ _verificationHostname

std::string BaseLib::TcpSocket::_verificationHostname
protected

§ _verifyCertificate

bool BaseLib::TcpSocket::_verifyCertificate = true
protected

§ _verifyHostname

bool BaseLib::TcpSocket::_verifyHostname = true
protected

§ _writeMutex

std::mutex BaseLib::TcpSocket::_writeMutex
protected

§ _writeTimeout

int64_t BaseLib::TcpSocket::_writeTimeout = 15000000
protected

§ average_packets_per_minute_received_

std::vector<AverageMeanData> BaseLib::TcpSocket::average_packets_per_minute_received_
protected

§ average_packets_per_minute_sent_

std::vector<AverageMeanData> BaseLib::TcpSocket::average_packets_per_minute_sent_
protected

§ server_threads_

std::vector<std::thread> BaseLib::TcpSocket::server_threads_
protected

§ server_threads_in_use_

std::atomic<uint32_t> BaseLib::TcpSocket::server_threads_in_use_ {0}
protected

The documentation for this class was generated from the following files: