summaryrefslogtreecommitdiffstats
path: root/src/client/connectwindow/connectwindow.cpp
blob: 07a1a76fdfae8805592726c17b6bb22a87f3ef2a (plain) (blame)
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/*
 * connectwindow.cpp
 *
 *  Created on: 28.01.2013
 *      Author: sr
 */

#include "connectwindow.h"
#include "../../shared/settings.h"
#include "../../shared/network.h"
#include "../../shared/util.h"

#include "../net/serverconnection.h"

#include <QNetworkInterface>

#define UDPBUFSIZ 9000
#define SALT_LEN 18

/**
 * Initialize Connection Window.
 * @param parent
 */
ConnectWindow::ConnectWindow(QWidget *parent) :
	QDialog(parent), _connected(false), _timerDiscover(0), _timerHide(0), _connection(NULL), _state(Idle),
	_hashErrorCount(0), _hashSslErrorCount(0), _certErrorCount(0), _ipErrorCount(0), _discoveryInterval(800)
{
    setupUi(this);
    //
	connect(cmdOK, SIGNAL(clicked()), this, SLOT(onOkClick()));
	connect(cmdCancel, SIGNAL(clicked()), this, SLOT(onCancelClick()));
	int tries = 10;
	while (tries-- != 0)
	{
		const quint16 port = (quint16)(qrand() % 10000) + 10000;
		if (_discoverySocket.bind(QHostAddress::Any, port))
			break;
		if (tries == 0)
			qFatal("Could not bind to any UDP port for server discovery.");
	}
    connect(&_discoverySocket, SIGNAL(readyRead()), this, SLOT(onUdpReadyRead()));
	this->setState(Idle);
    lblCheckmark->hide();
}

ConnectWindow::~ConnectWindow()
{

}

/**
 * Set Client as Connected (true) or Disconnected (false).
 * After settings updateState() is called.
 * @param connected
 */
void ConnectWindow::setConnected(const bool connected)
{
	_connected = connected;
	this->updateState();
	if (_state == Scanning)
	{
		killTimer(_timerDiscover);
		_discoveryInterval = 1000;
		_timerDiscover = startTimer(_discoveryInterval);
	}
}

/**
 * Set current state of Client.
 * After setting state updateState() is called.
 * @param state
 */
void ConnectWindow::setState(const ConnectionState state)
{
	if (_state != state)
	{
		_state = state;
		this->updateState();
	}
}

/**
 * Handle changes in state and update window.
 */
void ConnectWindow::updateState()
{
	txtName->setEnabled(_state == Idle && !_connected);

	if (_connected)
	{
        lblCheckmark->setVisible(true);
		cmdOK->setEnabled(true);
		cmdOK->setText(tr("&Disconnect"));
		lblStatus->setText(tr("Connected."));
		txtName->setEnabled(false);
		return;
	}

	if (_state != Idle)
		cmdOK->setText(tr("&Stop"));
	else
		cmdOK->setText(tr("&Connect"));

	switch (_state)
	{
	case Idle:
		lblStatus->setText(tr("Ready to connect; please enter session name."));
		break;
	case Scanning:
		lblStatus->setText(tr("Scanning for session %1.").arg(txtName->text()));
		_timerDiscover = startTimer(_discoveryInterval);
		break;
	case Connecting:
		lblStatus->setText(tr("Found session, connecting..."));
		break;
	case AwaitingChallenge:
		lblStatus->setText(tr("Waiting for server challenge..."));
		break;
	case AwaitingChallengeResponse:
		lblStatus->setText(tr("Replied to challenge, sent own..."));
		break;
	case LoggingIn:
		lblStatus->setText(tr("Logging in..."));
		break;
	case Connected:
		lblStatus->setText(tr("Connection established!"));
		break;
	case InvalidIpList:
	case InvalidHash:
	case InvalidCert:
	case InvalidSslHash:
		lblError->setText(tr("Invalid hash: %1; invalid cert: %2; invalid iplist: %3; invalid sslhash: %4")
			.arg(_hashErrorCount).arg(_certErrorCount).arg(_ipErrorCount).arg(_hashSslErrorCount));
		break;
	}
}

/*
 * Overrides
 */

/**
 * Called when a Qt timer fires; used for server discovery and
 * auto-hiding the connect dialog.
 */
void ConnectWindow::timerEvent(QTimerEvent* event)
{
	if (event->timerId() == _timerDiscover)
	{
		killTimer(_timerDiscover);
		if (_connected || _state != Scanning) // Not scanning, bail out
			return;
		if (_discoveryInterval < 30000)
			_discoveryInterval += 100;
		_timerDiscover = startTimer(_discoveryInterval);
		// Don't send packet if we're trying to connect
		if (_connection != NULL)
			return;
		// Send discovery
		_packet.reset();
		QByteArray iplist(Network::interfaceAddressesToString().toUtf8());
		QByteArray salt1(SALT_LEN, 0);
		if (_salt2.size() < SALT_LEN)
			_salt2.resize(SALT_LEN);
		for (int i = 0; i < SALT_LEN; ++i)
		{
			salt1[i] = qrand() & 0xff;
			_salt2[i] = qrand() & 0xff;
		}
		_packet.reset();
		_packet.setField(_HASH, genSha1(&_nameBytes, &salt1, &iplist));
		_packet.setField(_SALT1, salt1);
		_packet.setField(_SALT2, _salt2);
		_packet.setField(_IPLIST, iplist);
		foreach (QNetworkInterface interface, QNetworkInterface::allInterfaces())
		{
			foreach (QNetworkAddressEntry entry, interface.addressEntries())
			{
				if (!entry.broadcast().isNull() && entry.ip() != QHostAddress::LocalHost && entry.ip() != QHostAddress::LocalHostIPv6)
				{
					qDebug() << "Broadcasting to " << entry.broadcast().toString();
					if (!_packet.writeMessage(&_discoverySocket, entry.broadcast(), SERVICE_DISCOVERY_PORT))
						qDebug("FAILED");
				}
			}
		}
		qDebug("Broadcasting to 255.255.255.255");
		if (!_packet.writeMessage(&_discoverySocket, QHostAddress::Broadcast, SERVICE_DISCOVERY_PORT))
			qDebug("FAILED");
		// End send discovery
	}
	else if(event->timerId() == _timerHide)
	{
		killTimer(_timerHide);
		_timerHide = 0;
		this->hide();
        lblCheckmark->hide();
	}
	else
		// Unknown/Old timer id, kill it
		killTimer(event->timerId());
}

/**
 * Close Event e and hide window.
 * @param e
 */
void ConnectWindow::closeEvent(QCloseEvent *e)
{
	e->ignore();
	this->hide();
}

/**
 * Gives the keyboard input focus to the input line.
 * @param event
 */
void ConnectWindow::showEvent(QShowEvent* event)
{
	txtName->setFocus();
}

/*
 * Slots
 */

/**
 * Handle click on Connect/Disconnect button.
 * If already connected --> Stop/disconnect.
 * Else scanning for given sessionId.
 */
void ConnectWindow::onOkClick()
{
	if (_timerHide)
		killTimer(_timerHide);
	_timerHide = 0;
	if (_timerDiscover)
		killTimer(_timerDiscover);
	if (_connected || _state != Idle)
	{
		// Stop or disconnect
		_timerDiscover = 0;
		emit disconnect();
		this->setState(Idle);
	}
	else
	{
		//  Connect (scan for session)
		_discoveryInterval = 800;
		_nameBytes = txtName->text().toUtf8();
		_timerDiscover = startTimer(_discoveryInterval);
		_hashErrorCount = _hashSslErrorCount = _certErrorCount = _ipErrorCount = 0;
		this->setState(Scanning);
	}
}

/**
 * Handle click on Cancel/Hide Button.
 * Just hide the window.
 */
void ConnectWindow::onCancelClick()
{
	this->hide();
}

/**
 * Handle incoming service discovery packets.
 */
void ConnectWindow::onUdpReadyRead()
{
	char data[UDPBUFSIZ];
	QHostAddress addr;
	quint16 port;
	while (_discoverySocket.hasPendingDatagrams())
	{
		const qint64 size = _discoverySocket.readDatagram(data, UDPBUFSIZ, &addr, &port);
		if (size <= 0 || _connection != NULL)
			continue;

		_packet.reset();
		if (!_packet.readMessage(data, (quint32)size))
			continue;
		// Valid packet, process it:
		const QByteArray hash(_packet.getFieldBytes(_HASH));
		const QByteArray iplist(_packet.getFieldBytes(_IPLIST));
		const QByteArray port(_packet.getFieldBytes(_PORT));
		const QByteArray cert(_packet.getFieldBytes(_CERT));
		// Check if the source IP of the packet matches any of the addresses given in the IP list
		if (!Network::isAddressInList(QString::fromUtf8(iplist), addr.toString()))
		{
			++_ipErrorCount;
			this->setState(InvalidIpList);
			this->setState(Scanning);
			continue;
		}
		// If so, check if the submitted hash seems valid
		if (genSha1(&_nameBytes, &_salt2, &iplist, &port, &cert) != hash)
		{
			// did not match local session name, or other data was spoofed
			++_hashErrorCount;
			this->setState(InvalidHash);
			this->setState(Scanning);
			continue;
		}
		// Otherwise it's a valid reply, try to connect
		_connection = new ServerConnection(addr.toString(), (quint16)QString::fromUtf8(port).toInt(), _nameBytes, cert);
		connect(_connection, SIGNAL(stateChange(ConnectWindow::ConnectionState)), this, SLOT(onConnectionStateChange(ConnectWindow::ConnectionState)));
		connect(_connection, SIGNAL(destroyed(QObject*)), this, SLOT(onConnectionClosed(QObject*)));
	}
}

/**
 * Handle connection state changes and update member variables describing state.
 * @param state
 */
void ConnectWindow::onConnectionStateChange(ConnectWindow::ConnectionState state)
{
	bool reset = (_state == Scanning);
	if (state == InvalidSslHash)
		++_hashSslErrorCount;
	this->setState(state);
	if (reset)
		_state = Scanning;
	if (state == Connected)
	{
		QObject::disconnect(_connection, SIGNAL(stateChange(ConnectWindow::ConnectionState)), this, SLOT(onConnectionStateChange(ConnectWindow::ConnectionState)));
		QObject::disconnect(_connection, SIGNAL(destroyed(QObject*)), this, SLOT(onConnectionClosed(QObject*)));
		emit connected(_connection);
		_connection = NULL;
		_timerHide = startTimer(2000);
	}
}

/**
 * Set _connection = NULL.
 * @param connection
 */
void ConnectWindow::onConnectionClosed(QObject* connection)
{
	_connection = NULL;
}