-
Notifications
You must be signed in to change notification settings - Fork 26
/
tst_ssh.cpp
1111 lines (1020 loc) · 42.1 KB
/
tst_ssh.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************
**
** Copyright (C) 2018 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include <qssh/sftpchannel.h>
#include <qssh/sshconnection.h>
#include <qssh/sshdirecttcpiptunnel.h>
#include <qssh/sshforwardedtcpiptunnel.h>
#include <qssh/sshpseudoterminal.h>
#include <qssh/sshremoteprocessrunner.h>
#include <qssh/sshtcpipforwardserver.h>
#include <qssh/sshx11displayinfo_p.h>
#include <qssh/sshx11inforetriever_p.h>
#include <QDateTime>
#include <QDir>
#include <QEventLoop>
#include <QStringList>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTemporaryDir>
#include <QTimer>
#include <QtTest>
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
#include <QRandomGenerator>
#endif
#include <cstdlib>
using namespace QSsh;
static QString getHostFromEnvironment()
{
return QString::fromLocal8Bit(qgetenv("QTC_SSH_TEST_HOST"));
}
enum class TestType { Normal, Tunnel };
static const char *portVar(TestType testType)
{
return testType == TestType::Normal ? "QTC_SSH_TEST_PORT" : "QTC_SSH_TEST_PORT_TUNNEL";
}
static const char *userVar(TestType testType)
{
return testType == TestType::Normal ? "QTC_SSH_TEST_USER" : "QTC_SSH_TEST_USER_TUNNEL";
}
static const char *pwdVar(TestType testType)
{
return testType == TestType::Normal ? "QTC_SSH_TEST_PASSWORD" : "QTC_SSH_TEST_PASSWORD_TUNNEL";
}
static const char *keyFileVar(TestType testType)
{
return testType == TestType::Normal ? "QTC_SSH_TEST_KEYFILE" : "QTC_SSH_TEST_KEYFILE_TUNNEL";
}
static bool canUseFallbackValue(TestType testType)
{
return testType == TestType::Tunnel && getHostFromEnvironment() == QLatin1String("localhost");
}
static quint16 getPortFromEnvironment(TestType testType)
{
const int port = qEnvironmentVariableIntValue(portVar(testType));
if (port != 0)
return port;
if (canUseFallbackValue(testType))
return getPortFromEnvironment(TestType::Normal);
return 22;
}
static QString getUserFromEnvironment(TestType testType)
{
const QString user = QString::fromLocal8Bit(qgetenv(userVar(testType)));
if (user.isEmpty() && canUseFallbackValue(testType))
return getUserFromEnvironment(TestType::Normal);
return user;
}
static QString getPasswordFromEnvironment(TestType testType)
{
const QString pwd = QString::fromLocal8Bit(qgetenv(pwdVar(testType)));
if (pwd.isEmpty() && canUseFallbackValue(testType))
return getPasswordFromEnvironment(TestType::Normal);
return pwd;
}
static QString getKeyFileFromEnvironment(TestType testType)
{
const QString keyFile = QString::fromLocal8Bit(qgetenv(keyFileVar(testType)));
if (keyFile.isEmpty() && canUseFallbackValue(testType))
return getKeyFileFromEnvironment(TestType::Normal);
return keyFile;
}
static SshConnectionParameters getParameters(TestType testType)
{
SshConnectionParameters params;
params.setHost(testType == TestType::Tunnel ? QLatin1String("localhost")
: getHostFromEnvironment());
params.setPort(getPortFromEnvironment(testType));
params.setUserName(getUserFromEnvironment(testType));
params.setPassword(getPasswordFromEnvironment(testType));
params.timeout = 10;
params.privateKeyFile = getKeyFileFromEnvironment(testType);
params.authenticationType = !params.password().isEmpty()
? SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods
: SshConnectionParameters::AuthenticationTypePublicKey;
return params;
}
#define CHECK_PARAMS(params, testType) \
do { \
if (params.host().isEmpty()) { \
Q_ASSERT(testType == TestType::Normal); \
QSKIP("No hostname provided. Set QTC_SSH_TEST_HOST."); \
} \
if (params.userName().isEmpty()) \
QSKIP(qPrintable(QStringLiteral("No user name provided. Set %1.") \
.arg(QString::fromLatin1(userVar(testType))))); \
if (params.password().isEmpty() && params.privateKeyFile.isEmpty()) \
QSKIP(qPrintable(QStringLiteral("No authentication data provided. " \
"Set %1 or %2.").arg(QString::fromLatin1(pwdVar(testType)), QString::fromLatin1(keyFileVar(testType))))); \
} while (false)
class tst_Ssh : public QObject
{
Q_OBJECT
private slots:
void directTunnel();
void errorHandling_data();
void errorHandling();
void forwardTunnel();
void pristineConnectionObject();
void remoteProcess_data();
void remoteProcess();
void remoteProcessChannels();
void remoteProcessInput();
void sftp();
void x11InfoRetriever_data();
void x11InfoRetriever();
private:
bool waitForConnection(SshConnection &connection);
};
void tst_Ssh::directTunnel()
{
// Establish SSH connection
const SshConnectionParameters params = getParameters(TestType::Tunnel);
CHECK_PARAMS(params, TestType::Tunnel);
SshConnection connection(params);
QVERIFY(waitForConnection(connection));
// Set up the tunnel
QTcpServer targetServer;
QTcpSocket *targetSocket = nullptr;
bool tunnelInitialized = false;
QVERIFY2(targetServer.listen(QHostAddress::LocalHost), qPrintable(targetServer.errorString()));
const quint16 targetPort = targetServer.serverPort();
const SshDirectTcpIpTunnel::Ptr tunnel
= connection.createDirectTunnel(QStringLiteral("localhost"), 1024, QStringLiteral("localhost"), targetPort);
QEventLoop loop;
const auto connectionHandler = [&targetServer, &targetSocket, &loop, &tunnelInitialized] {
targetSocket = targetServer.nextPendingConnection();
targetServer.close();
if (tunnelInitialized)
loop.quit();
};
connect(&targetServer, &QTcpServer::newConnection, connectionHandler);
connect(tunnel.data(), &SshDirectTcpIpTunnel::error, &loop, &QEventLoop::quit);
connect(tunnel.data(), &SshDirectTcpIpTunnel::initialized,
[&tunnelInitialized, &targetSocket, &loop] {
tunnelInitialized = true;
if (targetSocket)
loop.quit();
});
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
timer.setSingleShot(true);
timer.setInterval((params.timeout + 5) * 1000);
timer.start();
QVERIFY(!tunnel->isOpen());
tunnel->initialize();
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(tunnel->isOpen());
QVERIFY(targetSocket);
QVERIFY(tunnelInitialized);
// Send data through the tunnel and check that it is received by the "remote" side
static const QByteArray testData("Urgsblubb?");
QByteArray clientDataReceivedByServer;
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
connect(targetSocket, &QAbstractSocket::errorOccurred, &loop, &QEventLoop::quit);
#else
connect(targetSocket,
static_cast<void (QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error),
&loop, &QEventLoop::quit);
#endif
const auto socketDataHandler = [targetSocket, &clientDataReceivedByServer, &loop] {
clientDataReceivedByServer += targetSocket->readAll();
if (clientDataReceivedByServer == testData)
loop.quit();
};
connect(targetSocket, &QIODevice::readyRead, socketDataHandler);
timer.start();
tunnel->write(testData);
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(tunnel->isOpen());
QVERIFY2(targetSocket->error() == QAbstractSocket::UnknownSocketError,
qPrintable(targetSocket->errorString()));
QCOMPARE(clientDataReceivedByServer, testData);
// Send data back and check that it is received by the "local" side
QByteArray serverDataReceivedByClient;
connect(tunnel.data(), &QIODevice::readyRead, [tunnel, &serverDataReceivedByClient, &loop] {
serverDataReceivedByClient += tunnel->readAll();
if (serverDataReceivedByClient == testData)
loop.quit();
});
timer.start();
targetSocket->write(clientDataReceivedByServer);
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(tunnel->isOpen());
QVERIFY2(targetSocket->error() == QAbstractSocket::UnknownSocketError,
qPrintable(targetSocket->errorString()));
QCOMPARE(serverDataReceivedByClient, testData);
// Close tunnel by closing the "remote" socket
connect(tunnel.data(), &QIODevice::aboutToClose, &loop, &QEventLoop::quit);
timer.start();
targetSocket->close();
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(!tunnel->isOpen());
QVERIFY2(targetSocket->error() == QAbstractSocket::UnknownSocketError,
qPrintable(targetSocket->errorString()));
}
using ErrorList = QList<SshError>;
void tst_Ssh::errorHandling_data()
{
QTest::addColumn<QString>("host");
QTest::addColumn<quint16>("port");
QTest::addColumn<SshConnectionParameters::AuthenticationType>("authType");
QTest::addColumn<QString>("user");
QTest::addColumn<QString>("password");
QTest::addColumn<QString>("keyFile");
QTest::addColumn<ErrorList>("expectedErrors");
QTest::newRow("no host")
<< QStringLiteral("hgdfxgfhgxfhxgfchxgcf") << quint16(12345)
<< SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods
<< QString() << QString() << QString() << ErrorList{SshSocketError, SshTimeoutError};
const QString theHost = getHostFromEnvironment();
if (theHost.isEmpty())
return;
const quint16 thePort = getPortFromEnvironment(TestType::Normal);
QTest::newRow("no user")
<< theHost << thePort
<< SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods
<< QStringLiteral("dumdidumpuffpuff") << QStringLiteral("whatever") << QString()
<< ErrorList{SshAuthenticationError};
QTest::newRow("wrong password")
<< theHost << thePort
<< SshConnectionParameters::AuthenticationTypeTryAllPasswordBasedMethods
<< QStringLiteral("root") << QStringLiteral("thiscantpossiblybeapasswordcanit") << QString()
<< ErrorList{SshAuthenticationError};
QTest::newRow("non-existing key file")
<< theHost << thePort
<< SshConnectionParameters::AuthenticationTypePublicKey
<< QStringLiteral("root") << QString()
<< QStringLiteral("somefilenamethatwedontexpecttocontainavalidkey")
<< ErrorList{SshKeyFileError};
// TODO: Valid key file not known to the server
}
void tst_Ssh::errorHandling()
{
QFETCH(QString, host);
QFETCH(quint16, port);
QFETCH(SshConnectionParameters::AuthenticationType, authType);
QFETCH(QString, user);
QFETCH(QString, password);
QFETCH(QString, keyFile);
QFETCH(ErrorList, expectedErrors);
SshConnectionParameters params;
params.setHost(host);
params.setPort(port);
params.setUserName(user);
params.setPassword(password);
params.timeout = 10;
params.authenticationType = authType;
params.privateKeyFile = keyFile;
SshConnection connection(params);
QEventLoop loop;
bool disconnected = false;
QString dataReceived;
QObject::connect(&connection, &SshConnection::connected, &loop, &QEventLoop::quit);
QObject::connect(&connection, &SshConnection::error, &loop, &QEventLoop::quit);
QObject::connect(&connection, &SshConnection::disconnected,
[&disconnected] { disconnected = true; });
QObject::connect(&connection, &SshConnection::dataAvailable,
[&dataReceived](const QString &data) { dataReceived = data; });
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
timer.setSingleShot(true);
timer.start((params.timeout + 5) * 1000);
connection.connectToHost();
loop.exec();
QVERIFY(timer.isActive());
QCOMPARE(connection.state(), SshConnection::Unconnected);
QVERIFY2(expectedErrors.contains(connection.errorState()),
qPrintable(connection.errorString()));
QVERIFY(!disconnected);
QVERIFY2(dataReceived.isEmpty(), qPrintable(dataReceived));
}
void tst_Ssh::forwardTunnel()
{
// Set up SSH connection
const SshConnectionParameters params = getParameters(TestType::Tunnel);
CHECK_PARAMS(params, TestType::Tunnel);
SshConnection connection(params);
QVERIFY(waitForConnection(connection));
// Find a free port on the "remote" side and listen on it
quint16 targetPort;
{
QTcpServer server;
QVERIFY2(server.listen(QHostAddress::LocalHost), qPrintable(server.errorString()));
targetPort = server.serverPort();
}
SshTcpIpForwardServer::Ptr server = connection.createForwardServer(QLatin1String("localhost"),
targetPort);
QEventLoop loop;
QTimer timer;
connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
connect(server.data(), &SshTcpIpForwardServer::stateChanged, &loop, &QEventLoop::quit);
connect(server.data(), &SshTcpIpForwardServer::error, &loop, &QEventLoop::quit);
timer.setSingleShot(true);
timer.setInterval((params.timeout + 5) * 1000);
timer.start();
QCOMPARE(server->state(), SshTcpIpForwardServer::Inactive);
server->initialize();
QCOMPARE(server->state(), SshTcpIpForwardServer::Initializing);
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(server->state() == SshTcpIpForwardServer::Listening);
// Establish a tunnel
connect(server.data(), &QSsh::SshTcpIpForwardServer::newConnection, &loop, &QEventLoop::quit);
QTcpSocket targetSocket;
targetSocket.connectToHost(QStringLiteral("localhost"), targetPort);
timer.start();
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
const SshForwardedTcpIpTunnel::Ptr tunnel = server->nextPendingConnection();
QVERIFY(!tunnel.isNull());
QVERIFY(tunnel->isOpen());
// Send data through the socket and check that we receive it through the tunnel
static const QByteArray testData("Urgsblubb?");
QByteArray dataReceivedOnTunnel;
QString tunnelError;
const auto tunnelErrorHandler = [&loop, &tunnelError](const QString &error) {
tunnelError = error;
loop.quit();
};
connect(tunnel.data(), &SshForwardedTcpIpTunnel::error, tunnelErrorHandler);
connect(tunnel.data(), &QIODevice::readyRead, [tunnel, &dataReceivedOnTunnel, &loop] {
dataReceivedOnTunnel += tunnel->readAll();
if (dataReceivedOnTunnel == testData)
loop.quit();
});
timer.start();
targetSocket.write(testData);
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(tunnel->isOpen());
QVERIFY2(tunnelError.isEmpty(), qPrintable(tunnelError));
QCOMPARE(dataReceivedOnTunnel, testData);
// Send data though the tunnel and check that we receive it on the socket
QByteArray dataReceivedOnSocket;
connect(&targetSocket, &QTcpSocket::readyRead, [&targetSocket, &dataReceivedOnSocket, &loop] {
dataReceivedOnSocket += targetSocket.readAll();
if (dataReceivedOnSocket == testData)
loop.quit();
});
timer.start();
tunnel->write(dataReceivedOnTunnel);
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(tunnel->isOpen());
QCOMPARE(dataReceivedOnSocket, testData);
QVERIFY2(tunnelError.isEmpty(), qPrintable(tunnelError));
// Close the tunnel via the socket
connect(tunnel.data(), &SshForwardedTcpIpTunnel::aboutToClose, &loop, &QEventLoop::quit);
timer.start();
targetSocket.close();
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(!tunnel->isOpen());
QVERIFY2(tunnelError.isEmpty(), qPrintable(tunnelError));
QCOMPARE(server->state(), SshTcpIpForwardServer::Listening);
// Close the server
timer.start();
server->close();
QCOMPARE(server->state(), SshTcpIpForwardServer::Closing);
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QCOMPARE(server->state(), SshTcpIpForwardServer::Inactive);
}
void tst_Ssh::pristineConnectionObject()
{
QSsh::SshConnection connection((SshConnectionParameters()));
QCOMPARE(connection.state(), SshConnection::Unconnected);
QVERIFY(connection.createRemoteProcess("").isNull());
QVERIFY(connection.createSftpChannel().isNull());
}
void tst_Ssh::remoteProcess_data()
{
QTest::addColumn<QByteArray>("commandLine");
QTest::addColumn<bool>("useTerminal");
QTest::addColumn<bool>("isBlocking");
QTest::addColumn<bool>("successExpected");
QTest::addColumn<bool>("stdoutExpected");
QTest::addColumn<bool>("stderrExpected");
QTest::newRow("normal command")
<< QByteArray("ls -a /tmp") << false << false << true << true << false;
QTest::newRow("failing command")
<< QByteArray("top -n 1") << false << false << false << false << true;
QTest::newRow("blocking command")
<< QByteArray("/bin/sleep 100") << false << true << false << false << false;
QTest::newRow("terminal command")
<< QByteArray("top -n 1") << true << false << true << true << false;
}
void tst_Ssh::remoteProcess()
{
const SshConnectionParameters params = getParameters(TestType::Normal);
CHECK_PARAMS(params, TestType::Normal);
QFETCH(QByteArray, commandLine);
QFETCH(bool, useTerminal);
QFETCH(bool, isBlocking);
QFETCH(bool, successExpected);
QFETCH(bool, stdoutExpected);
QFETCH(bool, stderrExpected);
QByteArray remoteStdout;
QByteArray remoteStderr;
SshRemoteProcessRunner runner;
QEventLoop loop;
connect(&runner, &SshRemoteProcessRunner::connectionError, &loop, &QEventLoop::quit);
connect(&runner, &SshRemoteProcessRunner::processStarted, &loop, &QEventLoop::quit);
connect(&runner, &SshRemoteProcessRunner::processClosed, &loop, &QEventLoop::quit);
connect(&runner, &SshRemoteProcessRunner::readyReadStandardOutput,
[&remoteStdout, &runner] { remoteStdout += runner.readAllStandardOutput(); });
connect(&runner, &SshRemoteProcessRunner::readyReadStandardError,
[&remoteStderr, &runner] { remoteStderr += runner.readAllStandardError(); });
if (useTerminal)
runner.runInTerminal(commandLine, SshPseudoTerminal(), params);
else
runner.run(commandLine, params);
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
timer.setSingleShot(true);
timer.setInterval((params.timeout + 5) * 1000);
timer.start();
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(runner.isProcessRunning()); // Event loop exit should have been triggered by started().
QVERIFY2(remoteStdout.isEmpty(), remoteStdout.constData());
QVERIFY2(remoteStderr.isEmpty(), remoteStderr.constData());
SshRemoteProcessRunner killer;
if (isBlocking)
killer.run("pkill -f -9 \"" + commandLine + '"', params);
timer.start();
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(!runner.isProcessRunning());
if (isBlocking) {
// Some shells (e.g. mksh) do not report a crash exit.
if (runner.processExitStatus() == SshRemoteProcess::CrashExit)
QCOMPARE(runner.processExitSignal(), SshRemoteProcess::KillSignal);
else
QVERIFY(runner.processExitCode() != 0);
} else {
QCOMPARE(successExpected, runner.processExitCode() == 0);
}
QCOMPARE(stdoutExpected, !remoteStdout.isEmpty());
QCOMPARE(stderrExpected, !remoteStderr.isEmpty());
}
void tst_Ssh::remoteProcessChannels()
{
const SshConnectionParameters params = getParameters(TestType::Normal);
CHECK_PARAMS(params, TestType::Normal);
SshConnection connection(params);
QVERIFY(waitForConnection(connection));
static const QByteArray testString("ChannelTest");
QByteArray remoteStdout;
QByteArray remoteStderr;
QByteArray remoteData;
SshRemoteProcess::Ptr echoProcess
= connection.createRemoteProcess("printf " + testString + " >&2");
echoProcess->setReadChannel(QProcess::StandardError);
QEventLoop loop;
connect(echoProcess.data(), &SshRemoteProcess::closed, &loop, &QEventLoop::quit);
connect(echoProcess.data(), &QIODevice::readyRead,
[&remoteData, echoProcess] { remoteData += echoProcess->readAll(); });
connect(echoProcess.data(), &SshRemoteProcess::readyReadStandardOutput,
[&remoteStdout, echoProcess] { remoteStdout += echoProcess->readAllStandardOutput(); });
connect(echoProcess.data(), &SshRemoteProcess::readyReadStandardError,
[&remoteStderr, echoProcess] { remoteStderr = testString; });
echoProcess->start();
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
timer.setSingleShot(true);
timer.setInterval((params.timeout + 5) * 1000);
timer.start();
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(!echoProcess->isRunning());
QCOMPARE(echoProcess->exitSignal(), SshRemoteProcess::NoSignal);
QCOMPARE(echoProcess->exitCode(), 0);
QVERIFY(remoteStdout.isEmpty());
QCOMPARE(remoteData, testString);
QCOMPARE(remoteData, remoteStderr);
}
void tst_Ssh::remoteProcessInput()
{
const SshConnectionParameters params = getParameters(TestType::Normal);
CHECK_PARAMS(params, TestType::Normal);
SshConnection connection(params);
QVERIFY(waitForConnection(connection));
SshRemoteProcess::Ptr catProcess
= connection.createRemoteProcess(QString::fromLatin1("/bin/cat").toUtf8());
QEventLoop loop;
connect(catProcess.data(), &SshRemoteProcess::started, &loop, &QEventLoop::quit);
connect(catProcess.data(), &SshRemoteProcess::closed, &loop, &QEventLoop::quit);
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
timer.setSingleShot(true);
timer.setInterval((params.timeout + 5) * 1000);
timer.start();
catProcess->start();
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(catProcess->isRunning());
static const QLatin1String testString("x\r\n");
connect(catProcess.data(), &QIODevice::readyRead, &loop, &QEventLoop::quit);
QTextStream stream(catProcess.data());
stream << testString;
stream.flush();
timer.start();
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(catProcess->isRunning());
const QString data = QString::fromUtf8(catProcess->readAll());
QCOMPARE(data, testString);
SshRemoteProcessRunner * const killer = new SshRemoteProcessRunner(this);
killer->run("pkill -9 cat", params);
timer.start();
loop.exec();
QVERIFY(!catProcess->isRunning());
QVERIFY(catProcess->exitCode() != 0
|| catProcess->exitSignal() == SshRemoteProcess::KillSignal);
}
void tst_Ssh::sftp()
{
// Connect to server
const SshConnectionParameters params = getParameters(TestType::Normal);
CHECK_PARAMS(params, TestType::Normal);
SshConnection connection(params);
QVERIFY(waitForConnection(connection));
// Establish SFTP channel
SftpChannel::Ptr sftpChannel = connection.createSftpChannel();
QList<SftpJobId> jobs;
bool invalidFinishedSignal = false;
QString jobError;
QEventLoop loop;
connect(sftpChannel.data(), &SftpChannel::initialized, &loop, &QEventLoop::quit);
connect(sftpChannel.data(), &SftpChannel::channelError, &loop, &QEventLoop::quit);
connect(sftpChannel.data(), &SftpChannel::closed, &loop, &QEventLoop::quit);
connect(sftpChannel.data(), &SftpChannel::finished,
[&loop, &jobs, &invalidFinishedSignal, &jobError](SftpJobId job, const SftpError errorType, const QString &error) {
Q_UNUSED(errorType);
if (!jobs.removeOne(job)) {
invalidFinishedSignal = true;
loop.quit();
return;
}
if (!error.isEmpty()) {
jobError = error;
loop.quit();
return;
}
if (jobs.empty())
loop.quit();
});
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
timer.setSingleShot(true);
timer.setInterval((params.timeout + 5) * 1000);
timer.start();
sftpChannel->initialize();
loop.exec();
QVERIFY(timer.isActive());
timer.stop();
QVERIFY(!invalidFinishedSignal);
QCOMPARE(sftpChannel->state(), SftpChannel::Initialized);
// Create and upload 1000 small files and one big file
QTemporaryDir dirForFilesToUpload;
QTemporaryDir dirForFilesToDownload;
QVERIFY2(dirForFilesToUpload.isValid(), qPrintable(dirForFilesToUpload.errorString()));
QVERIFY2(dirForFilesToDownload.isValid(), qPrintable(dirForFilesToDownload.errorString()));
static const auto getRemoteFilePath = [](const QString &localFileName) {
return QStringLiteral("/tmp/").append(localFileName).append(QLatin1String(".upload"));
};
const auto getDownloadFilePath = [&dirForFilesToDownload](const QString &localFileName) {
return dirForFilesToDownload.path().append(QLatin1Char('/')).append(localFileName);
};
std::srand(QDateTime::currentDateTime().toSecsSinceEpoch());
for (int i = 0; i < 1000; ++i) {
const QString fileName = QLatin1String("sftptestfile") + QString::number(i + 1);
QFile file(dirForFilesToUpload.path() + QLatin1Char('/') + fileName);
QVERIFY2(file.open(QIODevice::WriteOnly), qPrintable(file.errorString()));
int content[1024 / sizeof(int)];
for (size_t j = 0; j < sizeof content / sizeof content[0]; ++j) {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
content[j] = QRandomGenerator::system()->generate();
#else
content[j] = qrand();
#endif
}
file.write(reinterpret_cast<char *>(content), sizeof content);
file.close();
QVERIFY2(file.error() == QFile::NoError, qPrintable(file.errorString()));
const QString remoteFilePath = getRemoteFilePath(fileName);
const SftpJobId uploadJob = sftpChannel->uploadFile(file.fileName(), remoteFilePath,
SftpOverwriteExisting);
QVERIFY(uploadJob != SftpInvalidJob);
jobs << uploadJob;
}
static const QLatin1String bigFileName("sftpbigfile");
QFile bigFile(dirForFilesToUpload.path() + QLatin1Char('/') + bigFileName);
QVERIFY2(bigFile.open(QIODevice::WriteOnly), qPrintable(bigFile.errorString()));
const int bigFileSize = 100 * 1024 * 1024;
const int blockSize = 8192;
const int blockCount = bigFileSize / blockSize;
for (int block = 0; block < blockCount; ++block) {
int content[blockSize / sizeof(int)];
for (size_t j = 0; j < sizeof content / sizeof content[0]; ++j) {
#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))
content[j] = QRandomGenerator::system()->generate();
#else
content[j] = qrand();
#endif
}
bigFile.write(reinterpret_cast<char *>(content), sizeof content);
}
bigFile.close();
QVERIFY2(bigFile.error() == QFile::NoError, qPrintable(bigFile.errorString()));
const SftpJobId uploadJob = sftpChannel->uploadFile(bigFile.fileName(),
getRemoteFilePath(bigFileName), SftpOverwriteExisting);
QVERIFY(uploadJob != SftpInvalidJob);
jobs << uploadJob;
QCOMPARE(jobs.size(), 1001);
loop.exec();
QVERIFY(!invalidFinishedSignal);
QVERIFY2(jobError.isEmpty(), qPrintable(jobError));
QCOMPARE(sftpChannel->state(), SftpChannel::Initialized);
QVERIFY(jobs.empty());
// Download the uploaded files to a different location
const QStringList allUploadedFileNames
= QDir(dirForFilesToUpload.path()).entryList(QDir::Files);
QCOMPARE(allUploadedFileNames.size(), 1001);
for (const QString &fileName : allUploadedFileNames) {
const QString localFilePath = dirForFilesToUpload.path() + QLatin1Char('/') + fileName;
const QString remoteFilePath = getRemoteFilePath(fileName);
const QString downloadFilePath = getDownloadFilePath(fileName);
const SftpJobId downloadJob = sftpChannel->downloadFile(remoteFilePath, downloadFilePath,
SftpOverwriteExisting);
QVERIFY(downloadJob != SftpInvalidJob);
jobs << downloadJob;
}
QCOMPARE(jobs.size(), 1001);
loop.exec();
QVERIFY(!invalidFinishedSignal);
QVERIFY2(jobError.isEmpty(), qPrintable(jobError));
QCOMPARE(sftpChannel->state(), SftpChannel::Initialized);
QVERIFY(jobs.empty());
// Compare contents of uploaded and downloaded files
for (const QString &fileName : allUploadedFileNames) {
QFile originalFile(dirForFilesToUpload.path() + QLatin1Char('/') + fileName);
QVERIFY2(originalFile.open(QIODevice::ReadOnly), qPrintable(originalFile.errorString()));
QFile downloadedFile(dirForFilesToDownload.path() + QLatin1Char('/') + fileName);
QVERIFY2(downloadedFile.open(QIODevice::ReadOnly),
qPrintable(downloadedFile.errorString()));
QVERIFY(originalFile.fileName() != downloadedFile.fileName());
QCOMPARE(originalFile.size(), downloadedFile.size());
qint64 bytesLeft = originalFile.size();
while (bytesLeft > 0) {
const qint64 bytesToRead = qMin(bytesLeft, Q_INT64_C(1024 * 1024));
const QByteArray origBlock = originalFile.read(bytesToRead);
const QByteArray copyBlock = downloadedFile.read(bytesToRead);
QCOMPARE(origBlock.size(), bytesToRead);
QCOMPARE(origBlock, copyBlock);
bytesLeft -= bytesToRead;
}
}
// Remove the uploaded files on the remote system
for (const QString &fileName : allUploadedFileNames) {
const QString remoteFilePath = getRemoteFilePath(fileName);
const SftpJobId removeJob = sftpChannel->removeFile(remoteFilePath);
QVERIFY(removeJob != SftpInvalidJob);
jobs << removeJob;
}
loop.exec();
QVERIFY(!invalidFinishedSignal);
QVERIFY2(jobError.isEmpty(), qPrintable(jobError));
QCOMPARE(sftpChannel->state(), SftpChannel::Initialized);
QVERIFY(jobs.empty());
// Create a directory on the remote system
const QString remoteDirPath = QLatin1String("/tmp/sftptest-") + QDateTime::currentDateTime().toString();
const SftpJobId mkdirJob = sftpChannel->createDirectory(remoteDirPath);
QVERIFY(mkdirJob != SftpInvalidJob);
jobs << mkdirJob;
loop.exec();
QVERIFY(!invalidFinishedSignal);
QVERIFY2(jobError.isEmpty(), qPrintable(jobError));
QCOMPARE(sftpChannel->state(), SftpChannel::Initialized);
QVERIFY(jobs.empty());
// Retrieve and check the attributes of the remote directory
QList<SftpFileInfo> remoteFileInfo;
const auto fileInfoHandler
= [&remoteFileInfo](SftpJobId, const QList<SftpFileInfo> &fileInfoList) {
remoteFileInfo << fileInfoList;
};
connect(sftpChannel.data(), &SftpChannel::fileInfoAvailable, fileInfoHandler);
const SftpJobId statDirJob = sftpChannel->statFile(remoteDirPath);
QVERIFY(statDirJob != SftpInvalidJob);
jobs << statDirJob;
loop.exec();
QVERIFY(!invalidFinishedSignal);
QVERIFY2(jobError.isEmpty(), qPrintable(jobError));
QCOMPARE(sftpChannel->state(), SftpChannel::Initialized);
QVERIFY(jobs.empty());
QCOMPARE(remoteFileInfo.size(), 1);
const SftpFileInfo remoteDirInfo = remoteFileInfo.takeFirst();
QCOMPARE(remoteDirInfo.type, FileTypeDirectory);
QCOMPARE(remoteDirInfo.name, QFileInfo(remoteDirPath).fileName());
// Retrieve and check the contents of the remote directory
const SftpJobId lsDirJob = sftpChannel->listDirectory(remoteDirPath);
QVERIFY(lsDirJob != SftpInvalidJob);
jobs << lsDirJob;
loop.exec();
QVERIFY(!invalidFinishedSignal);
QVERIFY2(jobError.isEmpty(), qPrintable(jobError));
QCOMPARE(sftpChannel->state(), SftpChannel::Initialized);
QVERIFY(jobs.empty());
QCOMPARE(remoteFileInfo.size(), 2);
for (const SftpFileInfo &fi : remoteFileInfo) {
QCOMPARE(fi.type, FileTypeDirectory);
QVERIFY2(fi.name == QLatin1String(".") || fi.name == QLatin1String(".."), qPrintable(fi.name));
}
QVERIFY(remoteFileInfo.first().name != remoteFileInfo.last().name);
// Remove the remote directory.
const SftpJobId rmDirJob = sftpChannel->removeDirectory(remoteDirPath);
QVERIFY(rmDirJob != SftpInvalidJob);
jobs << rmDirJob;
loop.exec();
QVERIFY(!invalidFinishedSignal);
QVERIFY2(jobError.isEmpty(), qPrintable(jobError));
QCOMPARE(sftpChannel->state(), SftpChannel::Initialized);
QVERIFY(jobs.empty());
// Closing down
sftpChannel->closeChannel();
QCOMPARE(sftpChannel->state(), SftpChannel::Closing);
loop.exec();
QVERIFY(!invalidFinishedSignal);
QVERIFY2(jobError.isEmpty(), qPrintable(jobError));
QCOMPARE(sftpChannel->state(), SftpChannel::Closed);
}
static QStringList appendExeExtensions(const QString &executable)
{
QStringList execs(executable);
const QFileInfo fi(executable);
#ifdef Q_OS_WIN
// Check all the executable extensions on windows:
// PATHEXT is only used if the executable has no extension
// if (fi.suffix().isEmpty()) {
// const QStringList extensions = value("PATHEXT").split(';');
// for (const QString &ext : extensions)
// execs << executable + ext.toLower();
// }
#endif
return execs;
}
/** Expand environment variables in a string.
*
* Environment variables are accepted in the following forms:
* $SOMEVAR, ${SOMEVAR} on Unix and %SOMEVAR% on Windows.
* No escapes and quoting are supported.
* If a variable is not found, it is not substituted.
*/
static QString expandVariables(const QString &input)
{
QString result = input;
#ifdef Q_OS_WIN
for (int vStart = -1, i = 0; i < result.length(); ) {
QChar c = result.at(i++);
if (c == QLatin1Char('%')) {
if (vStart > 0) {
const QByteArray varName = result.mid(vStart, i - vStart - 1).toLocal8Bit();
if (qEnvironmentVariableIsSet(varName.constData())) {
const QByteArray varValue = qgetenv(varName.constData());
result.replace(vStart - 1, i - vStart + 1, QString::fromStdString(varValue.toStdString()));
i = vStart - 1 + varValue.length();
vStart = -1;
} else {
vStart = i;
}
} else {
vStart = i;
}
}
}
#else//Q_OS_WIN
enum { BASE, OPTIONALVARIABLEBRACE, VARIABLE, BRACEDVARIABLE } state = BASE;
int vStart = -1;
for (int i = 0; i < result.length();) {
QChar c = result.at(i++);
if (state == BASE) {
if (c == QLatin1Char('$'))
state = OPTIONALVARIABLEBRACE;
} else if (state == OPTIONALVARIABLEBRACE) {
if (c == QLatin1Char('{')) {
state = BRACEDVARIABLE;
vStart = i;
} else if (c.isLetterOrNumber() || c == QLatin1Char('_')) {
state = VARIABLE;
vStart = i - 1;
} else {
state = BASE;
}
} else if (state == BRACEDVARIABLE) {
if (c == QLatin1Char('}')) {
const QByteArray varName = result.mid(vStart, i - 1 - vStart).toLocal8Bit();
if (qEnvironmentVariableIsSet(varName.constData())) {
const QString varValue = QString::fromLocal8Bit(qgetenv(varName.constData()));
result.replace(vStart - 2, i - vStart + 2, varValue);
i = vStart - 2 + varValue.length();
}
state = BASE;
}
} else if (state == VARIABLE) {
if (!c.isLetterOrNumber() && c != QLatin1Char('_')) {
const QByteArray varName = result.mid(vStart, i - vStart - 1).toLocal8Bit();
if (qEnvironmentVariableIsSet(varName.constData())) {
const QString varValue = QString::fromLocal8Bit(qgetenv(varName.constData()));
result.replace(vStart - 1, i - vStart, varValue);
i = vStart - 1 + varValue.length();
}
state = BASE;
}
}
}
if (state == VARIABLE) {
const QByteArray varName = result.mid(vStart).toLocal8Bit();
if (qEnvironmentVariableIsSet(varName.constData())) {
result.replace(vStart - 1, result.length() - vStart + 1, QString::fromLocal8Bit(qgetenv(varName.constData())));
}
}
#endif//Q_OS_WIN
return result;
}
/// Constructs a FileName from \a fileName
/// \a fileName is only passed through QDir::cleanPath
static QFileInfo fromUserInput(const QString &filename)
{
QString clean = QDir::cleanPath(filename);
if (clean.startsWith(QLatin1String("~/")))
clean = QDir::homePath() + clean.mid(1);
return QFileInfo(clean);
}
static QFileInfoList systemPath()
{
#ifdef Q_OS_WIN
static const QLatin1Char separator(';');
#else
static const QLatin1Char separator(':');
#endif
const QStringList pathComponents = QString::fromLocal8Bit(qgetenv("PATH"))
#if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0))
.split(separator, Qt::SkipEmptyParts);
#else
.split(separator, QString::SkipEmptyParts);
#endif
QFileInfoList ret;
for (const QString &component : pathComponents) {
ret.append(fromUserInput(component));
}
return ret;
}
static QFileInfo searchInDirectory(const QStringList &execs, const QFileInfo &directory,
QSet<QString> &alreadyChecked)
{
const int checkedCount = alreadyChecked.count();
alreadyChecked.insert(directory.canonicalPath());
if (!directory.isDir() || alreadyChecked.count() == checkedCount)
return QFileInfo();
const QString dir = directory.canonicalPath();
QFileInfo fi;
for (const QString &exec : execs) {