TSDuck v3.44-4659
MPEG Transport Stream Toolkit
Loading...
Searching...
No Matches
ts::TLSServer Class Reference

Implementation of a SSL/TLS server. More...

#include <tsTLSServer.h>

Inheritance diagram for ts::TLSServer:
Collaboration diagram for ts::TLSServer:

Public Types

using SuperClass = TCPServer
 Reference to the superclass.
 

Public Member Functions

 TLSServer (Report *report, const TLSArgs &args)
 Constructor with initial arguments.
 
 TLSServer (Report *report=nullptr)
 Constructor.
 
 TLSServer (ReporterBase *delegate)
 Constructor.
 
 TLSServer (ReporterBase *delegate, const TLSArgs &args)
 Constructor with initial arguments.
 
virtual bool accept (TCPConnection &client, IPSocketAddress &addr, IOSB *=nullptr) override
 Wait for an incoming client connection.
 
void addSubscription (SocketHandlerInterface *handler)
 Add a subscriber to open/close events.
 
bool bind (const IPSocketAddress &addr)
 Bind to a local address and port.
 
void cancelSubscription (SocketHandlerInterface *handler)
 Remove a subscriber to open/close events.
 
virtual bool close (bool silent=false) override
 Close the socket.
 
IP generation () const
 Get the IP generation with which the socket was open.
 
const UStringgetCertificatePath () const
 Get the certificate path for the server.
 
const UStringgetCertificateStore () const
 Get the certificate store.
 
const UStringgetKeyPath () const
 Get the private key path for the server.
 
bool getLocalAddress (IPSocketAddress &addr) const
 Get local socket address.
 
SysSocketType getSocket () const
 Get the underlying socket device handle (use with care).
 
bool isNonBlocking () const
 Check if the device is in non-blocking mode.
 
bool isOpen () const
 Check if socket is open.
 
virtual bool listen (int backlog) override
 Start the server.
 
bool muteReport (bool mute)
 Temporarily mute the associated report.
 
virtual bool open (IP gen) override
 Open the socket.
 
Reportreport () const
 Access the Report which is associated with this object.
 
bool reusePort (bool reuse_port)
 Set the "reuse port" option.
 
void setArgs (const TLSArgs &args)
 Set command line arguments for the server.
 
void setCertificatePath (const UString &path)
 Set the certificate path for the server.
 
void setCertificateStore (const UString &name)
 Set the certificate store.
 
bool setKeepAlive (bool active)
 Set the "keep alive" option.
 
void setKeyPath (const UString &path)
 Set the private key path for the server.
 
bool setLingerTime (int seconds)
 Set the linger time option.
 
bool setNoDelay (bool active)
 Set the "no delay" option.
 
bool setNoLinger ()
 Remove the linger time option.
 
bool setNonBlocking (bool non_blocking)
 Set the device in non-blocking mode.
 
bool setReceiveBufferSize (size_t size)
 Set the receive buffer size.
 
bool setReceiveTimeout (cn::milliseconds timeout)
 Set the receive timeout.
 
ReportsetReport (Report *report)
 Associate this object with another Report to log errors.
 
ReporterBasesetReport (ReporterBase *delegate)
 Associate this object with another ReporterBase to log errors.
 
bool setSendBufferSize (size_t size)
 Set the send buffer size.
 
bool setTTL (int ttl)
 Set the Time To Live (TTL) option.
 

Static Public Member Functions

static int SilentLevel (bool silent)
 Compute a log severity level from a "silent" parameter.
 

Protected Member Functions

virtual bool allowSetNonBlocking () const override
 Check that the non-blocking mode can be set.
 
bool checkNonBlocking (bool non_blocking, const UChar *opname)
 Check the blocking mode of a device.
 
bool checkNonBlocking (IOSB *iosb, const UChar *opname)
 Check the blocking mode of a device.
 
bool convert (IPAddress &addr) const
 Convert an IP address to make it compatible with the socket IP generation.
 
bool createSocket (IP gen, int type, int protocol)
 Create the socket.
 
virtual void declareOpened (SysSocketType sock) override
 Set an open socket descriptor from a subclass.
 
virtual void handleClosed ()
 This virtual method can be overriden by subclasses to be notified of close.
 
virtual void handleOpened ()
 This virtual method can be overriden by subclasses to be notified of open.
 
bool setSystemNonBlocking (SysSocketType fd, bool non_blocking)
 Convenience method to set a system file descriptor or socket handle in non-blocking mode.
 

Protected Attributes

std::recursive_mutex _mutex {}
 Mutex protecting this object.
 

Detailed Description

Implementation of a SSL/TLS server.

Creating a test private key and its self-signed certificate

On UNIX systems (with OpenSSL):

openssl req -quiet -newkey rsa:3072 -new -noenc -x509 -subj="/CN=$(hostname)" -days 3650 -keyout key.pem -out cert.pem

To display the properties of the certificate:

openssl x509 -in cert.pem -noout -text

On Windows:

New-SelfSignedCertificate -FriendlyName "Test Server" -Type SSLServerAuthentication `
-DnsName @([System.Net.Dns]::GetHostName(), "localhost") `
-CertStoreLocation Cert:\CurrentUser\My `
-KeyAlgorithm "RSA" -KeyLength 3072

To display the properties of the certificate:

Get-ChildItem Cert:\CurrentUser\My | Where-Object -Property FriendlyName -eq "Test Server" | Format-List
General-purpose base class for polymophic objects.
Definition tsObject.h:36

A self-signed certificate is considered as invalid. So, make sure to ignore this error. With curl, use option –insecure or -k.

To view the certificate of a server using OpenSSL:

openssl s_client -showcerts -servername <name> -connect <name>:<port> </dev/null | openssl x509 -noout -text

Constructor & Destructor Documentation

◆ TLSServer() [1/4]

ts::TLSServer::TLSServer ( Report report = nullptr)
explicit

Constructor.

Parameters
[in]reportWhere to report errors. The report object must remain valid as long as this object exists or setReport() is used with another Report object. If report is null, log messages are discarded.

◆ TLSServer() [2/4]

ts::TLSServer::TLSServer ( ReporterBase delegate)
explicit

Constructor.

Parameters
[in]delegateUse the report of another ReporterBase. If delegate is null, log messages are discarded.

◆ TLSServer() [3/4]

ts::TLSServer::TLSServer ( Report report,
const TLSArgs args 
)
inline

Constructor with initial arguments.

Parameters
[in]reportWhere to report errors. The report object must remain valid as long as this object exists or setReport() is used with another Report object. If report is null, log messages are discarded.
[in]argsInitial TLS arguments.

◆ TLSServer() [4/4]

ts::TLSServer::TLSServer ( ReporterBase delegate,
const TLSArgs args 
)
inline

Constructor with initial arguments.

Parameters
[in]delegateUse the report of another ReporterBase. If delegate is null, log messages are discarded.
[in]argsInitial TLS arguments.

Member Function Documentation

◆ setArgs()

void ts::TLSServer::setArgs ( const TLSArgs args)

Set command line arguments for the server.

Parameters
[in]argsTLS arguments.

◆ setCertificatePath()

void ts::TLSServer::setCertificatePath ( const UString path)
inline

Set the certificate path for the server.

Parameters
[in]pathPath to the certificate.
  • On UNIX systems (with OpenSSL), this is the path name of the certificate file in PEM format.
  • On Windows, this is the name of a certificate, either its "friendly name", its subject name (without "CN="), its DNS name.

◆ getCertificatePath()

const UString & ts::TLSServer::getCertificatePath ( ) const
inline

Get the certificate path for the server.

Returns
A constant reference to the path to the certificate.
See also
setCertificatePath()

◆ setKeyPath()

void ts::TLSServer::setKeyPath ( const UString path)
inline

Set the private key path for the server.

Parameters
[in]pathPath to the private key.
  • On UNIX systems (with OpenSSL), this is the path name of the private key file in PEM format.
  • On Windows, the private key is retrieved with the certificate and this parameter is unused.

◆ getKeyPath()

const UString & ts::TLSServer::getKeyPath ( ) const
inline

Get the private key path for the server.

Returns
A constant reference to the path to the private key.
See also
setKeyPath()

◆ setCertificateStore()

void ts::TLSServer::setCertificateStore ( const UString name)
inline

Set the certificate store.

Parameters
[in]name
  • On UNIX systems (with OpenSSL), this parameter is unused.
  • On Windows, the possible values are "system" (Cert:\LocalMachine\My) and "user" (Cert:\CurrentUser\My). The default is "user".

◆ getCertificateStore()

const UString & ts::TLSServer::getCertificateStore ( ) const
inline

Get the certificate store.

Returns
A constant reference to the name of the certificate store.
See also
setCertificateStore()

◆ listen()

virtual bool ts::TLSServer::listen ( int  backlog)
overridevirtual

Start the server.

Here, starting the server means starting to listen to incoming client connections. Internally to the kernel, the incoming connections are queued up to backlog. When the method accept() is invoked and some incoming connections are already queued in the kernel, the oldest one is immediately accepted. Otherwise, accept() blocks until a new incoming connection arrives.

Parameters
[in]backlogMaximum number of incoming connections which allowed to queue in the kernel until the next call to accept(). Note that this value is a minimum queue size. But the kernel may accept more. There is no guarantee that additional incoming connections will be rejected if more than backlog are already queueing.
Returns
True on success, false on error.

Reimplemented from ts::TCPServer.

◆ accept()

virtual bool ts::TLSServer::accept ( TCPConnection client,
IPSocketAddress addr,
IOSB iosb = nullptr 
)
overridevirtual

Wait for an incoming client connection.

Parameters
[out]clientThis object receives the new connection. Upon successful return from accept(), the TCPConnection object is a properly connected TCP session. Once the connection is completed, the TCPConnection objects on the client side and the server side are symmetric and can be used the same way.
[out]addrThis object receives the socket address of the client. If the server wants to filter client connections based on their IP address, it may use addr for that.
[in,out]iosbAddress of an IOSB structure. If non-null, the socket must be in non-blocking mode. When null, the socket must be in blocking mode (the default). See the description of IOSB. Important: The parameter iosb should not be used by applications. It should be used only by "reactive classes", which work in combination with a Reactor.
Returns
True on success, false on error.
See also
listen()

Reimplemented from ts::TCPServer.

◆ close()

virtual bool ts::TLSServer::close ( bool  silent = false)
overridevirtual

Close the socket.

If overridden by a subclass, the superclass must be called at the end of the overridden close().

Parameters
[in]silentIf true, do not report errors through the logger. This is typically useful when the socket is in some error condition and closing it is necessary although it may generate additional meaningless errors.
Returns
True on success, false on error.

Reimplemented from ts::TCPServer.

◆ setTTL()

bool ts::TCPSocket::setTTL ( int  ttl)
inherited

Set the Time To Live (TTL) option.

Parameters
[in]ttlThe TTL value, ie. the maximum number of "hops" between routers before an IP packet is dropped.
Returns
True on success, false on error.

◆ setNoLinger()

bool ts::TCPSocket::setNoLinger ( )
inherited

Remove the linger time option.

Returns
True on success, false on error.

◆ setLingerTime()

bool ts::TCPSocket::setLingerTime ( int  seconds)
inherited

Set the linger time option.

Parameters
[in]secondsNumber of seconds to wait after shuting down the socket.
Returns
True on success, false on error.

◆ setKeepAlive()

bool ts::TCPSocket::setKeepAlive ( bool  active)
inherited

Set the "keep alive" option.

Parameters
[in]activeIf true, the socket periodically sends "keep alive" packets when the connection is idle.
Returns
True on success, false on error.

◆ setNoDelay()

bool ts::TCPSocket::setNoDelay ( bool  active)
inherited

Set the "no delay" option.

Parameters
[in]activeIf true, the socket immediately sends outgoing packets. By default, a TCP socket waits a small amount of time after a send() operation to get a chance to group outgoing data from successive send() operations into one single packet.
Returns
True on success, false on error.

◆ open()

virtual bool ts::TCPSocket::open ( IP  gen)
overridevirtualinherited

Open the socket.

Parameters
[in]genIP generation, IPv4 or IPv6. If set to IP::Any, open an IPv6 socket (IPv4 connections allowed).
Returns
True on success, false on error.

Implements ts::Socket.

◆ handleOpened()

virtual void ts::TCPSocket::handleOpened ( )
protectedvirtualinherited

This virtual method can be overriden by subclasses to be notified of open.

All subclasses should explicitly invoke their superclass' handlers.

◆ handleClosed()

virtual void ts::TCPSocket::handleClosed ( )
protectedvirtualinherited

This virtual method can be overriden by subclasses to be notified of close.

All subclasses should explicitly invoke their superclass' handlers.

Reimplemented in ts::TCPConnection.

◆ declareOpened()

virtual void ts::TCPSocket::declareOpened ( SysSocketType  sock)
overrideprotectedvirtualinherited

Set an open socket descriptor from a subclass.

This method is used by a server to declare that a client socket has just become opened.

Parameters
[in]sockNew socket descriptor.

Reimplemented from ts::Socket.

◆ isOpen()

bool ts::Socket::isOpen ( ) const
inlineinherited

Check if socket is open.

Returns
True if socket is open.

◆ generation()

IP ts::Socket::generation ( ) const
inlineinherited

Get the IP generation with which the socket was open.

Returns
The IP generation used to open the socket. Never IP::Any.

◆ setSendBufferSize()

bool ts::Socket::setSendBufferSize ( size_t  size)
inherited

Set the send buffer size.

Parameters
[in]sizeSend buffer size in bytes.
Returns
True on success, false on error.

◆ setReceiveBufferSize()

bool ts::Socket::setReceiveBufferSize ( size_t  size)
inherited

Set the receive buffer size.

Parameters
[in]sizeReceive buffer size in bytes.
Returns
True on success, false on error.

◆ setReceiveTimeout()

bool ts::Socket::setReceiveTimeout ( cn::milliseconds  timeout)
inherited

Set the receive timeout.

Parameters
[in]timeoutReceive timeout in milliseconds. If negative or zero, receive timeout is not used, reception waits forever.
Returns
True on success, false on error.

◆ reusePort()

bool ts::Socket::reusePort ( bool  reuse_port)
inherited

Set the "reuse port" option.

Parameters
[in]reuse_portIf true, the socket is allowed to reuse a local UDP port which is already bound.
Returns
True on success, false on error.

◆ bind()

bool ts::Socket::bind ( const IPSocketAddress addr)
inherited

Bind to a local address and port.

The IP address part of the socket address must one of:

  • IPAddress::AnyAddress4.
    • UDP: Any local interface may be used to send or receive UDP datagrams. For each outgoing packet, the actual interface is selected by the kernel based on the routing rules. Incoming UDP packets for the selected port will be accepted from any local interface.
    • TCP client: Any local interface may be used to connect to a server.
    • TCP server: Any local interface may be used to receive incoming client connections.
  • The IP address of an interface of the local system.
    • UDP: Outgoing packets will be unconditionally sent through this interface. Incoming UDP packets for the selected port will be accepted only when they arrive through the selected interface.
    • TCP client: Outgoing connections will be only allowed through this interface.
    • TCP server: Incoming client connections will be accepted only when they arrive through the selected interface.

Special note for receiving multicast on most Unix systems (at least Linux and macOS): The IP address shall be either AnyAddress4 or the multicast group address. Do not specify a local address to receive multicast on Unix.

The port number part of the socket address must be one of:

  • IPSocketAddress::AnyPort. The socket is bound to an arbitrary unused local UDP or TCP port. This is the usual configuration for a TCP client.
  • A specific port number. If this UDP or TCP port is already bound by another local socket of the same type, the bind operation fails, unless the "reuse port" option has already been set.
Parameters
[in]addrLocal socket address to bind to.
Returns
True on success, false on error.

◆ getLocalAddress()

bool ts::Socket::getLocalAddress ( IPSocketAddress addr) const
inherited

Get local socket address.

Parameters
[out]addrLocal socket address of the connection.
Returns
True on success, false on error.

◆ getSocket()

SysSocketType ts::Socket::getSocket ( ) const
inlineinherited

Get the underlying socket device handle (use with care).

This method is reserved for low-level operations and should not be used by normal applications.

Returns
The underlying socket system device handle or file descriptor. Return SYS_SOCKET_INVALID if the socket is not open.

◆ addSubscription()

void ts::Socket::addSubscription ( SocketHandlerInterface handler)
inherited

Add a subscriber to open/close events.

Parameters
[in]handlerThe object to call on open() and close().

◆ cancelSubscription()

void ts::Socket::cancelSubscription ( SocketHandlerInterface handler)
inherited

Remove a subscriber to open/close events.

Parameters
[in]handlerThe object to no longer call on open() and close().

◆ createSocket()

bool ts::Socket::createSocket ( IP  gen,
int  type,
int  protocol 
)
protectedinherited

Create the socket.

Parameters
[in]genIP generation.
[in]typeSocket type: SOCK_STREAM, SOCK_DGRAM
[in]protocolSocket protocol: IPPROTO_TCP, IPPROTO_UDP
Returns
True on success, false on error.
See also
open(ge, Report&)

◆ convert()

bool ts::Socket::convert ( IPAddress addr) const
protectedinherited

Convert an IP address to make it compatible with the socket IP generation.

Parameters
addr[in,out] The address to convert.
Returns
True on success, false on error.

◆ allowSetNonBlocking()

virtual bool ts::Socket::allowSetNonBlocking ( ) const
overrideprotectedvirtualinherited

Check that the non-blocking mode can be set.

Must be implemented by subclasses which do not support setting the non-blocking in certain states, such as after being opened. The default implementation always allows setting the non-blocking mode.

Returns
True if setting the non-blocking mode is allowed, false otherwise.

Reimplemented from ts::NonBlockingDevice.

◆ setNonBlocking()

bool ts::NonBlockingDevice::setNonBlocking ( bool  non_blocking)
inherited

Set the device in non-blocking mode.

Important: Usually, this method must be called before opening the device, whatever it means. Otherwise it is ignored and the device blocking mode is unchanged.

Parameters
[in]non_blockingIt true, the device is set in non-blocking mode.
Returns
True on success, false if the device is already open and the non-blocking mode is unchanged.

◆ isNonBlocking()

bool ts::NonBlockingDevice::isNonBlocking ( ) const
inlineinherited

Check if the device is in non-blocking mode.

Returns
True if the device is in non-blocking mode, false otherwise.
See also
setNonBlocking()

◆ checkNonBlocking() [1/2]

bool ts::NonBlockingDevice::checkNonBlocking ( bool  non_blocking,
const UChar opname 
)
protectedinherited

Check the blocking mode of a device.

Called by subclass methods which are explicitly called in blocking or non-blocking mode.

Parameters
[in]non_blockingThe required non-blocking mode.
[in]opnameName of the operation, for the error message.
Returns
True on success, false on error.

◆ checkNonBlocking() [2/2]

bool ts::NonBlockingDevice::checkNonBlocking ( IOSB iosb,
const UChar opname 
)
protectedinherited

Check the blocking mode of a device.

Called by subclass methods which are explicitly called in blocking or non-blocking mode.

Parameters
[in,out]iosbAddress of an IOSB structure. If non-null, we are in non-blocking mode. When null, we are in blocking mode. When non-null, pending is reset to false and overlap is zeroed.
[in]opnameName of the operation, for the error message.
Returns
True on success, false on error.

◆ setSystemNonBlocking()

bool ts::NonBlockingDevice::setSystemNonBlocking ( SysSocketType  fd,
bool  non_blocking 
)
protectedinherited

Convenience method to set a system file descriptor or socket handle in non-blocking mode.

Parameters
[in]fdSystem file descriptor (UNIX) or socket handle (Windows). On Windows, non-socket devices shall be opened with flag FILE_FLAG_OVERLAPPED instead of using this method.
[in]non_blockingIt true, the device is set in non-blocking mode.
Returns
True on success, false on error.

◆ report()

Report & ts::ReporterBase::report ( ) const
inherited

Access the Report which is associated with this object.

Can be called from another thread only if the Report object is thread-safe.

Returns
A reference to the associated report.

◆ setReport() [1/2]

Report * ts::ReporterBase::setReport ( Report report)
inherited

Associate this object with another Report to log errors.

Parameters
[in]reportWhere to report errors. The report object must remain valid as long as this object exists or setReport() is used with another Report object. If report is null, log messages are discarded.
Returns
The address of the previous Report object or a null pointer if there was none.

◆ setReport() [2/2]

ReporterBase * ts::ReporterBase::setReport ( ReporterBase delegate)
inherited

Associate this object with another ReporterBase to log errors.

Parameters
[in]delegateUse the report of another ReporterBase. If delegate is null, the previous explicit Report is used..
Returns
The address of the previous ReporterBase object or a null pointer if there was none.

◆ muteReport()

bool ts::ReporterBase::muteReport ( bool  mute)
inherited

Temporarily mute the associated report.

Parameters
[in]muteIt true, report() will return a null report (log messages are discarded), until muteReport() is invoked again with mute set to false.
Returns
Previous state of the mute field.

◆ SilentLevel()

static int ts::ReporterBase::SilentLevel ( bool  silent)
inlinestaticinherited

Compute a log severity level from a "silent" parameter.

Some subclass methods have a "silent" parameter to avoid reporting errors which may be insignificant, typically when closing a device after an error, in which case the close operation may produce other errors if the previous error left the device in an inconsistent state. While those errors should not be displayed as errors, we still display them at debug level.

Parameters
[in]silentIf true, do not report errors, report debug messages instead.
Returns
Error when silent is false, Debug otherwise.

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