-
Notifications
You must be signed in to change notification settings - Fork 0
/
qftp.cpp
2408 lines (2042 loc) · 75.2 KB
/
qftp.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) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//#define QFTPPI_DEBUG
//#define QFTPDTP_DEBUG
#include "qftp.h"
#include "qabstractsocket.h"
#ifndef QT_NO_FTP
#include "qcoreapplication.h"
#include "qtcpsocket.h"
#include "qurlinfo.h"
#include "qstringlist.h"
#include "qregexp.h"
#include "qtimer.h"
#include "qfileinfo.h"
//#include "qhash.h"
#include "qtcpserver.h"
#include "qlocale.h"
QT_BEGIN_NAMESPACE
class QFtpPI;
/*
The QFtpDTP (DTP = Data Transfer Process) controls all client side
data transfer between the client and server.
*/
class QFtpDTP : public QObject
{
Q_OBJECT
public:
enum ConnectState {
CsHostFound,
CsConnected,
CsClosed,
CsHostNotFound,
CsConnectionRefused
};
QFtpDTP(QFtpPI *p, QObject *parent = 0);
void setData(QByteArray *);
void setDevice(QIODevice *);
void writeData();
void setBytesTotal(qint64 bytes);
bool hasError() const;
QString errorMessage() const;
void clearError();
void connectToHost(const QString & host, quint16 port);
int setupListener(const QHostAddress &address);
void waitForConnection();
QTcpSocket::SocketState state() const;
qint64 bytesAvailable() const;
qint64 read(char *data, qint64 maxlen);
QByteArray readAll();
void abortConnection();
static bool parseDir(const QByteArray &buffer, const QString &userName, QUrlInfo *info);
signals:
void listInfo(const QUrlInfo&);
void readyRead();
void dataTransferProgress(qint64, qint64);
void connectState(int);
private slots:
void socketConnected();
void socketReadyRead();
void socketError(QAbstractSocket::SocketError);
void socketConnectionClosed();
void socketBytesWritten(qint64);
void setupSocket();
void dataReadyRead();
private:
void clearData();
QTcpSocket *socket;
QTcpServer listener;
QFtpPI *pi;
QString err;
qint64 bytesDone;
qint64 bytesTotal;
bool callWriteData;
// If is_ba is true, ba is used; ba is never 0.
// Otherwise dev is used; dev can be 0 or not.
union {
QByteArray *ba;
QIODevice *dev;
} data;
bool is_ba;
QByteArray bytesFromSocket;
};
/**********************************************************************
*
* QFtpPI - Protocol Interpreter
*
*********************************************************************/
class QFtpPI : public QObject
{
Q_OBJECT
public:
QFtpPI(QObject *parent = 0);
void connectToHost(const QString &host, quint16 port);
bool sendCommands(const QStringList &cmds);
bool sendCommand(const QString &cmd)
{ return sendCommands(QStringList(cmd)); }
void clearPendingCommands();
void abort();
QString currentCommand() const
{ return currentCmd; }
bool rawCommand;
bool transferConnectionExtended;
QFtpDTP dtp; // the PI has a DTP which is not the design of RFC 959, but it
// makes the design simpler this way
signals:
void connectState(int);
void finished(const QString&);
void error(int, const QString&);
void rawFtpReply(int, const QString&);
private slots:
void hostFound();
void connected();
void connectionClosed();
void delayedCloseFinished();
void readyRead();
void error(QAbstractSocket::SocketError);
void dtpConnectState(int);
private:
// the states are modelled after the generalized state diagram of RFC 959,
// page 58
enum State {
Begin,
Idle,
Waiting,
Success,
Failure
};
enum AbortState {
None,
AbortStarted,
WaitForAbortToFinish
};
bool processReply();
bool startNextCmd();
QTcpSocket commandSocket;
QString replyText;
char replyCode[3];
State state;
AbortState abortState;
QStringList pendingCommands;
QString currentCmd;
bool waitForDtpToConnect;
bool waitForDtpToClose;
QByteArray bytesFromSocket;
friend class QFtpDTP;
};
/**********************************************************************
*
* QFtpCommand implemenatation
*
*********************************************************************/
class QFtpCommand
{
public:
QFtpCommand(QFtp::Command cmd, QStringList raw, const QByteArray &ba);
QFtpCommand(QFtp::Command cmd, QStringList raw, QIODevice *dev = 0);
~QFtpCommand();
int id;
QFtp::Command command;
QStringList rawCmds;
// If is_ba is true, ba is used; ba is never 0.
// Otherwise dev is used; dev can be 0 or not.
union {
QByteArray *ba;
QIODevice *dev;
} data;
bool is_ba;
static QBasicAtomicInt idCounter;
};
QBasicAtomicInt QFtpCommand::idCounter = Q_BASIC_ATOMIC_INITIALIZER(1);
QFtpCommand::QFtpCommand(QFtp::Command cmd, QStringList raw, const QByteArray &ba)
: command(cmd), rawCmds(raw), is_ba(true)
{
id = idCounter.fetchAndAddRelaxed(1);
data.ba = new QByteArray(ba);
}
QFtpCommand::QFtpCommand(QFtp::Command cmd, QStringList raw, QIODevice *dev)
: command(cmd), rawCmds(raw), is_ba(false)
{
id = idCounter.fetchAndAddRelaxed(1);
data.dev = dev;
}
QFtpCommand::~QFtpCommand()
{
if (is_ba)
delete data.ba;
}
/**********************************************************************
*
* QFtpDTP implemenatation
*
*********************************************************************/
QFtpDTP::QFtpDTP(QFtpPI *p, QObject *parent) :
QObject(parent),
socket(0),
listener(this),
pi(p),
callWriteData(false)
{
clearData();
listener.setObjectName(QLatin1String("QFtpDTP active state server"));
connect(&listener, SIGNAL(newConnection()), SLOT(setupSocket()));
}
void QFtpDTP::setData(QByteArray *ba)
{
is_ba = true;
data.ba = ba;
}
void QFtpDTP::setDevice(QIODevice *dev)
{
is_ba = false;
data.dev = dev;
}
void QFtpDTP::setBytesTotal(qint64 bytes)
{
bytesTotal = bytes;
bytesDone = 0;
emit dataTransferProgress(bytesDone, bytesTotal);
}
void QFtpDTP::connectToHost(const QString & host, quint16 port)
{
bytesFromSocket.clear();
if (socket) {
delete socket;
socket = 0;
}
socket = new QTcpSocket(this);
#ifndef QT_NO_BEARERMANAGEMENT
//copy network session down to the socket
socket->setProperty("_q_networksession", property("_q_networksession"));
#endif
socket->setObjectName(QLatin1String("QFtpDTP Passive state socket"));
connect(socket, SIGNAL(connected()), SLOT(socketConnected()));
connect(socket, SIGNAL(readyRead()), SLOT(socketReadyRead()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(socketError(QAbstractSocket::SocketError)));
connect(socket, SIGNAL(disconnected()), SLOT(socketConnectionClosed()));
connect(socket, SIGNAL(bytesWritten(qint64)), SLOT(socketBytesWritten(qint64)));
socket->connectToHost(host, port);
}
int QFtpDTP::setupListener(const QHostAddress &address)
{
#ifndef QT_NO_BEARERMANAGEMENT
//copy network session down to the socket
listener.setProperty("_q_networksession", property("_q_networksession"));
#endif
if (!listener.isListening() && !listener.listen(address, 0))
return -1;
return listener.serverPort();
}
void QFtpDTP::waitForConnection()
{
// This function is only interesting in Active transfer mode; it works
// around a limitation in QFtp's design by blocking, waiting for an
// incoming connection. For the default Passive mode, it does nothing.
if (listener.isListening())
listener.waitForNewConnection();
}
QTcpSocket::SocketState QFtpDTP::state() const
{
return socket ? socket->state() : QTcpSocket::UnconnectedState;
}
qint64 QFtpDTP::bytesAvailable() const
{
if (!socket || socket->state() != QTcpSocket::ConnectedState)
return (qint64) bytesFromSocket.size();
return socket->bytesAvailable();
}
qint64 QFtpDTP::read(char *data, qint64 maxlen)
{
qint64 read;
if (socket && socket->state() == QTcpSocket::ConnectedState) {
read = socket->read(data, maxlen);
} else {
read = qMin(maxlen, qint64(bytesFromSocket.size()));
memcpy(data, bytesFromSocket.data(), read);
bytesFromSocket.remove(0, read);
}
bytesDone += read;
return read;
}
QByteArray QFtpDTP::readAll()
{
QByteArray tmp;
if (socket && socket->state() == QTcpSocket::ConnectedState) {
tmp = socket->readAll();
bytesDone += tmp.size();
} else {
tmp = bytesFromSocket;
bytesFromSocket.clear();
}
return tmp;
}
void QFtpDTP::writeData()
{
if (!socket)
return;
if (is_ba) {
#if defined(QFTPDTP_DEBUG)
qDebug("QFtpDTP::writeData: write %d bytes", data.ba->size());
#endif
if (data.ba->size() == 0)
emit dataTransferProgress(0, bytesTotal);
else
socket->write(data.ba->data(), data.ba->size());
socket->close();
clearData();
} else if (data.dev) {
callWriteData = false;
const qint64 blockSize = 16*1024;
char buf[16*1024];
qint64 read = data.dev->read(buf, blockSize);
#if defined(QFTPDTP_DEBUG)
qDebug("QFtpDTP::writeData: write() of size %lli bytes", read);
#endif
if (read > 0) {
socket->write(buf, read);
} else if (read == -1 || (!data.dev->isSequential() && data.dev->atEnd())) {
// error or EOF
if (bytesDone == 0 && socket->bytesToWrite() == 0)
emit dataTransferProgress(0, bytesTotal);
socket->close();
clearData();
}
// do we continue uploading?
callWriteData = data.dev != 0;
}
}
void QFtpDTP::dataReadyRead()
{
writeData();
}
inline bool QFtpDTP::hasError() const
{
return !err.isNull();
}
inline QString QFtpDTP::errorMessage() const
{
return err;
}
inline void QFtpDTP::clearError()
{
err.clear();
}
void QFtpDTP::abortConnection()
{
#if defined(QFTPDTP_DEBUG)
qDebug("QFtpDTP::abortConnection, bytesAvailable == %lli",
socket ? socket->bytesAvailable() : (qint64) 0);
#endif
callWriteData = false;
clearData();
if (socket)
socket->abort();
}
static void _q_fixupDateTime(QDateTime *dateTime)
{
// Adjust for future tolerance.
const int futureTolerance = 86400;
if (dateTime->secsTo(QDateTime::currentDateTime()) < -futureTolerance) {
QDate d = dateTime->date();
d.setDate(d.year() - 1, d.month(), d.day());
dateTime->setDate(d);
}
}
static void _q_parseUnixDir(const QStringList &tokens, const QString &userName, QUrlInfo *info)
{
// Unix style, 7 + 1 entries
// -rw-r--r-- 1 ftp ftp 17358091 Aug 10 2004 qt-x11-free-3.3.3.tar.gz
// drwxr-xr-x 3 ftp ftp 4096 Apr 14 2000 compiled-examples
// lrwxrwxrwx 1 ftp ftp 9 Oct 29 2005 qtscape -> qtmozilla
if (tokens.size() != 8)
return;
char first = tokens.at(1).at(0).toLatin1();
if (first == 'd') {
info->setDir(true);
info->setFile(false);
info->setSymLink(false);
} else if (first == '-') {
info->setDir(false);
info->setFile(true);
info->setSymLink(false);
} else if (first == 'l') {
info->setDir(true);
info->setFile(false);
info->setSymLink(true);
}
// Resolve filename
QString name = tokens.at(7);
if (info->isSymLink()) {
int linkPos = name.indexOf(QLatin1String(" ->"));
if (linkPos != -1)
name.resize(linkPos);
}
info->setName(name);
// Resolve owner & group
info->setOwner(tokens.at(3));
info->setGroup(tokens.at(4));
// Resolve size
info->setSize(tokens.at(5).toLongLong());
QStringList formats;
formats << QLatin1String("MMM dd yyyy") << QLatin1String("MMM dd hh:mm") << QLatin1String("MMM d yyyy")
<< QLatin1String("MMM d hh:mm") << QLatin1String("MMM d yyyy") << QLatin1String("MMM dd yyyy");
QString dateString = tokens.at(6);
dateString[0] = dateString[0].toUpper();
// Resolve the modification date by parsing all possible formats
QDateTime dateTime;
int n = 0;
#ifndef QT_NO_DATESTRING
do {
dateTime = QLocale::c().toDateTime(dateString, formats.at(n++));
} while (n < formats.size() && (!dateTime.isValid()));
#endif
if (n == 2 || n == 4) {
// Guess the year.
dateTime.setDate(QDate(QDate::currentDate().year(),
dateTime.date().month(),
dateTime.date().day()));
_q_fixupDateTime(&dateTime);
}
if (dateTime.isValid())
info->setLastModified(dateTime);
// Resolve permissions
int permissions = 0;
QString p = tokens.at(2);
permissions |= (p[0] == QLatin1Char('r') ? QUrlInfo::ReadOwner : 0);
permissions |= (p[1] == QLatin1Char('w') ? QUrlInfo::WriteOwner : 0);
permissions |= (p[2] == QLatin1Char('x') ? QUrlInfo::ExeOwner : 0);
permissions |= (p[3] == QLatin1Char('r') ? QUrlInfo::ReadGroup : 0);
permissions |= (p[4] == QLatin1Char('w') ? QUrlInfo::WriteGroup : 0);
permissions |= (p[5] == QLatin1Char('x') ? QUrlInfo::ExeGroup : 0);
permissions |= (p[6] == QLatin1Char('r') ? QUrlInfo::ReadOther : 0);
permissions |= (p[7] == QLatin1Char('w') ? QUrlInfo::WriteOther : 0);
permissions |= (p[8] == QLatin1Char('x') ? QUrlInfo::ExeOther : 0);
info->setPermissions(permissions);
bool isOwner = info->owner() == userName;
info->setReadable((permissions & QUrlInfo::ReadOther) || ((permissions & QUrlInfo::ReadOwner) && isOwner));
info->setWritable((permissions & QUrlInfo::WriteOther) || ((permissions & QUrlInfo::WriteOwner) && isOwner));
}
static void _q_parseDosDir(const QStringList &tokens, const QString &userName, QUrlInfo *info)
{
// DOS style, 3 + 1 entries
// 01-16-02 11:14AM <DIR> epsgroup
// 06-05-03 03:19PM 1973 readme.txt
if (tokens.size() != 4)
return;
Q_UNUSED(userName);
QString name = tokens.at(3);
info->setName(name);
info->setSymLink(name.toLower().endsWith(QLatin1String(".lnk")));
if (tokens.at(2) == QLatin1String("<DIR>")) {
info->setFile(false);
info->setDir(true);
} else {
info->setFile(true);
info->setDir(false);
info->setSize(tokens.at(2).toLongLong());
}
// Note: We cannot use QFileInfo; permissions are for the server-side
// machine, and QFileInfo's behavior depends on the local platform.
int permissions = QUrlInfo::ReadOwner | QUrlInfo::WriteOwner
| QUrlInfo::ReadGroup | QUrlInfo::WriteGroup
| QUrlInfo::ReadOther | QUrlInfo::WriteOther;
QString ext;
int extIndex = name.lastIndexOf(QLatin1Char('.'));
if (extIndex != -1)
ext = name.mid(extIndex + 1);
if (ext == QLatin1String("exe") || ext == QLatin1String("bat") || ext == QLatin1String("com"))
permissions |= QUrlInfo::ExeOwner | QUrlInfo::ExeGroup | QUrlInfo::ExeOther;
info->setPermissions(permissions);
info->setReadable(true);
info->setWritable(info->isFile());
QDateTime dateTime;
#ifndef QT_NO_DATESTRING
dateTime = QLocale::c().toDateTime(tokens.at(1), QLatin1String("MM-dd-yy hh:mmAP"));
if (dateTime.date().year() < 1971) {
dateTime.setDate(QDate(dateTime.date().year() + 100,
dateTime.date().month(),
dateTime.date().day()));
}
#endif
info->setLastModified(dateTime);
}
bool QFtpDTP::parseDir(const QByteArray &buffer, const QString &userName, QUrlInfo *info)
{
if (buffer.isEmpty())
return false;
QString bufferStr = QString::fromLatin1(buffer).trimmed();
// Unix style FTP servers
QRegExp unixPattern(QLatin1String("^([\\-dl])([a-zA-Z\\-]{9,9})\\s+\\d+\\s+(\\S*)\\s+"
"(\\S*)\\s+(\\d+)\\s+(\\S+\\s+\\S+\\s+\\S+)\\s+(\\S.*)"));
if (unixPattern.indexIn(bufferStr) == 0) {
_q_parseUnixDir(unixPattern.capturedTexts(), userName, info);
return true;
}
// DOS style FTP servers
QRegExp dosPattern(QLatin1String("^(\\d\\d-\\d\\d-\\d\\d\\d?\\d?\\ \\ \\d\\d:\\d\\d[AP]M)\\s+"
"(<DIR>|\\d+)\\s+(\\S.*)$"));
if (dosPattern.indexIn(bufferStr) == 0) {
_q_parseDosDir(dosPattern.capturedTexts(), userName, info);
return true;
}
// Unsupported
return false;
}
void QFtpDTP::socketConnected()
{
bytesDone = 0;
#if defined(QFTPDTP_DEBUG)
qDebug("QFtpDTP::connectState(CsConnected)");
#endif
emit connectState(QFtpDTP::CsConnected);
}
void QFtpDTP::socketReadyRead()
{
if (!socket)
return;
if (pi->currentCommand().isEmpty()) {
socket->close();
#if defined(QFTPDTP_DEBUG)
qDebug("QFtpDTP::connectState(CsClosed)");
#endif
emit connectState(QFtpDTP::CsClosed);
return;
}
if (pi->abortState == QFtpPI::AbortStarted) {
// discard data
socket->readAll();
return;
}
if (pi->currentCommand().startsWith(QLatin1String("LIST"))) {
while (socket->canReadLine()) {
QUrlInfo i;
QByteArray line = socket->readLine();
#if defined(QFTPDTP_DEBUG)
qDebug("QFtpDTP read (list): '%s'", line.constData());
#endif
if (parseDir(line, QLatin1String(""), &i)) {
emit listInfo(i);
} else {
// some FTP servers don't return a 550 if the file or directory
// does not exist, but rather write a text to the data socket
// -- try to catch these cases
if (line.endsWith("No such file or directory\r\n"))
err = QString::fromLatin1(line);
}
}
} else {
if (!is_ba && data.dev) {
do {
QByteArray ba;
ba.resize(socket->bytesAvailable());
qint64 bytesRead = socket->read(ba.data(), ba.size());
if (bytesRead < 0) {
// a read following a readyRead() signal will
// never fail.
return;
}
ba.resize(bytesRead);
bytesDone += bytesRead;
#if defined(QFTPDTP_DEBUG)
qDebug("QFtpDTP read: %lli bytes (total %lli bytes)", bytesRead, bytesDone);
#endif
if (data.dev) // make sure it wasn't deleted in the slot
data.dev->write(ba);
emit dataTransferProgress(bytesDone, bytesTotal);
// Need to loop; dataTransferProgress is often connected to
// slots that update the GUI (e.g., progress bar values), and
// if events are processed, more data may have arrived.
} while (socket->bytesAvailable());
} else {
#if defined(QFTPDTP_DEBUG)
qDebug("QFtpDTP readyRead: %lli bytes available (total %lli bytes read)",
bytesAvailable(), bytesDone);
#endif
emit dataTransferProgress(bytesDone+socket->bytesAvailable(), bytesTotal);
emit readyRead();
}
}
}
void QFtpDTP::socketError(QAbstractSocket::SocketError e)
{
if (e == QTcpSocket::HostNotFoundError) {
#if defined(QFTPDTP_DEBUG)
qDebug("QFtpDTP::connectState(CsHostNotFound)");
#endif
emit connectState(QFtpDTP::CsHostNotFound);
} else if (e == QTcpSocket::ConnectionRefusedError) {
#if defined(QFTPDTP_DEBUG)
qDebug("QFtpDTP::connectState(CsConnectionRefused)");
#endif
emit connectState(QFtpDTP::CsConnectionRefused);
}
}
void QFtpDTP::socketConnectionClosed()
{
if (!is_ba && data.dev) {
clearData();
}
if (socket && socket->state() == QTcpSocket::ConnectedState)
{
bytesFromSocket = socket->readAll();
}
#if defined(QFTPDTP_DEBUG)
qDebug("QFtpDTP::connectState(CsClosed)");
#endif
emit connectState(QFtpDTP::CsClosed);
}
void QFtpDTP::socketBytesWritten(qint64 bytes)
{
bytesDone += bytes;
#if defined(QFTPDTP_DEBUG)
qDebug("QFtpDTP::bytesWritten(%lli)", bytesDone);
#endif
emit dataTransferProgress(bytesDone, bytesTotal);
if (callWriteData)
writeData();
}
void QFtpDTP::setupSocket()
{
socket = listener.nextPendingConnection();
socket->setObjectName(QLatin1String("QFtpDTP Active state socket"));
connect(socket, SIGNAL(connected()), SLOT(socketConnected()));
connect(socket, SIGNAL(readyRead()), SLOT(socketReadyRead()));
connect(socket, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(socketError(QAbstractSocket::SocketError)));
connect(socket, SIGNAL(disconnected()), SLOT(socketConnectionClosed()));
connect(socket, SIGNAL(bytesWritten(qint64)), SLOT(socketBytesWritten(qint64)));
listener.close();
}
void QFtpDTP::clearData()
{
is_ba = false;
data.dev = 0;
}
/**********************************************************************
*
* QFtpPI implemenatation
*
*********************************************************************/
QFtpPI::QFtpPI(QObject *parent) :
QObject(parent),
rawCommand(false),
transferConnectionExtended(true),
dtp(this),
commandSocket(0),
state(Begin), abortState(None),
currentCmd(QString()),
waitForDtpToConnect(false),
waitForDtpToClose(false)
{
commandSocket.setObjectName(QLatin1String("QFtpPI_socket"));
connect(&commandSocket, SIGNAL(hostFound()),
SLOT(hostFound()));
connect(&commandSocket, SIGNAL(connected()),
SLOT(connected()));
connect(&commandSocket, SIGNAL(disconnected()),
SLOT(connectionClosed()));
connect(&commandSocket, SIGNAL(readyRead()),
SLOT(readyRead()));
connect(&commandSocket, SIGNAL(error(QAbstractSocket::SocketError)),
SLOT(error(QAbstractSocket::SocketError)));
connect(&dtp, SIGNAL(connectState(int)),
SLOT(dtpConnectState(int)));
}
void QFtpPI::connectToHost(const QString &host, quint16 port)
{
emit connectState(QFtp::HostLookup);
#ifndef QT_NO_BEARERMANAGEMENT
//copy network session down to the socket & DTP
commandSocket.setProperty("_q_networksession", property("_q_networksession"));
dtp.setProperty("_q_networksession", property("_q_networksession"));
#endif
commandSocket.connectToHost(host, port);
}
/*
Sends the sequence of commands \a cmds to the FTP server. When the commands
are all done the finished() signal is emitted. When an error occurs, the
error() signal is emitted.
If there are pending commands in the queue this functions returns false and
the \a cmds are not added to the queue; otherwise it returns true.
*/
bool QFtpPI::sendCommands(const QStringList &cmds)
{
if (!pendingCommands.isEmpty())
return false;
if (commandSocket.state() != QTcpSocket::ConnectedState || state!=Idle) {
emit error(QFtp::NotConnected, QFtp::tr("Not connected"));
return true; // there are no pending commands
}
pendingCommands = cmds;
startNextCmd();
return true;
}
void QFtpPI::clearPendingCommands()
{
pendingCommands.clear();
dtp.abortConnection();
currentCmd.clear();
state = Idle;
}
void QFtpPI::abort()
{
pendingCommands.clear();
if (abortState != None)
// ABOR already sent
return;
abortState = AbortStarted;
#if defined(QFTPPI_DEBUG)
qDebug("QFtpPI send: ABOR");
#endif
commandSocket.write("ABOR\r\n", 6);
if (currentCmd.startsWith(QLatin1String("STOR ")))
dtp.abortConnection();
}
void QFtpPI::hostFound()
{
emit connectState(QFtp::Connecting);
}
void QFtpPI::connected()
{
state = Begin;
#if defined(QFTPPI_DEBUG)
// qDebug("QFtpPI state: %d [connected()]", state);
#endif
// try to improve performance by setting TCP_NODELAY
commandSocket.setSocketOption(QAbstractSocket::LowDelayOption, 1);
emit connectState(QFtp::Connected);
}
void QFtpPI::connectionClosed()
{
commandSocket.close();
emit connectState(QFtp::Unconnected);
}
void QFtpPI::delayedCloseFinished()
{
emit connectState(QFtp::Unconnected);
}
void QFtpPI::error(QAbstractSocket::SocketError e)
{
if (e == QTcpSocket::HostNotFoundError) {
emit connectState(QFtp::Unconnected);
emit error(QFtp::HostNotFound,
QFtp::tr("Host %1 not found").arg(commandSocket.peerName()));
} else if (e == QTcpSocket::ConnectionRefusedError) {
emit connectState(QFtp::Unconnected);
emit error(QFtp::ConnectionRefused,
QFtp::tr("Connection refused to host %1").arg(commandSocket.peerName()));
} else if (e == QTcpSocket::SocketTimeoutError) {
emit connectState(QFtp::Unconnected);
emit error(QFtp::ConnectionRefused,
QFtp::tr("Connection timed out to host %1").arg(commandSocket.peerName()));
}
}
void QFtpPI::readyRead()
{
if (waitForDtpToClose)
return;
while (commandSocket.canReadLine()) {
// read line with respect to line continuation
QString line = QString::fromLatin1(commandSocket.readLine());
if (replyText.isEmpty()) {
if (line.length() < 3) {
// protocol error
return;
}
const int lowerLimit[3] = {1,0,0};
const int upperLimit[3] = {5,5,9};
for (int i=0; i<3; i++) {
replyCode[i] = line[i].digitValue();
if (replyCode[i]<lowerLimit[i] || replyCode[i]>upperLimit[i]) {
// protocol error
return;
}
}
}
QString endOfMultiLine;
endOfMultiLine.resize(4);
endOfMultiLine[0] = '0' + replyCode[0];
endOfMultiLine[1] = '0' + replyCode[1];
endOfMultiLine[2] = '0' + replyCode[2];
endOfMultiLine[3] = QLatin1Char(' ');
QString lineCont(endOfMultiLine);
lineCont[3] = QLatin1Char('-');
QString lineLeft4 = line.left(4);
while (lineLeft4 != endOfMultiLine) {
if (lineLeft4 == lineCont)
replyText += line.mid(4); // strip 'xyz-'
else
replyText += line;
if (!commandSocket.canReadLine())
return;
line = QString::fromLatin1(commandSocket.readLine());
lineLeft4 = line.left(4);
}
replyText += line.mid(4); // strip reply code 'xyz '
if (replyText.endsWith(QLatin1String("\r\n")))
replyText.chop(2);
if (processReply())
replyText = QLatin1String("");
}
}
/*
Process a reply from the FTP server.
Returns true if the reply was processed or false if the reply has to be
processed at a later point.
*/
bool QFtpPI::processReply()
{
#if defined(QFTPPI_DEBUG)
// qDebug("QFtpPI state: %d [processReply() begin]", state);
if (replyText.length() < 400)
qDebug("QFtpPI recv: %d %s", 100*replyCode[0]+10*replyCode[1]+replyCode[2], replyText.toLatin1().constData());
else
qDebug("QFtpPI recv: %d (text skipped)", 100*replyCode[0]+10*replyCode[1]+replyCode[2]);
#endif
int replyCodeInt = 100*replyCode[0] + 10*replyCode[1] + replyCode[2];
// process 226 replies ("Closing Data Connection") only when the data
// connection is really closed to avoid short reads of the DTP
if (replyCodeInt == 226 || (replyCodeInt == 250 && currentCmd.startsWith(QLatin1String("RETR")))) {
if (dtp.state() != QTcpSocket::UnconnectedState) {
waitForDtpToClose = true;
return false;