Документация
ОС Аврора 5.0.1

tlssocket.cpp

В приведённом ниже коде показано, как создать сокет, который может работать через соединение безопасности транспортного уровня (TLS, также известное как SSL).

/*
 Copyright (C) 2007 Justin Karneges <justin@affinix.com>
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
 
#ifndef TLSSOCKET_H
 
#include <QTcpSocket>
#include <QtCrypto>
 
class TLSSocket : public QTcpSocket
{
    Q_OBJECT
public:
    TLSSocket(QObject *parent = nullptr);
    ~TLSSocket() override;
 
    void      connectToHostEncrypted(const QString &host, quint16 port);
    QCA::TLS *tls();
 
    bool waitForReadyRead(int msecs = -1) override;
 
protected:
    // из qiodevice
    qint64 readData(char *data, qint64 maxlen) override;
    qint64 writeData(const char *data, qint64 len) override;
 
private:
    class Private;
    friend class Private;
    Private *d;
};
 
#endif
/*
 Copyright (C) 2007 Justin Karneges <justin@affinix.com>
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
 
#include "tlssocket.h"
 
#include <QCoreApplication>
 
int main(int argc, char **argv)
{
    QCA::Initializer init;
    QCoreApplication qapp(argc, argv);
 
    TLSSocket socket;
    socket.connectToHostEncrypted(QStringLiteral("www.paypal.com"), 443);
    socket.write("GET / HTTP/1.0\r\n\r\n");
    while (socket.waitForReadyRead())
        printf("%s", socket.readAll().constData());
 
    return 0;
}
/*
 Copyright (C) 2007 Justin Karneges <justin@affinix.com>
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
 
#include "tlssocket.h"
 
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
 
class TLSSocket::Private : public QObject
{
    Q_OBJECT
public:
    TLSSocket *       q;
    QTcpSocket *      sock;
    QCA::TLS *        tls;
    QString           host;
    bool              encrypted;
    bool              error, done;
    QByteArray        readbuf, writebuf;
    QCA::Synchronizer sync;
    bool              waiting;
 
    Private(TLSSocket *_q)
        : QObject(_q)
        , q(_q)
        , sync(_q)
    {
        sock = new QTcpSocket(this);
        connect(sock, &QTcpSocket::connected, this, &TLSSocket::Private::sock_connected);
        connect(sock, &QTcpSocket::readyRead, this, &TLSSocket::Private::sock_readyRead);
        connect(sock, &QTcpSocket::bytesWritten, this, &TLSSocket::Private::sock_bytesWritten);
        connect(sock,
                QOverload<QAbstractSocket::SocketError>::of(&QTcpSocket::error),
                this,
                &TLSSocket::Private::sock_error);
 
        tls = new QCA::TLS(this);
        connect(tls, &QCA::TLS::handshaken, this, &TLSSocket::Private::tls_handshaken);
        connect(tls, &QCA::TLS::readyRead, this, &TLSSocket::Private::tls_readyRead);
        connect(tls, &QCA::TLS::readyReadOutgoing, this, &TLSSocket::Private::tls_readyReadOutgoing);
        connect(tls, &QCA::TLS::closed, this, &TLSSocket::Private::tls_closed);
        connect(tls, &QCA::TLS::error, this, &TLSSocket::Private::tls_error);
        tls->setTrustedCertificates(QCA::systemStore());
        encrypted = false;
        error     = false;
        waiting   = false;
        done      = false;
    }
 
    bool waitForReadyRead(int msecs)
    {
        waiting = true;
        bool ok = sync.waitForCondition(msecs);
        // while(1)
        //      QCoreApplication::instance()->processEvents();
        waiting = false;
        if (error || done)
            return false;
        return ok;
    }
 
private Q_SLOTS:
    void sock_connected()
    {
        // printf("сокет подключён\n");
        tls->startClient(host);
    }
 
    void sock_readyRead()
    {
        // printf("сокет готов для чтения\n");
        QByteArray buf = sock->readAll();
        // printf("%d байтов\n", buf.size());
        tls->writeIncoming(buf);
    }
 
    void sock_bytesWritten(qint64 x)
    {
        Q_UNUSED(x);
        // printf("записано байтов: %d\n", (int)x);
    }
 
    void sock_error(QAbstractSocket::SocketError x)
    {
        // printf("ошибка сокета: %d\n", x);
        Q_UNUSED(x);
        done = true;
        if (waiting)
            sync.conditionMet();
    }
 
    void tls_handshaken()
    {
        // printf("рукопожатие tls завершено\n");
        if (tls->peerIdentityResult() != QCA::TLS::Valid) {
            printf("не действительно\n");
            sock->abort();
            tls->reset();
            error = true;
        } else {
            // printf("действительно\n");
            encrypted = true;
            // printf("%d байтов в writebuf\n", writebuf.size());
            if (!writebuf.isEmpty()) {
                // printf("[%s]\n", writebuf.data());
                tls->write(writebuf);
                writebuf.clear();
            }
        }
        if (waiting)
            sync.conditionMet();
    }
 
    void tls_readyRead()
    {
        // printf("tls готов для чтения\n");
        if (waiting)
            sync.conditionMet();
    }
 
    void tls_readyReadOutgoing()
    {
        // printf("tls готов читать исходящие\n");
        QByteArray buf = tls->readOutgoing();
        // printf("%d байтов\n", buf.size());
        sock->write(buf);
    }
 
    void tls_closed()
    {
        // printf("tls закрыт\n");
    }
 
    void tls_error()
    {
        // printf("ошибка tls\n");
    }
};
 
TLSSocket::TLSSocket(QObject *parent)
    : QTcpSocket(parent)
{
    d = new Private(this);
}
 
TLSSocket::~TLSSocket()
{
    delete d;
}
 
void TLSSocket::connectToHostEncrypted(const QString &host, quint16 port)
{
    d->host = host;
    setOpenMode(QIODevice::ReadWrite);
    d->sock->connectToHost(host, port);
}
 
QCA::TLS *TLSSocket::tls()
{
    return d->tls;
}
 
bool TLSSocket::waitForReadyRead(int msecs)
{
    /*if(d->readbuf.isEmpty())
        return false;
 
    if(d->tls->bytesAvailable() == 0)
        return false;*/
 
    return d->waitForReadyRead(msecs);
}
 
qint64 TLSSocket::readData(char *data, qint64 maxlen)
{
    if (!d->error)
        d->readbuf += d->tls->read();
    unsigned char *p        = (unsigned char *)d->readbuf.data();
    int            size     = d->readbuf.size();
    int            readsize = qMin(size, (int)maxlen);
    int            newsize  = size - readsize;
    memcpy(data, p, readsize);
    memmove(p, p + readsize, newsize);
    d->readbuf.resize(newsize);
    return readsize;
}
 
qint64 TLSSocket::writeData(const char *data, qint64 len)
{
    // printf("записывается %d байтов\n", (int)len);
    QByteArray buf(data, len);
    if (d->encrypted)
        d->tls->write(buf);
    else
        d->writebuf += buf;
    return len;
}
 
#include "tlssocket.moc"

Мы используем cookies для персонализации сайта и его более удобного использования. Вы можете запретить cookies в настройках браузера.

Пожалуйста ознакомьтесь с политикой использования cookies.