-
Notifications
You must be signed in to change notification settings - Fork 1
/
connection.cpp
404 lines (328 loc) · 11.4 KB
/
connection.cpp
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
#include "connection.h"
#include "common.h"
#include "connectionhandler.h"
#include <QSslSocket>
#include <QSslConfiguration>
#include <QSettings>
#include <QJsonDocument>
#include <QJsonObject>
#include <QPoint>
#include <QDir>
Connection::Connection(ConnectionHandler *parent) :
m_handler(parent)
{
m_basePath = QDir::homePath() + '/';
m_socket = new QSslSocket(this);
QSslConfiguration config = m_socket->sslConfiguration();
QSettings settings;
QSslCertificate ourCert = QSslCertificate(settings.value("privcert").toByteArray());
QSslKey ourKey = QSslKey(settings.value("privkey").toByteArray(), QSsl::Ec);
config.setCaCertificates(parent->trustedCertificates());
config.setLocalCertificate(ourCert);
config.setPrivateKey(ourKey);
m_socket->setSslConfiguration(config);
m_socket->ignoreSslErrors();
connect(m_socket, SIGNAL(sslErrors(QList<QSslError>)), m_socket, SLOT(ignoreSslErrors()));
connect(m_socket, &QSslSocket::disconnected, this, &Connection::disconnected);
connect(m_socket, &QSslSocket::disconnected, this, &Connection::onDisconnected);
connect(m_socket, &QSslSocket::encrypted, this, &Connection::onEncrypted);
#if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0))
connect(m_socket, &QAbstractSocket::errorOccurred, this, &Connection::onError);
#else
connect(m_socket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, &Connection::onError);
#endif
/// Avoid connections hanging for more than a second
m_timeoutTimer = new QTimer(this);
m_timeoutTimer->setInterval(1000); // shouldn't take more than a second to connect..
m_timeoutTimer->setSingleShot(true);
// abort() nukes the buffers and doesn't wait
connect(m_timeoutTimer.data(), &QTimer::timeout, m_socket, [this]() { m_socket->abort(); });
m_timeoutTimer->start();
}
Connection::~Connection()
{
if (m_socket->state() != QAbstractSocket::UnconnectedState) {
m_socket->abort();
}
}
void Connection::initiateMouseControl(const Host &host)
{
qDebug() << "initiating mouse control of" << host.address;
m_host = host;
m_type = SendMouseControl;
m_socket->connectToHostEncrypted(host.address.toString(), TRANSFER_PORT);
}
void Connection::download(const Host &host, const QString &remotePath, const QString &localPath)
{
qDebug() << "downloading" << remotePath << "from" << host.address;
m_host = host;
m_type = ReceiveFile;
m_remotePath = remotePath;
m_localPath = localPath;
m_socket->connectToHostEncrypted(host.address.toString(), TRANSFER_PORT);
}
void Connection::upload(const Host &host, const QString &remotePath, const QString &localPath)
{
qDebug() << "uploading" << remotePath << "to" << host.address;
m_host = host;
m_type = ReceiveFile;
m_remotePath = remotePath;
m_localPath = localPath;
m_socket->connectToHostEncrypted(host.address.toString(), TRANSFER_PORT);
}
void Connection::list(const Host &host, const QString &remotePath)
{
qDebug() << "listing" << remotePath << "on" << host.address;
m_host = host;
m_type = ReceiveListing;
m_remotePath = remotePath;
m_socket->connectToHostEncrypted(host.address.toString(), TRANSFER_PORT);
}
bool Connection::isConnected() const
{
return m_socket->isEncrypted() && m_host.trusted;
}
void Connection::onEncrypted()
{
m_host.certificate = m_socket->peerCertificate();
m_timeoutTimer->stop();
if (!m_handler->isTrusted(m_host)) {
qWarning() << "Connected to host with untrusted certificate";
qDebug().noquote() << m_socket->peerCertificate().toText();
m_socket->disconnectFromHost();
return;
}
qDebug() << "Encryption complete";
m_host.address = m_socket->peerAddress();
emit connectionEstablished(this);
if (m_type == Incoming) {
connect(m_socket, &QSslSocket::readyRead, this, &Connection::onReadyRead);
qDebug() << "Incoming connection, waiting for request";
return;
}
QJsonObject request;
switch (m_type) {
case ReceiveListing:
request["command"] = "list";
request["path"] = m_remotePath;
connect(m_socket, &QSslSocket::readyRead, this, &Connection::onReadyRead);
break;
case SendFile:
request["command"] = "upload";
request["path"] = m_remotePath;
connect(m_socket, &QSslSocket::bytesWritten, this, &Connection::onBytesWritten);
break;
case ReceiveFile:
request["command"] = "download";
request["path"] = m_remotePath;
connect(m_socket, &QSslSocket::readyRead, this, &Connection::onReadyRead);
break;
case SendMouseControl:
case Incoming:
return;
default:
qDebug() << "Unexpected type" << m_type;
return;
}
qDebug() << "sending" << request;
m_socket->write(QJsonDocument(request).toJson(QJsonDocument::Compact) + "\n");
}
void Connection::onError()
{
qWarning() << "server error" << m_socket->errorString();
m_socket->disconnectFromHost();
}
void Connection::onDisconnected()
{
qDebug() << "Disconnected from" << m_host.address << "type" << m_type;
if (m_file) {
m_file->close();
m_file->deleteLater();
m_file = nullptr;
}
deleteLater();
}
void Connection::sendMouseClickEvent(const QPoint &position, const MouseButton button)
{
QJsonObject request;
request["command"] = "mouseclick";
request["x"] = position.x();
request["y"] = position.y();
request["mousebutton"] = int(button);
m_socket->write(QJsonDocument(request).toJson(QJsonDocument::Compact) + "\n");
}
void Connection::sendMouseMoveEvent(const QPoint &position)
{
QJsonObject request;
request["command"] = "mousemove";
request["x"] = position.x();
request["y"] = position.y();
m_socket->write(QJsonDocument(request).toJson(QJsonDocument::Compact) + "\n");
}
void Connection::handleMouseCommand(const QString &command, const QJsonObject &data)
{
const QPoint position(data["x"].toInt(-1), data["y"].toInt(-1));
if (position.x() < 0 || position.y() < 0) {
qWarning() << "invalid position";
return;
}
if (command == "mousemove") {
emit mouseMoveRequested(position);
return;
}
if (command != "mouseclick") {
qWarning() << "Unhandled mouse command" << command;
}
const int button = data["mousebutton"].toInt(-1);
switch(button) {
case LeftButton:
case RightButton:
case MiddleButton:
case ScrollUp:
case ScrollDown:
emit mouseClickRequested(position, MouseButton(button));
break;
default:
qWarning() << "Unhandled mouse button" << button;
break;
}
return;
}
void Connection::onReadyRead()
{
if (!m_handler->isTrusted(m_host)) {
qWarning() << "Should not happen, but we got ready read for untrusted";
qDebug().noquote() << m_socket->peerCertificate().toText();
m_socket->disconnectFromHost();
return;
}
if (m_type == Incoming) {
if (!m_socket->canReadLine()) {
return;
}
QJsonParseError parseError;
QJsonObject request = QJsonDocument::fromJson(m_socket->readLine(), &parseError).object();
if (parseError.error != QJsonParseError::NoError) {
qWarning() << "Failed to parse json" << parseError.errorString();
m_socket->disconnectFromHost();
return;
}
const QString command = request["command"].toString();
if (command.startsWith("mouse")) {
handleMouseCommand(command, request);
return;
}
handleCommand(command, request["path"].toString());
return;
}
if (m_type == ReceiveListing) {
qDebug() << "Listing, received data";
QStringList entries;
while (m_socket->canReadLine()) {
QString entry = QString::fromUtf8(m_socket->readLine()).trimmed();
if (!entry.isEmpty()) {
entries.append(entry);
}
}
if (!entries.isEmpty()) {
emit listingReceived(m_remotePath, entries);
}
return;
}
if (m_type != ReceiveFile){
qWarning() << "Unexpected readyread for connection type" << m_type;
m_socket->disconnectFromHost();
return;
}
if (!m_file) {
m_file = new QFile(m_localPath, this);
if (m_file->exists()) {
qWarning() << "Refusing to overwrite local file" << m_localPath;
m_socket->disconnectFromHost();
return;
}
if (!m_file->open(QIODevice::WriteOnly)) {
qWarning() << "Failed to open" << m_localPath << "for writing" << m_file->errorString();
m_socket->disconnectFromHost();
return;
}
qDebug() << "Opened" << m_localPath << "for writing";
}
const qint64 bytesToRead = m_socket->bytesAvailable();
m_file->write(m_socket->readAll());
emit bytesTransferred(bytesToRead);
}
void Connection::onBytesWritten(qint64 bytes)
{
emit bytesTransferred(bytes);
if (m_socket->bytesToWrite() > 0) {
qDebug() << "Still" << m_socket->bytesToWrite() << "bytes to write";
return;
}
if (m_type == SendMouseControl) {
return;
}
if (m_type == SendListing) {
qDebug() << "Finished sending list";
m_socket->disconnectFromHost();
return;
}
if (m_type != SendFile) {
qWarning() << "Bytes written, but we're not sending a file!";
m_socket->disconnectFromHost();
return;
}
if (!m_file) {
m_file = new QFile(m_localPath, this);
if (!m_file->exists()) {
qWarning() << "Local file does not exist" << m_localPath;
m_socket->disconnectFromHost();
return;
}
if (!m_file->open(QIODevice::ReadOnly)) {
qWarning() << "Failed to open" << m_localPath << "for reading" << m_file->errorString();
m_socket->disconnectFromHost();
return;
}
qDebug() << "Opened" << m_localPath << "for reading";
}
if (m_file->atEnd()) {
qDebug() << "finished sending file";
m_socket->disconnectFromHost();
return;
}
m_socket->write(m_file->read(TRANSFER_BYTE_SIZE));
}
void Connection::handleCommand(const QString &command, QString path)
{
path = m_basePath + QDir::cleanPath(path);
m_localPath = path;
qDebug() << "Got command" << command << "for" << path;
if (command == "list") {
QString retData;
const QDir dir(path);
const QFileInfoList files = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDot, QDir::Name | QDir::DirsFirst | QDir::LocaleAware);
for (const QFileInfo &fi : files) {
retData += QString::number(fi.size()) + ':' + fi.fileName();
if (fi.isDir()) {
retData += '/';
}
retData += '\n';
}
m_socket->write(retData.toUtf8());
m_type = SendListing;
connect(m_socket, &QSslSocket::bytesWritten, this, &Connection::onBytesWritten);
return;
}
if (command == "upload") {
m_type = ReceiveFile;
} else if (command == "download") {
m_type = SendFile;
connect(m_socket, &QSslSocket::bytesWritten, this, &Connection::onBytesWritten);
onBytesWritten(0);
} else {
qWarning() << "Unknown command" << command;
m_socket->disconnectFromHost();
return;
}
}