Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QSslSocket: how to know if the client use http or https



  • Hello everybody,

    I created a server web in qt with QTcpServer . I would like the server be accesible with http and https (ssl). I can configure my server to use one or other but i don't know how to do both.

    void HttpServer::incomingConnection(qintptr socketDescriptor)
    {
        bool sslEnable = // how to know what the client want ?
    
        if (!sslEnable) {
            QTcpSocket *socket = new QTcpSocket(this);
            socket->setSocketDescriptor(socketDescriptor);
            addPendingConnection(socket);
        } else {
            QSslSocket *socket = new QSslSocket(this);
    
            if (socket->setSocketDescriptor(socketDescriptor)) {
                connect(socket, &QSslSocket::encrypted, this, &HttpServer::encrypted);
                connect(socket,
                        SIGNAL(sslErrors(QList<QSslError>)),
                        this,
                        SLOT(sslErrors(QList<QSslError>)));
                connect(socket, &QSslSocket::peerVerifyError, this, &HttpServer::peerVerifyError);
    
                socket->setProtocol(QSsl::TlsV1_2);
                socket->setLocalCertificate(certificate);
                socket->setPrivateKey(key);
                socket->setSocketOption(QAbstractSocket::KeepAliveOption, 1);
                socket->setPeerVerifyMode(QSslSocket::QueryPeer);
                socket->startServerEncryption();
    
                addPendingConnection(socket);
            } else {
                socket->deleteLater();
            }
        }
    }
    

    thank you for your help


  • Qt Champions 2017

    You're half way there. You need to exchange a couple of message over plain TCP with the client to negotiate if SSL is supported, and which protocols can be used, and then you can configure the ssl socket (if it is) and call startServerEncryption. Otherwise you just use the QSslSocket as a plain QTcpSocket.



  • @kshegunov do you have an example?


  • Qt Champions 2017

    @Snyfir said in QSslSocket: how to know if the client use http or https:

    @kshegunov do you have an example?

    I haven't implemented the HTTP protocol before, so no, I don't. Here's an rfc, you can check out, however.


  • Lifetime Qt Champion

    Hi,

    You might want to check the cutelyst project for inspiration.

    On a side note, it usually boils down to:

    • Connect on port 80 -> http
    • Connect on port 443 -> https

    But in the actual date and time, you should just redirect port 80 to 443 and to https communication only.


Log in to reply