#include "messagethread.h"
#include <QIODevice>
#include <QDataStream>
#include <QAbstractSocket>
#include <QFile>
#include <QCoreApplication>
#include <QDebug>
MessageThread
::MessageThread(int socketDescriptor,
QObject *parent
):QThread(parent
){
m_socketDescriptor = socketDescriptor;
m_numOfExpectedBytes = 0;
m_cleanExitDone = false;
}
MessageThread::~MessageThread()
{
delete m_mutex;
}
void MessageThread::run(void)
{
#ifdef UNSECURE_CONNECTION
#else
m_socket = new QSslSocket();
#endif
if (m_socket->setSocketDescriptor(m_socketDescriptor))
{
QList<QSslCertificate> certificateList;
certificateList.append(QSslCertificate());
connect(m_socket, SIGNAL(readyRead()), this, SLOT(processReadyRead()), Qt::DirectConnection);
connect(m_socket, SIGNAL(disconnected()), this, SLOT(performCleanExit()));
#ifdef UNSECURE_CONNECTION
// Nothing to do if the connection is unsecure
#else
// Add the key that will make the handshake
m_socket->setPrivateKey(":/certs/my-key.pem");
m_socket->setLocalCertificate(":/certs/my-cert.pem");
// Add the certificate authority to the list of certificate sent
QFile f
(":/certs/cacert.pem");
QSslCertificate cert(f.readAll());
if (!cert.isValid())
qDebug("Invaild certificate");
m_socket->addCaCertificate(cert);
m_socket->startServerEncryption();
#endif
}
else
{
qDebug()<<tr("Could not create socket from descriptor");
qDebug()<<m_socket->errorString();
performCleanExit();
}
#ifndef NO_AUTH_TIME_LIMIT
m_authorized = false;
connect(m_authTimer, SIGNAL(timeout()), this, SLOT(checkPending()), Qt::DirectConnection);
m_authTimer->setInterval(THREAD_MAX_PENDING_CONN_INTERVAL);
m_authTimer->setSingleShot(true);
m_authTimer->start();
#endif
/* Call the event loop of the thread */
exec();
}
void MessageThread::performCleanExit(void)
{
m_mutex->lock();
if (!m_cleanExitDone)
{
m_cleanExitDone = true;
s = m_socket->state();
// Remove the connection
{
m_socket->disconnectFromHost();
m_socket->waitForDisconnected();
}
disconnect(m_socket, 0, 0, 0);
m_socket->deleteLater();
}
#ifndef NO_AUTH_TIME_LIMIT
m_authTimer->deleteLater();
#endif
m_mutex->unlock();
// Cover the case where we started with this function and the check pending
// is called right after quit().
quit();
}
void MessageThread::processReadyRead(void)
{
if (m_socket->bytesAvailable() == 0)
{
return;
}
m_socket->readAll();
//performCleanExit();
}
void MessageThread::checkPending(void)
{
#ifndef NO_AUTH_TIME_LIMIT
if (!m_authorized)
{
qDebug("Time out baby");
performCleanExit();
}
#endif
}