QtNetwork (examples) - update secure socket client example

This patch contains:

- some cosmetic changes to  make example look more like
  modern C++;
- UI initialization code and SSL signals handling were split
  into separate member-functions;
- useless checks 'if (socket)' were deleted;
- widget's minimum size is now fixed + font size
  in 'CertInfo' dialog increased to make it readable.

Change-Id: I7aadb78896832a989494d280d6da0635045f948c
Reviewed-by: Timur Pocheptsov <timur.pocheptsov@qt.io>
Reviewed-by: Edward Welbourne <edward.welbourne@qt.io>
This commit is contained in:
Timur Pocheptsov 2017-09-21 13:24:07 +02:00 committed by Edward Welbourne
parent 7896efdd9f
commit ddb191e47a
8 changed files with 135 additions and 114 deletions

View File

@ -1,6 +1,6 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
@ -57,8 +57,8 @@ CertificateInfo::CertificateInfo(QWidget *parent)
form = new Ui_CertificateInfo;
form->setupUi(this);
connect(form->certificationPathView, SIGNAL(currentIndexChanged(int)),
this, SLOT(updateCertificateInfo(int)));
connect(form->certificationPathView, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &CertificateInfo::updateCertificateInfo);
}
CertificateInfo::~CertificateInfo()
@ -68,25 +68,23 @@ CertificateInfo::~CertificateInfo()
void CertificateInfo::setCertificateChain(const QList<QSslCertificate> &chain)
{
this->chain = chain;
certificateChain = chain;
form->certificationPathView->clear();
for (int i = 0; i < chain.size(); ++i) {
const QSslCertificate &cert = chain.at(i);
for (int i = 0; i < certificateChain.size(); ++i) {
const QSslCertificate &cert = certificateChain.at(i);
form->certificationPathView->addItem(tr("%1%2 (%3)").arg(!i ? QString() : tr("Issued by: "))
.arg(cert.subjectInfo(QSslCertificate::Organization).join(QLatin1Char(' ')))
.arg(cert.subjectInfo(QSslCertificate::CommonName).join(QLatin1Char(' '))));
}
form->certificationPathView->setCurrentIndex(0);
}
void CertificateInfo::updateCertificateInfo(int index)
{
form->certificateInfoView->clear();
if (index >= 0 && index < chain.size()) {
const QSslCertificate &cert = chain.at(index);
if (index >= 0 && index < certificateChain.size()) {
const QSslCertificate &cert = certificateChain.at(index);
QStringList lines;
lines << tr("Organization: %1").arg(cert.subjectInfo(QSslCertificate::Organization).join(QLatin1Char(' ')))
<< tr("Subunit: %1").arg(cert.subjectInfo(QSslCertificate::OrganizationalUnitName).join(QLatin1Char(' ')))
@ -101,9 +99,7 @@ void CertificateInfo::updateCertificateInfo(int index)
<< tr("Issuer Locality: %1").arg(cert.issuerInfo(QSslCertificate::LocalityName).join(QLatin1Char(' ')))
<< tr("Issuer State/Province: %1").arg(cert.issuerInfo(QSslCertificate::StateOrProvinceName).join(QLatin1Char(' ')))
<< tr("Issuer Common Name: %1").arg(cert.issuerInfo(QSslCertificate::CommonName).join(QLatin1Char(' ')));
foreach (QString line, lines)
for (const auto &line : lines)
form->certificateInfoView->addItem(line);
} else {
form->certificateInfoView->clear();
}
}

View File

@ -1,6 +1,6 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
@ -51,8 +51,9 @@
#ifndef CERTIFICATEINFO_H
#define CERTIFICATEINFO_H
#include <QtWidgets/QDialog>
#include <QtNetwork/QSslCertificate>
#include <QDialog>
#include <QList>
#include <QSslCertificate>
QT_BEGIN_NAMESPACE
class Ui_CertificateInfo;
@ -62,7 +63,7 @@ class CertificateInfo : public QDialog
{
Q_OBJECT
public:
CertificateInfo(QWidget *parent = 0);
explicit CertificateInfo(QWidget *parent = nullptr);
~CertificateInfo();
void setCertificateChain(const QList<QSslCertificate> &chain);
@ -71,8 +72,8 @@ private slots:
void updateCertificateInfo(int index);
private:
Ui_CertificateInfo *form;
QList<QSslCertificate> chain;
Ui_CertificateInfo *form = nullptr;
QList<QSslCertificate> certificateChain;
};
#endif

View File

@ -42,7 +42,7 @@
<widget class="QListWidget" name="certificateInfoView">
<property name="font">
<font>
<pointsize>8</pointsize>
<pointsize>10</pointsize>
</font>
</property>
<property name="wordWrap">

View File

@ -1,6 +1,6 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
@ -50,6 +50,9 @@
#include <QApplication>
#include <QMessageBox>
#include <QtNetwork>
QT_REQUIRE_CONFIG(ssl);
#include "sslclient.h"
@ -61,7 +64,7 @@ int main(int argc, char **argv)
if (!QSslSocket::supportsSsl()) {
QMessageBox::information(0, "Secure Socket Client",
"This system does not support OpenSSL.");
"This system does not support SSL/TLS.");
return -1;
}

View File

@ -1,3 +1,5 @@
requires(qtHaveModule(network))
HEADERS += certificateinfo.h \
sslclient.h
SOURCES += certificateinfo.cpp \

View File

@ -1,6 +1,6 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
@ -50,29 +50,17 @@
#include "certificateinfo.h"
#include "sslclient.h"
#include "ui_sslclient.h"
#include "ui_sslerrors.h"
#include <QtWidgets/QScrollBar>
#include <QtWidgets/QStyle>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QMessageBox>
#include <QtNetwork/QSslCipher>
#include <QtCore>
SslClient::SslClient(QWidget *parent)
: QWidget(parent), socket(0), padLock(0), executingDialog(false)
: QWidget(parent)
{
form = new Ui_Form;
form->setupUi(this);
form->hostNameEdit->setSelection(0, form->hostNameEdit->text().size());
form->sessionOutput->setHtml(tr("&lt;not connected&gt;"));
connect(form->hostNameEdit, SIGNAL(textChanged(QString)),
this, SLOT(updateEnabledState()));
connect(form->connectButton, SIGNAL(clicked()),
this, SLOT(secureConnect()));
connect(form->sendButton, SIGNAL(clicked()),
this, SLOT(sendData()));
setupUi();
setupSecureSocket();
}
SslClient::~SslClient()
@ -82,17 +70,15 @@ SslClient::~SslClient()
void SslClient::updateEnabledState()
{
bool unconnected = !socket || socket->state() == QAbstractSocket::UnconnectedState;
const bool unconnected = socket->state() == QAbstractSocket::UnconnectedState;
form->hostNameEdit->setReadOnly(!unconnected);
form->hostNameEdit->setFocusPolicy(unconnected ? Qt::StrongFocus : Qt::NoFocus);
form->hostNameLabel->setEnabled(unconnected);
form->portBox->setEnabled(unconnected);
form->portLabel->setEnabled(unconnected);
form->connectButton->setEnabled(unconnected && !form->hostNameEdit->text().isEmpty());
bool connected = socket && socket->state() == QAbstractSocket::ConnectedState;
const bool connected = socket->state() == QAbstractSocket::ConnectedState;
form->sessionOutput->setEnabled(connected);
form->sessionInput->setEnabled(connected);
form->sessionInputLabel->setEnabled(connected);
@ -101,20 +87,6 @@ void SslClient::updateEnabledState()
void SslClient::secureConnect()
{
if (!socket) {
socket = new QSslSocket(this);
connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
connect(socket, SIGNAL(encrypted()),
this, SLOT(socketEncrypted()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(socketError(QAbstractSocket::SocketError)));
connect(socket, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(sslErrors(QList<QSslError>)));
connect(socket, SIGNAL(readyRead()),
this, SLOT(socketReadyRead()));
}
socket->connectToHostEncrypted(form->hostNameEdit->text(), form->portBox->value());
updateEnabledState();
}
@ -125,20 +97,18 @@ void SslClient::socketStateChanged(QAbstractSocket::SocketState state)
return;
updateEnabledState();
if (state == QAbstractSocket::UnconnectedState) {
form->sessionInput->clear();
form->hostNameEdit->setPalette(QPalette());
form->hostNameEdit->setFocus();
form->cipherLabel->setText(tr("<none>"));
if (padLock)
padLock->hide();
padLock->hide();
}
}
void SslClient::socketEncrypted()
{
if (!socket)
return; // might have disconnected already
form->sessionOutput->clear();
form->sessionInput->setFocus();
@ -146,36 +116,12 @@ void SslClient::socketEncrypted()
palette.setColor(QPalette::Base, QColor(255, 255, 192));
form->hostNameEdit->setPalette(palette);
QSslCipher ciph = socket->sessionCipher();
QString cipher = QString("%1, %2 (%3/%4)").arg(ciph.authenticationMethod())
.arg(ciph.name()).arg(ciph.usedBits()).arg(ciph.supportedBits());;
form->cipherLabel->setText(cipher);
if (!padLock) {
padLock = new QToolButton;
padLock->setIcon(QIcon(":/encrypted.png"));
#ifndef QT_NO_CURSOR
padLock->setCursor(Qt::ArrowCursor);
#endif
padLock->setToolTip(tr("Display encryption details."));
int extent = form->hostNameEdit->height() - 2;
padLock->resize(extent, extent);
padLock->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Ignored);
QHBoxLayout *layout = new QHBoxLayout(form->hostNameEdit);
layout->setMargin(form->hostNameEdit->style()->pixelMetric(QStyle::PM_DefaultFrameWidth));
layout->setSpacing(0);
layout->addStretch();
layout->addWidget(padLock);
form->hostNameEdit->setLayout(layout);
connect(padLock, SIGNAL(clicked()),
this, SLOT(displayCertificateInfo()));
} else {
padLock->show();
}
const QSslCipher cipher = socket->sessionCipher();
const QString cipherInfo = QString("%1, %2 (%3/%4)").arg(cipher.authenticationMethod())
.arg(cipher.name()).arg(cipher.usedBits())
.arg(cipher.supportedBits());;
form->cipherLabel->setText(cipherInfo);
padLock->show();
}
void SslClient::socketReadyRead()
@ -185,7 +131,7 @@ void SslClient::socketReadyRead()
void SslClient::sendData()
{
QString input = form->sessionInput->text();
const QString input = form->sessionInput->text();
appendString(input + '\n');
socket->write(input.toUtf8() + "\r\n");
form->sessionInput->clear();
@ -193,7 +139,12 @@ void SslClient::sendData()
void SslClient::socketError(QAbstractSocket::SocketError)
{
if (handlingSocketError)
return;
handlingSocketError = true;
QMessageBox::critical(this, tr("Connection error"), socket->errorString());
handlingSocketError = false;
}
void SslClient::sslErrors(const QList<QSslError> &errors)
@ -201,10 +152,10 @@ void SslClient::sslErrors(const QList<QSslError> &errors)
QDialog errorDialog(this);
Ui_SslErrors ui;
ui.setupUi(&errorDialog);
connect(ui.certificateChainButton, SIGNAL(clicked()),
this, SLOT(displayCertificateInfo()));
connect(ui.certificateChainButton, &QPushButton::clicked,
this, &SslClient::displayCertificateInfo);
foreach (const QSslError &error, errors)
for (const auto &error : errors)
ui.sslErrorList->addItem(error.errorString());
executingDialog = true;
@ -219,10 +170,69 @@ void SslClient::sslErrors(const QList<QSslError> &errors)
void SslClient::displayCertificateInfo()
{
CertificateInfo *info = new CertificateInfo(this);
info->setCertificateChain(socket->peerCertificateChain());
info->exec();
info->deleteLater();
CertificateInfo info;
info.setCertificateChain(socket->peerCertificateChain());
info.exec();
}
void SslClient::setupUi()
{
if (form)
return;
form = new Ui_Form;
form->setupUi(this);
form->hostNameEdit->setSelection(0, form->hostNameEdit->text().size());
form->sessionOutput->setHtml(tr("&lt;not connected&gt;"));
connect(form->hostNameEdit, SIGNAL(textChanged(QString)),
this, SLOT(updateEnabledState()));
connect(form->connectButton, SIGNAL(clicked()),
this, SLOT(secureConnect()));
connect(form->sendButton, SIGNAL(clicked()),
this, SLOT(sendData()));
padLock = new QToolButton;
padLock->setIcon(QIcon(":/encrypted.png"));
connect(padLock, SIGNAL(clicked()), this, SLOT(displayCertificateInfo()));
#if QT_CONFIG(cursor)
padLock->setCursor(Qt::ArrowCursor);
#endif
padLock->setToolTip(tr("Display encryption details."));
const int extent = form->hostNameEdit->height() - 2;
padLock->resize(extent, extent);
padLock->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Ignored);
QHBoxLayout *layout = new QHBoxLayout(form->hostNameEdit);
layout->setMargin(form->hostNameEdit->style()->pixelMetric(QStyle::PM_DefaultFrameWidth));
layout->setSpacing(0);
layout->addStretch();
layout->addWidget(padLock);
form->hostNameEdit->setLayout(layout);
padLock->hide();
}
void SslClient::setupSecureSocket()
{
if (socket)
return;
socket = new QSslSocket(this);
connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
connect(socket, SIGNAL(encrypted()),
this, SLOT(socketEncrypted()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(socketError(QAbstractSocket::SocketError)));
connect(socket, SIGNAL(sslErrors(QList<QSslError>)),
this, SLOT(sslErrors(QList<QSslError>)));
connect(socket, SIGNAL(readyRead()),
this, SLOT(socketReadyRead()));
}
void SslClient::appendString(const QString &line)

View File

@ -1,6 +1,6 @@
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
@ -51,13 +51,13 @@
#ifndef SSLCLIENT_H
#define SSLCLIENT_H
#include <QtWidgets/QWidget>
#include <QtNetwork/QAbstractSocket>
#include <QtNetwork/QSslSocket>
#include <QtNetwork>
QT_REQUIRE_CONFIG(ssl);
#include <QtWidgets>
QT_BEGIN_NAMESPACE
class QSslSocket;
class QToolButton;
class Ui_Form;
QT_END_NAMESPACE
@ -65,7 +65,7 @@ class SslClient : public QWidget
{
Q_OBJECT
public:
SslClient(QWidget *parent = 0);
explicit SslClient(QWidget *parent = nullptr);
~SslClient();
private slots:
@ -80,12 +80,15 @@ private slots:
void displayCertificateInfo();
private:
void setupUi();
void setupSecureSocket();
void appendString(const QString &line);
QSslSocket *socket;
QToolButton *padLock;
Ui_Form *form;
bool executingDialog;
QSslSocket *socket = nullptr;
QToolButton *padLock = nullptr;
Ui_Form *form = nullptr;
bool handlingSocketError = false;
bool executingDialog = false;
};
#endif

View File

@ -10,6 +10,12 @@
<height>320</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>343</width>
<height>320</height>
</size>
</property>
<property name="windowTitle">
<string>Secure Socket Client</string>
</property>
@ -114,8 +120,8 @@
<string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif'; font-size:9pt;&quot;&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'.SF NS Text'; font-size:13pt; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif'; font-size:9pt;&quot;&gt;&lt;br /&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>