summaryrefslogtreecommitdiffstats
path: root/src/server/net/client.cpp
blob: 12b28a0d0cc15213002691df56ab19dd057ccb71 (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
/*
 * client.cpp
 *
 *  Created on: 18.01.2013
 *      Author: sr
 */

#include "client.h"
#include "../util/global.h"
#include "../../shared/settings.h"
#include "../../shared/util.h"
#include <QSslSocket>
#include <QHostAddress>
#include <QPixmap>
#include <cassert>

#define CHALLENGE_LEN 20

ClientId Client::_clientIdCounter = 0;

Client::Client(QSslSocket* socket) :
	_socket(socket), _authed(0), _timerDelete(0), _desiredProjectionSource(0), _isProjectionSource(false),
	_currentProjectionSource(0), _vncPort(0), _activeVncClient(false), _isTutor(false)
{
	assert(socket != NULL);
	_id = ++_clientIdCounter;
	_pingTimeout = QDateTime::currentMSecsSinceEpoch() + PING_TIMEOUT_MS;
	_ip = _socket->peerAddress().toString();
	qDebug("*** Client %s created.", qPrintable(_ip));
	// Connect important signals
	connect(_socket, SIGNAL(disconnected()), this, SLOT(onClosed()));
	connect(_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onError(QAbstractSocket::SocketError)));
	connect(_socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(onSslErrors(const QList<QSslError> &)));
	connect(_socket, SIGNAL(readyRead()), this, SLOT(onDataArrival()));
	// Send challenge
	_challenge.resize(CHALLENGE_LEN);
	for (int i = 0; i < CHALLENGE_LEN; ++i)
		_challenge[i] = qrand() & 0xff;
	_toClient.reset();
	_toClient.setField(_ID, _CHALLENGE);
	_toClient.setField(_CHALLENGE, _challenge);
	_toClient.writeMessage(_socket);
	// give client 3 seconds to complete handshake
	_timerIdAuthTimeout = startTimer(3000);
}

Client::~Client()
{
	if (_socket != NULL)
	{
		qCritical("**** SOCKET DELETE IN DESTRUCTOR");
		_socket->deleteLater();
	}
	qDebug("*** Client %s destroyed.", qPrintable(_ip));
}

void Client::timerEvent(QTimerEvent* event)
{
	if (event->timerId() == _timerIdAuthTimeout)
	{
		// Client did not send login request within 3 seconds
		killTimer(_timerIdAuthTimeout);
		_timerIdAuthTimeout = 0;
		this->disconnect();
	}
	else if (event->timerId() == _timerDelete)
	{
		if (_socket == NULL || _socket->state() == QAbstractSocket::UnconnectedState)
		{
			if (_socket != NULL)
				_socket->deleteLater();
			_socket = NULL;
			killTimer(_timerDelete);
			this->deleteLater();
			return;
		}
		_socket->abort();
		qDebug("A socket is still pending...");
	}
	else
		killTimer(event->timerId());
}

void Client::sendMessage(NetworkMessage& message)
{
	if (_socket == NULL || _socket->state() != QAbstractSocket::ConnectedState)
		return;
	message.writeMessage(_socket);
	if (!message.writeComplete())
	{
		qCritical() << "SendMessage to client " << _name << "@" << _ip << " failed!";
	}
}

void Client::requestThumb(const int width, const int height)
{
	if (_socket == NULL || _socket->state() != QAbstractSocket::ConnectedState)
	{
		qDebug("requestThumb called in bad state");
		return;
	}
	_toClient.reset();
	_toClient.setField(_ID, _THUMB);
	_toClient.setField(_X, QString::number(width));
	_toClient.setField(_Y, QString::number(height));
	_toClient.writeMessage(_socket);
}

void Client::onDataArrival()
{
	_pingTimeout = QDateTime::currentMSecsSinceEpoch() + PING_TIMEOUT_MS;
	//
	if (_socket == NULL || _socket->state() != QAbstractSocket::ConnectedState)
	{
		qDebug("dataArrival called in bad state");
		return;
	}

	//qDebug() << _socket->bytesAvailable() << " bytes to read";
	bool ret;
	while (_socket->bytesAvailable())
	{
		ret = _fromClient.readMessage(_socket); // let the message read data from socket
		if (!ret)   // error parsing msg, disconnect client!
		{
			this->disconnect();
			return;
		}
		if (_fromClient.readComplete())   // message is complete
		{
			this->handleMsg();
			_fromClient.reset();
			if (_socket == NULL)
				return;
		}
	}
}

void Client::onSslErrors(const QList<QSslError> & errors)
{
	this->disconnect();
}

void Client::onClosed()
{
	this->disconnect();
}

void Client::onError(QAbstractSocket::SocketError errcode)
{
	this->disconnect();
}

void Client::handleMsg()
{
	const QString &id = _fromClient.getFieldString(_ID);
	if (id.isEmpty())
	{
		qDebug("Received message with empty ID field. ignored.");
		return;
	}
	//qDebug() << "Received message " << id;

	if (_authed == 2)
	{
		// Following messages are only valid of the client is already authenticated
		if (id == _THUMB)
		{
			QPixmap pixmap;
			if (!pixmap.loadFromData(_fromClient.getFieldBytes("IMG")))
			{
				qDebug("Could not decode thumbnail image from client.");
				return;
			}
			emit thumbUpdated(this, pixmap);
		}
		else if (id == _VNCSERVER)
		{
			// Client tells about startup of vnc server
			const int port = _fromClient.getFieldString("PORT").toInt();
			if (port <= 0)
			{
				if (_vncPort <= 0)
				{
					qDebug() << "Starting VNC server on client" << _name << " (" << _ip << ") failed.";
					// TODO: Show message on manager
				}
			}
			else
			{
				_vncRoPass = _fromClient.getFieldString("ROPASS");
				_vncRwPass = _fromClient.getFieldString("RWPASS");
			}
			_vncPort = port;
			emit vncServerStateChange(this);
		}
		else if (id == _VNCCLIENT)
		{
			// Client tells us that it started or stopped displaying a remote screen via VNC
			_activeVncClient = (_fromClient.getFieldString("ENABLED").toInt() != 0);
			const ClientId other = (ClientId)_fromClient.getFieldString("CLIENTID").toInt();

			if (!_activeVncClient && other == 0)
				_desiredProjectionSource = 0;

			emit vncClientStateChange(this);

			if (!_activeVncClient)
				_currentProjectionSource = 0;
			else
				_currentProjectionSource = other;
		}
		return;
	}

	// Not authed yet, only care about login requests
	if (_authed == 1)
	{
		if (id == _LOGIN)
		{
			killTimer(_timerIdAuthTimeout);
			_timerIdAuthTimeout = 0;
			ClientLogin request;
			request.accept = true;
			request.host = _fromClient.getFieldString("HOST");
			request.name = _fromClient.getFieldString("NAME");
			request.ip = _socket->peerAddress().toString();
			qDebug() << "Login request by " << request.name;
			// emit event, see if request is accepted
			emit authenticating(this, &request);
			if (!request.accept)
			{
				qDebug("Request denied.");
				this->disconnect(); // Nope
				return;
			}
			// Accepted
			_authed = 2;
			qDebug("valid, step <- 2");
			_name = request.name;
			_host = request.host;
			_toClient.reset();
			_toClient.setField(_ID, _LOGIN);
			_toClient.writeMessage(_socket);
			emit authenticated(this);
		}
		return;
	}

	// Did not pass challenge yet
	if (_authed == 0)
	{
		// Waiting for challenge reply by client
		if (id == _CHALLENGE)
		{
			QByteArray hash(_fromClient.getFieldBytes(_HASH));
			QByteArray challenge(_fromClient.getFieldBytes(_CHALLENGE));
			if (genSha1(&Global::sessionNameArray(), &_challenge) != hash)
			{	// Challenge reply is invalid, drop client
				_toClient.buildErrorMessage("Challenge reply invalid.");
				_toClient.writeMessage(_socket);
				this->disconnect();
				return;
			}
			// Now answer to challenge by client
			_toClient.reset();
			_toClient.setField(_ID, _CHALLENGE);
			_toClient.setField(_HASH, genSha1(&Global::sessionNameArray(), &challenge));
			_toClient.writeMessage(_socket);
			_authed = 1;
			qDebug("client's challenge reply was valid, step <- 1");
		}
		return;
	}

}

void Client::startVncServer()
{
	_vncPort = 0;
	_toClient.reset();
	_toClient.setField(_ID, _VNCSERVER);
	_toClient.setField(_ENABLE, __TRUE);
	sendMessage(_toClient);
}

void Client::stopVncServer()
{
	_toClient.reset();
	_toClient.setField(_ID, _VNCSERVER);
	_toClient.setField(_ENABLE, __FALSE);
	sendMessage(_toClient);
}

void Client::stopVncClient()
{
	_toClient.reset();
	_toClient.setField(_ID, _VNCCLIENT);
	sendMessage(_toClient);
}

void Client::setTutor(bool enable)
{
	_toClient.reset();
	_toClient.setField(_ID, _TUTOR);
	_toClient.setField(_ENABLE, _BOOL(enable));
	sendMessage(_toClient);
	_isTutor = enable;
}

void Client::disconnect()
{
	if (_timerDelete == 0)
	{
		emit disconnected();
		_timerDelete = startTimer(500);
		qDebug("*** Client %s disconnected.", qPrintable(_ip));
		_socket->blockSignals(true);
		_socket->abort();
	}
}