summaryrefslogtreecommitdiff
path: root/distfoldd/server.cc
blob: a0ab98f22163e2d42ecb8a53e67fc9cf8672e081 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtNetwork/QSslSocket>

#include "localkey.h"
#include "server.h"

Server::Server(QObject *parent) :
    QTcpServer(parent)
{
	loadKeys();
	if (!listen()) {
		qWarning() << "Failed to start server socket";
	}
}

void Server::loadKeys()
{
	QDir local_key_dir(LocalKey::localKeyDir());
	QFile cert_file(local_key_dir.absoluteFilePath("server.crt"));
	if (cert_file.open(QIODevice::ReadOnly)) {
		_cert = QSslCertificate(&cert_file, QSsl::Pem);
		cert_file.close();
	}
	if (_cert.isNull()) {
		qWarning() << "Could not load server certificate";
	}
	QFile key_file(local_key_dir.absoluteFilePath("server.key"));
	if (key_file.open(QIODevice::ReadOnly)) {
		_key = QSslKey(&key_file, QSsl::Rsa, QSsl::Pem);
		key_file.close();
	}
	if (_key.isNull()) {
		qWarning() << "Could not load private key";
	}
}

void Server::incomingConnection(int socketDescriptor)
{
	QSslSocket *socket = new QSslSocket(this);
	connect(socket, SIGNAL(error(QAbstractSocket::SocketError)),
	        SLOT(handleSocketError(QAbstractSocket::SocketError)));
	if (socket->setSocketDescriptor(socketDescriptor)) {
		socket->setLocalCertificate(_cert);
		socket->setPrivateKey(_key);
		socket->setPeerVerifyMode(QSslSocket::QueryPeer);
		socket->startServerEncryption();
		addPendingConnection(socket);
	} else {
		delete socket;
	}
}

void Server::handleSocketError(QAbstractSocket::SocketError error)
{
	QSslSocket *socket = qobject_cast<QSslSocket*>(sender());
	qDebug() << "Server socket error:" << socket->error() << socket->errorString();
}