summaryrefslogtreecommitdiff
path: root/distfoldd/discoverer.cc
blob: 011f9382b86983df9c09307dad2ee495fa75e6cb (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#include <QtCore/QDebug>

#include "discoverer.h"

Discoverer::Discoverer(const QUuid &uuid, uint port, const QString &serviceName, QObject *parent) :
    QObject(parent), _folderUuid(uuid), _hostUuid(QUuid::createUuid()),
    _serviceName(serviceName), _port(port),
    _mtime(), _mtimeChanged(false),
    _receiver(new QUdpSocket(this)), _sender(new QUdpSocket(this)),
    _netConfig(new QNetworkConfigurationManager(this)),
    _timer(new QTimer(this))
{
	connect(_receiver, SIGNAL(readyRead()), SLOT(handleDataAvailable()));
	if (!_receiver->bind(servicePort, QUdpSocket::ShareAddress)) {
		qWarning() << "Failed to bind to discoverer port" << servicePort;
	}
	connect(_netConfig, SIGNAL(onlineStateChanged(bool)), SLOT(handleOnlineStateChanged(bool)));
	connect(_timer, SIGNAL(timeout()), SLOT(handleTimerTimeout()));
	_timer->setSingleShot(true);
	_timer->setTimerType(Qt::VeryCoarseTimer);
	if (_netConfig->isOnline() ||
	    _netConfig->allConfigurations(QNetworkConfiguration::Defined).empty()) {
		// Either only, or _netConfig has no configs so it is useless.
		qDebug() << "Start timer";
		_timer->start(activeBroadcastInterval * 1000);
	} else {
		qDebug() << "I am NOT online";
	}
}

void Discoverer::setLastModifiedTime(const QDateTime& dateTime)
{
	_mtime = dateTime;
	if (_knownHosts.empty()) {
		// Idle mode: do nothing.
	} else {
		// Active mode
		switchToActiveMode();
	}
	_mtimeChanged = true;
}

QByteArray Discoverer::encodeMessage() const
{
	QByteArray ba;
	QByteArray hostUuid = _hostUuid.toString().toLatin1();
	QByteArray folderUuid = _folderUuid.toString().toLatin1();
	QByteArray serviceNameUtf8 = _serviceName.toUtf8();
	Message msg;

	Q_ASSERT(hostUuid.length() == sizeof(msg.hostUuid));
	Q_ASSERT(folderUuid.length() == sizeof(msg.folderUuid));

	ba.reserve(sizeof(msg) + serviceNameUtf8.size());

	msg.mtime = _mtime.toTime_t();
	strncpy(msg.hostUuid, hostUuid.data(), sizeof(msg.hostUuid));
	msg.port = _port;
	strncpy(msg.folderUuid, folderUuid.data(), sizeof(msg.folderUuid));

	ba.append(reinterpret_cast<char*>(&msg), sizeof(msg));
	ba.append(serviceNameUtf8);
	return ba;
}

void Discoverer::switchToActiveMode()
{
	if (!_timer->isActive() || _timer->interval() > activeBroadcastInterval * 1000) {
		_timer->start(activeBroadcastInterval * 1000);
	}
}

void Discoverer::broadcastMessage()
{
	_sender->writeDatagram(encodeMessage(), QHostAddress::Broadcast, servicePort);
	_lastBroadcast = QDateTime::currentDateTime();
	_mtimeChanged = false;
	qDebug() << "Broadcast message at" << _lastBroadcast;
}

void Discoverer::handleDataAvailable()
{
	while (_receiver->hasPendingDatagrams()) {
		QByteArray data;
		QHostAddress sender;
		data.resize(_receiver->pendingDatagramSize());
		_receiver->readDatagram(data.data(), data.size(), &sender);

		handleBroadcastMessage(sender, data);
	}
}

void Discoverer::handleBroadcastMessage(const QHostAddress& sender, const QByteArray &data)
{
	const char *dataPtr = data.data();
	const Message *msg = reinterpret_cast<const Message*>(dataPtr);
	QString serviceName = QString::fromUtf8(&dataPtr[sizeof(Message)]);
	char uuidData[sizeof(msg->hostUuid)];

	strncpy(uuidData, msg->hostUuid, sizeof(uuidData));
	QUuid hostUuid(QString::fromLatin1(uuidData, sizeof(uuidData)));
	strncpy(uuidData, msg->folderUuid, sizeof(uuidData));
	QUuid folderUuid(QString::fromLatin1(uuidData, sizeof(uuidData)));

	if (hostUuid.isNull() || folderUuid.isNull()) {
		qWarning() << "Null uuid";
		return;
	}
	if (hostUuid == _hostUuid) {
		// A message from myself, ignore
		return;
	}
	if (folderUuid != _folderUuid) {
		// A message not about the same folder, ignore
		return;
	}

	qDebug() << "Got message from" << sender << msg->port;
	handleHostSeen(hostUuid);

	QDateTime mtime = QDateTime::fromTime_t(msg->mtime);
	qDebug() << mtime << _mtime << _mtime.secsTo(mtime);
	if (_mtime.secsTo(mtime) > dateTimeCompareMinDelta) {
		// We are outdated, let's try to connect to them.
		emit foundMoreRecentHost(sender, msg->port, mtime);
	}
}

void Discoverer::handleHostSeen(const QUuid &hostUuid)
{
	bool host_previously_seen = _knownHosts.contains(hostUuid);
	_knownHosts[hostUuid].lastSeen = QDateTime::currentDateTime();
	if (!host_previously_seen || _mtimeChanged) {
		switchToActiveMode();
	}
}

void Discoverer::handleTimerTimeout()
{
	qDebug() << "Timer tick";
	broadcastMessage();
	QDateTime now = QDateTime::currentDateTime();
	QHash<QUuid, HostInfo>::iterator i = _knownHosts.begin();
	while (i != _knownHosts.end()) {
		if (i.value().lastSeen.secsTo(now) > lostHostTimeout) {
			i = _knownHosts.erase(i);
		} else {
			++i;
		}
	}
	qDebug() << "Known hosts" << _knownHosts.size();
	_timer->start(idleBroadcastInterval * 1000);
}

void Discoverer::handleOnlineStateChanged(bool online)
{
	if (online) {
		qDebug() << "Online";
		switchToActiveMode();
	} else {
		qDebug() << "Offline";
		_knownHosts.clear();
		_timer->stop();
	}
}