forked from Akimkin/kf5-kio-ftps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathftps.cpp
2725 lines (2341 loc) · 89.9 KB
/
ftps.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
/*
This file is part of the KDE libraries
SPDX-FileCopyrightText: 2000-2006 David Faure <faure@kde.org>
SPDX-FileCopyrightText: 2019-2021 Harald Sitter <sitter@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
/*
Recommended reading explaining FTP details and quirks:
https://cr.yp.to/ftp.html (by D.J. Bernstein)
RFC:
RFC 959 "File Transfer Protocol (FTP)"
RFC 1635 "How to Use Anonymous FTP"
RFC 2428 "FTP Extensions for IPv6 and NATs" (defines EPRT and EPSV)
RFC 4217 "Securing FTP with TLS"
*/
#include <config-kioworker-ftps.h>
#include "ftps.h"
#ifdef Q_OS_WIN
#include <sys/utime.h>
#else
#include <utime.h>
#endif
#include <cctype>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <QAuthenticator>
#include <QCoreApplication>
#include <QDir>
#include <QHostAddress>
#include <QMimeDatabase>
#include <QNetworkProxy>
#include <QSslSocket>
#include <QTcpServer>
#include <QTcpSocket>
#include <KConfigGroup>
#include <KLocalizedString>
#include <KMessageBox>
#include <QDebug>
#include <kio/authinfo.h>
#include <kio/ioworker_defaults.h>
#include <kremoteencoding.h>
#include <QLoggingCategory>
Q_DECLARE_LOGGING_CATEGORY(KIO_FTPS)
Q_LOGGING_CATEGORY(KIO_FTPS, "kf.kio.workers.ftps", QtWarningMsg)
#if HAVE_STRTOLL
#define charToLongLong(a) strtoll(a, nullptr, 10)
#else
#define charToLongLong(a) strtol(a, nullptr, 10)
#endif
static constexpr char s_ftpLogin[] = "anonymous";
static constexpr char s_ftpPasswd[] = "anonymous@";
static constexpr bool s_enableCanResume = true;
// Pseudo plugin class to embed meta data
class KIOPluginForMetaData : public QObject
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.kde.kio.worker.ftps" FILE "ftps.json")
};
void SslServer::incomingConnection(qintptr socketDescriptor)
{
QSslSocket *m_socket = new QSslSocket;
if (!m_socket->setSocketDescriptor(socketDescriptor)) delete m_socket; //{
//connect(m_socket, SIGNAL(encrypted()), this, SLOT(ready()));
// //serverSocket->startServerEncryption();
//} else {
// delete serverSocket;
//}
}
static QString ftpCleanPath(const QString &path)
{
if (path.endsWith(QLatin1String(";type=A"), Qt::CaseInsensitive) || path.endsWith(QLatin1String(";type=I"), Qt::CaseInsensitive)
|| path.endsWith(QLatin1String(";type=D"), Qt::CaseInsensitive)) {
return path.left((path.length() - qstrlen(";type=X")));
}
return path;
}
static char ftpModeFromPath(const QString &path, char defaultMode = '\0')
{
const int index = path.lastIndexOf(QLatin1String(";type="));
if (index > -1 && (index + 6) < path.size()) {
const QChar mode = path.at(index + 6);
// kio_ftp supports only A (ASCII) and I(BINARY) modes.
if (mode == QLatin1Char('A') || mode == QLatin1Char('a') || mode == QLatin1Char('I') || mode == QLatin1Char('i')) {
return mode.toUpper().toLatin1();
}
}
return defaultMode;
}
static bool supportedProxyScheme(const QString &scheme)
{
return (scheme == QLatin1String("ftps") || scheme == QLatin1String("socks"));
}
// JPF: somebody should find a better solution for this or move this to KIO
namespace KIO
{
enum buffersizes {
/**
* largest buffer size that should be used to transfer data between
* KIO workers using the data() function
*/
maximumIpcSize = 32 * 1024,
/**
* this is a reasonable value for an initial read() that a KIO worker
* can do to obtain data via a slow network connection.
*/
initialIpcSize = 2 * 1024,
/**
* recommended size of a data block passed to findBufferFileType()
*/
minimumMimeSize = 1024,
};
// JPF: this helper was derived from write_all in file.cc (FileProtocol).
static // JPF: in ftp.cc we make it static
/**
* This helper handles some special issues (blocking and interrupted
* system call) when writing to a file handle.
*
* @return 0 on success or an error code on failure (ERR_CANNOT_WRITE,
* ERR_DISK_FULL, ERR_CONNECTION_BROKEN).
*/
int
WriteToFile(int fd, const char *buf, size_t len)
{
while (len > 0) {
// JPF: shouldn't there be a KDE_write?
ssize_t written = write(fd, buf, len);
if (written >= 0) {
buf += written;
len -= written;
continue;
}
switch (errno) {
case EINTR:
continue;
case EPIPE:
return ERR_CONNECTION_BROKEN;
case ENOSPC:
return ERR_DISK_FULL;
default:
return ERR_CANNOT_WRITE;
}
}
return 0;
}
}
const KIO::filesize_t FtpInternal::UnknownSize = (KIO::filesize_t)-1;
using namespace KIO;
extern "C" Q_DECL_EXPORT int kdemain(int argc, char **argv)
{
QCoreApplication app(argc, argv);
app.setApplicationName(QStringLiteral("kio_ftps"));
qCDebug(KIO_FTPS) << "Starting";
if (argc != 4) {
fprintf(stderr, "Usage: kio_ftp protocol domain-socket1 domain-socket2\n");
exit(-1);
}
Ftp worker(argv[2], argv[3]);
worker.dispatchLoop();
qCDebug(KIO_FTPS) << "Done";
return 0;
}
//===============================================================================
// FtpInternal
//===============================================================================
/**
* This closes a data connection opened by ftpOpenDataConnection().
*/
void FtpInternal::ftpCloseDataConnection()
{
delete m_data;
m_data = nullptr;
delete m_server;
m_server = nullptr;
}
/**
* This closes a control connection opened by ftpOpenControlConnection() and reinits the
* related states. This method gets called from the constructor with m_control = nullptr.
*/
void FtpInternal::ftpCloseControlConnection()
{
m_extControl = 0;
delete m_control;
m_control = nullptr;
m_cDataMode = 0;
m_bLoggedOn = false; // logon needs control connection
m_bTextMode = false;
m_bBusy = false;
}
/**
* Returns the last response from the server (iOffset >= 0) -or- reads a new response
* (iOffset < 0). The result is returned (with iOffset chars skipped for iOffset > 0).
*/
const char *FtpInternal::ftpResponse(int iOffset)
{
Q_ASSERT(m_control); // must have control connection socket
const char *pTxt = m_lastControlLine.data();
// read the next line ...
if (iOffset < 0) {
int iMore = 0;
m_iRespCode = 0;
if (!pTxt) {
return nullptr; // avoid using a nullptr when calling atoi.
}
// If the server sends a multiline response starting with
// "nnn-text" we loop here until a final "nnn text" line is
// reached. Only data from the final line will be stored.
do {
while (!m_control->canReadLine() && m_control->waitForReadyRead((q->readTimeout() * 1000))) { }
m_lastControlLine = m_control->readLine();
pTxt = m_lastControlLine.data();
int iCode = atoi(pTxt);
if (iMore == 0) {
// first line
qCDebug(KIO_FTPS) << " > " << pTxt;
if (iCode >= 100) {
m_iRespCode = iCode;
if (pTxt[3] == '-') {
// marker for a multiple line response
iMore = iCode;
}
} else {
qCWarning(KIO_FTPS) << "Cannot parse valid code from line" << pTxt;
}
} else {
// multi-line
qCDebug(KIO_FTPS) << " > " << pTxt;
if (iCode >= 100 && iCode == iMore && pTxt[3] == ' ') {
iMore = 0;
}
}
} while (iMore != 0);
qCDebug(KIO_FTPS) << "resp> " << pTxt;
m_iRespType = (m_iRespCode > 0) ? m_iRespCode / 100 : 0;
}
// return text with offset ...
while (iOffset-- > 0 && pTxt[0]) {
pTxt++;
}
return pTxt;
}
void FtpInternal::closeConnection()
{
if (m_control || m_data) {
qCDebug(KIO_FTPS) << "m_bLoggedOn=" << m_bLoggedOn << " m_bBusy=" << m_bBusy;
}
if (m_bBusy) { // ftpCloseCommand not called
qCWarning(KIO_FTPS) << "Abandoned data stream";
ftpCloseDataConnection();
}
if (m_bLoggedOn) { // send quit
if (!ftpSendCmd(QByteArrayLiteral("quit"), 0) || (m_iRespType != 2)) {
qCWarning(KIO_FTPS) << "QUIT returned error: " << m_iRespCode;
}
}
// close the data and control connections ...
ftpCloseDataConnection();
ftpCloseControlConnection();
}
FtpInternal::FtpInternal(Ftp *qptr)
: QObject()
, q(qptr)
{
ftpCloseControlConnection();
}
FtpInternal::~FtpInternal()
{
qCDebug(KIO_FTPS);
closeConnection();
}
void FtpInternal::setHost(const QString &_host, quint16 _port, const QString &_user, const QString &_pass)
{
qCDebug(KIO_FTPS) << _host << "port=" << _port << "user=" << _user;
m_proxyURL.clear();
m_proxyUrls.clear();
const auto proxies = QNetworkProxyFactory::proxyForQuery(QNetworkProxyQuery(_host, _port, QStringLiteral("ftps"), QNetworkProxyQuery::UrlRequest));
for (const QNetworkProxy &proxy : proxies) {
if (proxy.type() != QNetworkProxy::NoProxy) {
QUrl proxyUrl;
proxyUrl.setScheme(QStringLiteral("ftps"));
proxyUrl.setUserName(proxy.user());
proxyUrl.setPassword(proxy.password());
proxyUrl.setHost(proxy.hostName());
proxyUrl.setPort(proxy.port());
m_proxyUrls << proxyUrl.toString();
}
}
qCDebug(KIO_FTPS) << "proxy urls:" << m_proxyUrls;
if (m_host != _host || m_port != _port || m_user != _user || m_pass != _pass) {
closeConnection();
}
m_host = _host;
m_port = _port;
m_user = _user;
m_pass = _pass;
}
Result FtpInternal::openConnection()
{
return ftpOpenConnection(LoginMode::Explicit);
}
Result FtpInternal::ftpOpenConnection(LoginMode loginMode)
{
// check for implicit login if we are already logged on ...
if (loginMode == LoginMode::Implicit && m_bLoggedOn) {
Q_ASSERT(m_control); // must have control connection socket
return Result::pass();
}
qCDebug(KIO_FTPS) << "host=" << m_host << ", port=" << m_port << ", user=" << m_user << "password= [password hidden]";
q->infoMessage(i18n("Opening connection to host %1", m_host));
if (m_host.isEmpty()) {
return Result::fail(ERR_UNKNOWN_HOST);
}
Q_ASSERT(!m_bLoggedOn);
m_initialPath.clear();
m_currentPath.clear();
const Result result = ftpOpenControlConnection();
if (!result.success()) {
return result;
}
q->infoMessage(i18n("Connected to host %1", m_host));
bool userNameChanged = false;
if (loginMode != LoginMode::Deferred) {
const Result result = ftpLogin(&userNameChanged);
m_bLoggedOn = result.success();
if (!m_bLoggedOn) {
return result;
}
}
m_bTextMode = q->configValue(QStringLiteral("textmode"), false);
// Redirected due to credential change...
if (userNameChanged && m_bLoggedOn) {
QUrl realURL;
realURL.setScheme(QStringLiteral("ftps"));
if (m_user != QLatin1String(s_ftpLogin)) {
realURL.setUserName(m_user);
}
if (m_pass != QLatin1String(s_ftpPasswd)) {
realURL.setPassword(m_pass);
}
realURL.setHost(m_host);
if (m_port > 0 && m_port != DEFAULT_FTP_PORT) {
realURL.setPort(m_port);
}
if (m_initialPath.isEmpty()) {
m_initialPath = QStringLiteral("/");
}
realURL.setPath(m_initialPath);
qCDebug(KIO_FTPS) << "User name changed! Redirecting to" << realURL;
q->redirection(realURL);
return Result::fail();
}
return Result::pass();
}
/**
* Called by @ref openConnection. It opens the control connection to the ftp server.
*
* @return true on success.
*/
Result FtpInternal::ftpOpenControlConnection()
{
if (m_proxyUrls.isEmpty()) {
return ftpOpenControlConnection(m_host, m_port, true);
}
Result result = Result::fail();
for (const QString &proxyUrl : std::as_const(m_proxyUrls)) {
const QUrl url(proxyUrl);
const QString scheme(url.scheme());
if (!supportedProxyScheme(scheme)) {
// TODO: Need a new error code to indicate unsupported URL scheme.
result = Result::fail(ERR_CANNOT_CONNECT, url.toString());
continue;
}
if (!isSocksProxyScheme(scheme)) {
const Result result = ftpOpenControlConnection(url.host(), url.port(), true);
if (result.success()) {
return Result::pass();
}
continue;
}
qCDebug(KIO_FTPS) << "Connecting to SOCKS proxy @" << url;
m_proxyURL = url;
result = ftpOpenControlConnection(m_host, m_port, true);
if (result.success()) {
return result;
}
m_proxyURL.clear();
}
return result;
}
Result FtpInternal::ftpOpenControlConnection(const QString &host, int port, bool ignoreSslErrors)
{
m_bIgnoreSslErrors = ignoreSslErrors;
// implicitly close, then try to open a new connection ...
closeConnection();
QString sErrorMsg;
// now connect to the server and read the login message ...
if (port == 0) {
port = 21; // default FTP port
}
const auto connectionResult = synchronousConnectToHost(host, port);
m_control = connectionResult.socket;
int iErrorCode = m_control->state() == QAbstractSocket::ConnectedState ? 0 : ERR_CANNOT_CONNECT;
if (!connectionResult.result.success()) {
qDebug() << "overriding error code!!1" << connectionResult.result.error();
iErrorCode = connectionResult.result.error();
sErrorMsg = connectionResult.result.errorString();
}
// on connect success try to read the server message...
if (iErrorCode == 0) {
const char *psz = ftpResponse(-1);
if (m_iRespType != 2) {
// login not successful, do we have an message text?
if (psz[0]) {
sErrorMsg = i18n("%1 (Error %2)", host, q->remoteEncoding()->decode(psz).trimmed());
}
iErrorCode = ERR_CANNOT_CONNECT;
}
} else {
const auto socketError = m_control->error();
if (socketError == QAbstractSocket::HostNotFoundError) {
iErrorCode = ERR_UNKNOWN_HOST;
}
sErrorMsg = QStringLiteral("%1: %2").arg(host, m_control->errorString());
}
// Send unencrypted "AUTH TLS" request.
// TODO: redirect to FTP fallback on negative response.
if (iErrorCode == 0) {
bool authSucc = (ftpSendCmd("AUTH TLS") && (m_iRespCode == 234));
if (!authSucc) {
iErrorCode = ERR_WORKER_DEFINED;
sErrorMsg = QStringLiteral("The FTP server does not seem to support ftps-encryption.");
}
}
// Starts the encryption
if(iErrorCode == 0) {
// If the method has been called with ignoreSslErrors, make the ssl socket
// ignore the errors during handshakes.
if (ignoreSslErrors)
m_control->ignoreSslErrors();
m_control->startClientEncryption();
if (!m_control->waitForEncrypted(q->connectTimeout() * 1000)) {
// It is quite common, that the TLS handshake fails, as the majority
// of certificates are self signed, and thus the host cannot be verified.
// If the user wants to continue nevertheless, this method is called
// again, with the "ignoreSslErrors" flag.
bool doNotIgnore = true;
QList<QSslError> errors;
m_control->sslErrors(errors);
for (int i = 0; i < errors.size(); ++i) {
if (KMessageBox::warningContinueCancel(nullptr, errors.at(i).errorString(),
i18n("TLS Handshake Error"), KStandardGuiItem::cont(), KStandardGuiItem::cancel()) == KMessageBox::Cancel) {
doNotIgnore = false;
}
}
if (doNotIgnore) {
iErrorCode = ERR_WORKER_DEFINED;
sErrorMsg = QObject::tr("TLS Handshake Error.");
} else {
closeConnection();
return ftpOpenControlConnection(host, port, true);
}
}
}
// if there was a problem - report it ...
if (iErrorCode == 0) { // OK, return success
return Result::pass();
}
closeConnection(); // clean-up on error
return Result::fail(iErrorCode, sErrorMsg);
}
/**
* Called by @ref openConnection. It logs us in.
* @ref m_initialPath is set to the current working directory
* if logging on was successful.
*
* @return true on success.
*/
Result FtpInternal::ftpLogin(bool *userChanged)
{
q->infoMessage(i18n("Sending login information"));
Q_ASSERT(!m_bLoggedOn);
QString user(m_user);
QString pass(m_pass);
AuthInfo info;
info.url.setScheme(QStringLiteral("ftps"));
info.url.setHost(m_host);
if (m_port > 0 && m_port != DEFAULT_FTP_PORT) {
info.url.setPort(m_port);
}
if (!user.isEmpty()) {
info.url.setUserName(user);
}
// Check for cached authentication first and fallback to
// anonymous login when no stored credentials are found.
if (!q->configValue(QStringLiteral("TryAnonymousLoginFirst"), false) && pass.isEmpty() && q->checkCachedAuthentication(info)) {
user = info.username;
pass = info.password;
}
// Try anonymous login if both username/password
// information is blank.
if (user.isEmpty() && pass.isEmpty()) {
user = QString::fromLatin1(s_ftpLogin);
pass = QString::fromLatin1(s_ftpPasswd);
}
QByteArray tempbuf;
QString lastServerResponse;
int failedAuth = 0;
bool promptForRetry = false;
// Give the user the option to login anonymously...
info.setExtraField(QStringLiteral("anonymous"), false);
do {
// Check the cache and/or prompt user for password if 1st
// login attempt failed OR the user supplied a login name,
// but no password.
if (failedAuth > 0 || (!user.isEmpty() && pass.isEmpty())) {
QString errorMsg;
qCDebug(KIO_FTPS) << "Prompting user for login info...";
// Ask user if we should retry after when login fails!
if (failedAuth > 0 && promptForRetry) {
errorMsg = i18n(
"Message sent:\nLogin using username=%1 and "
"password=[hidden]\n\nServer replied:\n%2\n\n",
user,
lastServerResponse);
}
if (user != QLatin1String(s_ftpLogin)) {
info.username = user;
}
info.prompt = i18n(
"You need to supply a username and a password "
"to access this site.");
info.commentLabel = i18n("Site:");
info.comment = i18n("<b>%1</b>", m_host);
info.keepPassword = true; // Prompt the user for persistence as well.
info.setModified(false); // Default the modified flag since we reuse authinfo.
const bool disablePassDlg = q->configValue(QStringLiteral("DisablePassDlg"), false);
if (disablePassDlg) {
return Result::fail(ERR_USER_CANCELED, m_host);
}
const int errorCode = q->openPasswordDialog(info, errorMsg);
if (errorCode) {
return Result::fail(errorCode);
} else {
// User can decide go anonymous using checkbox
if (info.getExtraField(QStringLiteral("anonymous")).toBool()) {
user = QString::fromLatin1(s_ftpLogin);
pass = QString::fromLatin1(s_ftpPasswd);
} else {
user = info.username;
pass = info.password;
}
promptForRetry = true;
}
}
tempbuf = "USER " + user.toLatin1();
if (m_proxyURL.isValid()) {
tempbuf += '@' + m_host.toLatin1();
if (m_port > 0 && m_port != DEFAULT_FTP_PORT) {
tempbuf += ':' + QByteArray::number(m_port);
}
}
qCDebug(KIO_FTPS) << "Sending Login name: " << tempbuf;
bool loggedIn = (ftpSendCmd(tempbuf) && (m_iRespCode == 230));
bool needPass = (m_iRespCode == 331);
// Prompt user for login info if we do not
// get back a "230" or "331".
if (!loggedIn && !needPass) {
lastServerResponse = QString::fromUtf8(ftpResponse(0));
qCDebug(KIO_FTPS) << "Login failed: " << lastServerResponse;
++failedAuth;
continue; // Well we failed, prompt the user please!!
}
if (needPass) {
tempbuf = "PASS " + pass.toLatin1();
qCDebug(KIO_FTPS) << "Sending Login password: "
<< "[protected]";
loggedIn = (ftpSendCmd(tempbuf) && (m_iRespCode == 230));
}
if (loggedIn) {
// Make sure the user name changed flag is properly set.
if (userChanged) {
*userChanged = (!m_user.isEmpty() && (m_user != user));
}
// Do not cache the default login!!
if (user != QLatin1String(s_ftpLogin) && pass != QLatin1String(s_ftpPasswd)) {
// Update the username in case it was changed during login.
if (!m_user.isEmpty()) {
info.url.setUserName(user);
m_user = user;
}
// Cache the password if the user requested it.
if (info.keepPassword) {
q->cacheAuthentication(info);
}
}
failedAuth = -1;
} else {
// some servers don't let you login anymore
// if you fail login once, so restart the connection here
lastServerResponse = QString::fromUtf8(ftpResponse(0));
const Result result = ftpOpenControlConnection();
if (!result.success()) {
return result;
}
}
} while (++failedAuth);
qCDebug(KIO_FTPS) << "Login OK";
q->infoMessage(i18n("Login OK"));
// Okay, we're logged in. If this is IIS 4, switch dir listing style to Unix:
// Thanks to jk@soegaard.net (Jens Kristian Sgaard) for this hint
if (ftpSendCmd(QByteArrayLiteral("SYST")) && (m_iRespType == 2)) {
if (!qstrncmp(ftpResponse(0), "215 Windows_NT", 14)) { // should do for any version
(void)ftpSendCmd(QByteArrayLiteral("site dirstyle"));
// Check if it was already in Unix style
// Patch from Keith Refson <Keith.Refson@earth.ox.ac.uk>
if (!qstrncmp(ftpResponse(0), "200 MSDOS-like directory output is on", 37))
// It was in Unix style already!
{
(void)ftpSendCmd(QByteArrayLiteral("site dirstyle"));
}
// windows won't support chmod before KDE konquers their desktop...
m_extControl |= chmodUnknown;
}
} else {
qCWarning(KIO_FTPS) << "SYST failed";
}
// Get the current working directory
qCDebug(KIO_FTPS) << "Searching for pwd";
if (!ftpSendCmd(QByteArrayLiteral("PWD")) || (m_iRespType != 2)) {
qCDebug(KIO_FTPS) << "Couldn't issue pwd command";
return Result::fail(ERR_CANNOT_LOGIN, i18n("Could not login to %1.", m_host)); // or anything better ?
}
QString sTmp = q->remoteEncoding()->decode(ftpResponse(3));
const int iBeg = sTmp.indexOf(QLatin1Char('"'));
const int iEnd = sTmp.lastIndexOf(QLatin1Char('"'));
if (iBeg > 0 && iBeg < iEnd) {
m_initialPath = sTmp.mid(iBeg + 1, iEnd - iBeg - 1);
if (!m_initialPath.startsWith(QLatin1Char('/'))) {
m_initialPath.prepend(QLatin1Char('/'));
}
qCDebug(KIO_FTPS) << "Initial path set to: " << m_initialPath;
m_currentPath = m_initialPath;
}
return Result::pass();
}
/**
* ftpSendCmd - send a command (@p cmd) and read response
*
* @param maxretries number of time it should retry. Since it recursively
* calls itself if it can't read the answer (this happens especially after
* timeouts), we need to limit the recursiveness ;-)
*
* return true if any response received, false on error
*/
bool FtpInternal::ftpSendCmd(const QByteArray &cmd, int maxretries)
{
Q_ASSERT(m_control); // must have control connection socket
if (cmd.indexOf('\r') != -1 || cmd.indexOf('\n') != -1) {
qCWarning(KIO_FTPS) << "Invalid command received (contains CR or LF):" << cmd.data();
return false;
}
// Don't print out the password...
bool isPassCmd = (cmd.left(4).toLower() == "pass");
// Send the message...
const QByteArray buf = cmd + "\r\n"; // Yes, must use CR/LF - see https://cr.yp.to/ftp/request.html
int num = m_control->write(buf);
while (m_control->bytesToWrite() && m_control->waitForBytesWritten()) { }
// If we were able to successfully send the command, then we will
// attempt to read the response. Otherwise, take action to re-attempt
// the login based on the maximum number of retries specified...
if (num > 0) {
ftpResponse(-1);
} else {
m_iRespType = m_iRespCode = 0;
}
// If respCh is NULL or the response is 421 (Timed-out), we try to re-send
// the command based on the value of maxretries.
if ((m_iRespType <= 0) || (m_iRespCode == 421)) {
// We have not yet logged on...
if (!m_bLoggedOn) {
// The command was sent from the ftpLogin function, i.e. we are actually
// attempting to login in. NOTE: If we already sent the username, we
// return false and let the user decide whether (s)he wants to start from
// the beginning...
if (maxretries > 0 && !isPassCmd) {
closeConnection();
const auto result = ftpOpenConnection(LoginMode::Deferred);
if (result.success() && ftpSendCmd(cmd, maxretries - 1)) {
return true;
}
}
return false;
} else {
if (maxretries < 1) {
return false;
} else {
qCDebug(KIO_FTPS) << "Was not able to communicate with " << m_host << "Attempting to re-establish connection.";
closeConnection(); // Close the old connection...
const Result openResult = openConnection(); // Attempt to re-establish a new connection...
if (!openResult.success()) {
if (m_control) { // if openConnection succeeded ...
qCDebug(KIO_FTPS) << "Login failure, aborting";
closeConnection();
}
return false;
}
qCDebug(KIO_FTPS) << "Logged back in, re-issuing command";
// If we were able to login, resend the command...
if (maxretries) {
maxretries--;
}
return ftpSendCmd(cmd, maxretries);
}
}
}
return true;
}
/*
* ftpOpenPASVDataConnection - set up data connection, using PASV mode
*
* return 0 if successful, ERR_INTERNAL otherwise
* doesn't set error message, since non-pasv mode will always be tried if
* this one fails
*/
int FtpInternal::ftpOpenPASVDataConnection()
{
Q_ASSERT(m_control); // must have control connection socket
Q_ASSERT(!m_data); // ... but no data connection
// Check that we can do PASV
QHostAddress address = m_control->peerAddress();
if (address.protocol() != QAbstractSocket::IPv4Protocol && !isSocksProxy()) {
return ERR_INTERNAL; // no PASV for non-PF_INET connections
}
if (m_extControl & pasvUnknown) {
return ERR_INTERNAL; // already tried and got "unknown command"
}
m_bPasv = true;
/* Let's PASsiVe*/
if (!ftpSendCmd(QByteArrayLiteral("PASV")) || (m_iRespType != 2)) {
qCDebug(KIO_FTPS) << "PASV attempt failed";
// unknown command?
if (m_iRespType == 5) {
qCDebug(KIO_FTPS) << "disabling use of PASV";
m_extControl |= pasvUnknown;
}
return ERR_INTERNAL;
}
// The usual answer is '227 Entering Passive Mode. (160,39,200,55,6,245)'
// but anonftpd gives '227 =160,39,200,55,6,245'
int i[6];
const char *start = strchr(ftpResponse(3), '(');
if (!start) {
start = strchr(ftpResponse(3), '=');
}
if (!start
|| (sscanf(start, "(%d,%d,%d,%d,%d,%d)", &i[0], &i[1], &i[2], &i[3], &i[4], &i[5]) != 6
&& sscanf(start, "=%d,%d,%d,%d,%d,%d", &i[0], &i[1], &i[2], &i[3], &i[4], &i[5]) != 6)) {
qCritical() << "parsing IP and port numbers failed. String parsed: " << start;
return ERR_INTERNAL;
}
// we ignore the host part on purpose for two reasons
// a) it might be wrong anyway
// b) it would make us being susceptible to a port scanning attack
// now connect the data socket ...
quint16 port = i[4] << 8 | i[5];
const QString host = (isSocksProxy() ? m_host : address.toString());
const auto connectionResult = synchronousConnectToHost(host, port);
m_data = connectionResult.socket;
if (!connectionResult.result.success()) {
return connectionResult.result.error();
}
return m_data->state() == QAbstractSocket::ConnectedState ? 0 : ERR_INTERNAL;
}
/*
* ftpOpenEPSVDataConnection - opens a data connection via EPSV
*/
int FtpInternal::ftpOpenEPSVDataConnection()
{
Q_ASSERT(m_control); // must have control connection socket
Q_ASSERT(!m_data); // ... but no data connection
QHostAddress address = m_control->peerAddress();
int portnum;
if (m_extControl & epsvUnknown) {
return ERR_INTERNAL;
}
m_bPasv = true;
if (!ftpSendCmd(QByteArrayLiteral("EPSV")) || (m_iRespType != 2)) {
// unknown command?
if (m_iRespType == 5) {
qCDebug(KIO_FTPS) << "disabling use of EPSV";
m_extControl |= epsvUnknown;
}
return ERR_INTERNAL;
}
const char *start = strchr(ftpResponse(3), '|');
if (!start || sscanf(start, "|||%d|", &portnum) != 1) {
return ERR_INTERNAL;
}
Q_ASSERT(portnum > 0);
const QString host = (isSocksProxy() ? m_host : address.toString());
const auto connectionResult = synchronousConnectToHost(host, static_cast<quint16>(portnum));
m_data = connectionResult.socket;
if (!connectionResult.result.success()) {
return connectionResult.result.error();
}
return m_data->state() == QAbstractSocket::ConnectedState ? 0 : ERR_INTERNAL;
}
int FtpInternal::encryptDataChannel()
{
if (m_bIgnoreSslErrors)
m_data->ignoreSslErrors();
if (m_bPasv)
m_data->startClientEncryption();
else
m_data->startServerEncryption();
if (!m_data->waitForEncrypted(q->connectTimeout() * 1000))
return ERR_WORKER_DEFINED;
return 0;
}
bool FtpInternal::requestDataEncryption()
{
// initate tls transfer for data chanel on the control channel
bool pbszSucc = (ftpSendCmd("PBSZ 0") && (m_iRespType == 2));
if (!pbszSucc) return false;
// try protected data transfer first
bool protpSucc = (ftpSendCmd("PROT P") && (m_iRespType == 2));
if (!protpSucc)
{
// Set the data channel to clear (should not be necessary, just in case).
ftpSendCmd("PROT C");
return false;
}
return true;
}
/*
* ftpOpenDataConnection - set up data connection
*
* The routine calls several ftpOpenXxxxConnection() helpers to find
* the best connection mode. If a helper cannot connect if returns
* ERR_INTERNAL - so this is not really an error! All other error
* codes are treated as fatal, e.g. they are passed back to the caller
* who is responsible for calling error(). ftpOpenPortDataConnection
* can be called as last try and it does never return ERR_INTERNAL.
*
* @return 0 if successful, err code otherwise
*/
int FtpInternal::ftpOpenDataConnection()
{
// make sure that we are logged on and have no data connection...