Warning

This section contains snippets that were automatically translated from C++ to Python and may contain errors.

SSL Server and Client#

Setting up a secure Remote Object network using QSslSockets.

Encrypting communication is critical when you need to pass data through a network you don’t have full control over. The two applications in this example show how to share remote objects over an SSL connection, and how to access them.

../_images/ssl-example.webp

Both sslserver and sslcppclient use a custom root CA certificate to validate each other’s certificates all located in sslserver/cert.

SSL Server#

The sslserver is configured with certificates and a private key.

    config = QSslConfiguration.defaultConfiguration()
    config.setCaCertificates(QSslCertificate.fromPath(":/sslcert/rootCA.pem"))
    certificateFile = QFile(":/sslcert/server.crt")
    if certificateFile.open(QIODevice.ReadOnly | QIODevice.Text):
        config.setLocalCertificate(QSslCertificate(certificateFile.readAll(), QSsl.Pem))
else:
        qFatal("Could not open certificate file")
    keyFile = QFile(":/sslcert/server.key")
    if keyFile.open(QIODevice.ReadOnly | QIODevice.Text):
        key = QSslKey(keyFile.readAll(), QSsl.Rsa, QSsl.Pem, QSsl.PrivateKey)
        if key.isNull():
            qFatal("Key is not valid")
        config.setPrivateKey(key)
    else:
        qFatal("Could not open key file")

    config.setPeerVerifyMode(QSslSocket.VerifyPeer)
    QSslConfiguration.setDefaultConfiguration(config)

Then it creates a QRemoteObjectHost object and a QSslServer object. The QSslServer object listens on port 65511. Then setHostUrl is called on the QRemoteObjectHost object with the URL of the QSslServer object.

host = QRemoteObjectHost()
server = QSslServer()
server.listen(QHostAddress.Any, 65511)
host.setHostUrl(server.serverAddress().toString(), QRemoteObjectHost.AllowExternalRegistration)

A lambda is used to handle the errorOccurred signal by outputting the error to the terminal. A second lambda is connected to the pendingConnectionAvailable signal, which connects an error handler, and calls addHostSideConnection on the QRemoteObjectHost object with the incoming socket as argument to make the host object use the socket for communication.

server.errorOccurred.connect(
                 [](QSslSocket socket, QAbstractSocket.SocketError error) {
                     Q_UNUSED(socket)
                     print("QSslServer.errorOccurred", error)
                 })
server.pendingConnectionAvailable.connect([&server, &host]() {
    print("New connection available")
    socket = QSslSocket(server.nextPendingConnection())
    Q_ASSERT(socket)
    socket.errorOccurred.connect(
                     [](QAbstractSocket.SocketError error) {
                         print("QSslSocket.error", error)
                     })
    host.addHostSideConnection(socket)
})

Finally, a MinuteTimer object is created and enableRemoting is called on the QRemoteObjectHost object with the MinuteTimer object as argument to enable it to be shared.

timer = MinuteTimer()
host.enableRemoting(timer)

SSL Client#

The sslcppclient sets the root CA certificate and then creates a Tester object.

if __name__ == "__main__":

    a = QCoreApplication(argc, argv)
    config = QSslConfiguration.defaultConfiguration()
    config.setCaCertificates(QSslCertificate.fromPath(":/sslcert/rootCA.pem"))
    QSslConfiguration.setDefaultConfiguration(config)
    t = Tester()
    return a.exec()

In the Tester constructor a temporary QRemoteObjectNode object is created, and setupConnection is used to create and configure a QSslSocket object. An error handler is connected, and the QSslSocket is used by the QRemoteObjectNode object by calling addClientSideConnection on it.

m_client = QRemoteObjectNode()
socket = setupConnection()
socket.errorOccurred.connect(
        socket, [](QAbstractSocket.SocketError error){
    print("QSslSocket.error", error)
})
m_client.addClientSideConnection(socket)

Then three QScopedPointer that are members of the Tester class are connected to three replicas of MinuteTimer by using acquire on the QRemoteObjectNode object. Finally QTimer::singleShot is used four times to call reset after a delay.

ptr1.reset(m_client.acquire< MinuteTimerReplica >())
ptr2.reset(m_client.acquire< MinuteTimerReplica >())
ptr3.reset(m_client.acquire< MinuteTimerReplica >())
QTimer::singleShot(0, self.clear)
QTimer::singleShot(1, self.clear)
QTimer::singleShot(10000, self.clear)
QTimer::singleShot(11000, self.clear)

When Tester::clear is called for the first three times, one pointer is checked that it is bound and then reset, for a different pointer each time. When it is called for the fourth time it causes the application to quit.

def clear():

    i = 0
    if i == 0:
        i = i + 1
        if ptr1.isNull():
            qCritical() << "Pointer 1 was not set"
        ptr1.reset()
     elif i == 1:
        i = i + 1
        if ptr2.isNull():
            qCritical() << "Pointer 2 was not set"
        ptr2.reset()
     elif i == 2:
        i = i + 1
        if ptr3.isNull():
            qCritical() << "Pointer 3 was not set"
        ptr3.reset()
    else:
        qApp.quit()

Example project @ code.qt.io