Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathftpcontrolconnection.cpp
More file actions
743 lines (673 loc) · 17.1 KB
/
Copy pathftpcontrolconnection.cpp
File metadata and controls
743 lines (673 loc) · 17.1 KB
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
#include "ftpcontrolconnection.h"
#include "ftplistcommand.h"
#include "ftpretrcommand.h"
#include "ftpstorcommand.h"
#include "sslserver.h"
#include "dataconnection.h"
#include <QFileInfo>
#include <QDateTime>
#include <QDir>
#include <QStringList>
#include <QDir>
#include <QEventLoop>
#include <QDebug>
#include <QTimer>
#include <QSslSocket>
#include <QTextCodec>
FtpControlConnection::FtpControlConnection(QObject *parent, QSslSocket *socket, const QString &rootPath, const QString &userName, const QString &password, bool readOnly) :
QObject(parent)
{
this->m_socket = socket;
this->m_userName = userName;
this->m_password = password;
this->m_rootPath = rootPath;
this->m_readOnly = readOnly;
m_isLoggedIn = false;
m_encryptDataConnection = false;
socket->setParent(this);
connect(socket, SIGNAL(readyRead()), this, SLOT(acceptNewData()));
connect(socket, SIGNAL(disconnected()), this, SLOT(deleteLater())); // socket disconnected后析构FtpControlConnection
connect(socket, &QSslSocket::disconnected, [this, socket]() {
emit connectionClosed(socket->peerAddress().toString());
});
m_currentDirectory = "/";
m_dataConnection = new DataConnection(this);
reply("220 Welcome to FtpServer.");
qDebug() << "FtpControlConnection()";
}
FtpControlConnection::~FtpControlConnection()
{
qDebug() << "~FtpControlConnection()";
}
bool isGBK(unsigned char* data, int len)
{
int i = 0;
while (i < len)
{
if (data[i] <= 0x7f)
{
//编码小于等于127,只有一个字节的编码,兼容ASCII
i++;
continue;
}
else
{
//大于127的使用双字节编码
if (data[i] >= 0x81 &&
data[i] <= 0xfe &&
data[i + 1] >= 0x40 &&
data[i + 1] <= 0xfe &&
data[i + 1] != 0xf7)
{
i += 2;
continue;
}
else
{
return false;
}
}
}
return true;
}
bool is_str_utf8(const char* str)
{
unsigned int nBytes = 0;//UFT8可用1-6个字节编码,ASCII用一个字节
unsigned char chr = *str;
bool bAllAscii = true;
for (unsigned int i = 0; str[i] != '\0'; ++i)
{
chr = *(str + i);
//判断是否ASCII编码,如果不是,说明有可能是UTF8,ASCII用7位编码,最高位标记为0,0xxxxxxx
if (nBytes == 0 && (chr & 0x80) != 0)
{
bAllAscii = false;
}
if (nBytes == 0)
{
//如果不是ASCII码,应该是多字节符,计算字节数
if (chr >= 0x80)
{
if (chr >= 0xFC && chr <= 0xFD)
{
nBytes = 6;
}
else if (chr >= 0xF8)
{
nBytes = 5;
}
else if (chr >= 0xF0)
{
nBytes = 4;
}
else if (chr >= 0xE0)
{
nBytes = 3;
}
else if (chr >= 0xC0)
{
nBytes = 2;
}
else
{
return false;
}
nBytes--;
}
}
else
{
//多字节符的非首字节,应为 10xxxxxx
if ((chr & 0xC0) != 0x80)
{
return false;
}
//减到为零为止
nBytes--;
}
}
//违返UTF8编码规则
if (nBytes != 0)
{
return false;
}
if (bAllAscii)
{ //如果全部都是ASCII, 也是UTF8
return true;
}
return true;
}
bool is_str_gbk(const char* str)
{
unsigned int nBytes = 0;//GBK可用1-2个字节编码,中文两个 ,英文一个
unsigned char chr = *str;
bool bAllAscii = true; //如果全部都是ASCII,
for (unsigned int i = 0; str[i] != '\0'; ++i)
{
chr = *(str + i);
if ((chr & 0x80) != 0 && nBytes == 0)
{// 判断是否ASCII编码,如果不是,说明有可能是GBK
bAllAscii = false;
}
if (nBytes == 0)
{
if (chr >= 0x80)
{
if (chr >= 0x81 && chr <= 0xFE)
{
nBytes = +2;
}
else
{
return false;
}
nBytes--;
}
}
else
{
if (chr < 0x40 || chr>0xFE)
{
return false;
}
nBytes--;
}//else end
}
if (nBytes != 0)
{ //违返规则
return false;
}
if (bAllAscii)
{ //如果全部都是ASCII, 也是GBK
return true;
}
return true;
}
void FtpControlConnection::acceptNewData()
{
if (!m_socket->canReadLine())
{
return;
}
// Note how we execute only one line, and use QTimer::singleShot, instead
// of using a for-loop until no more lines are available. This is done
// so we don't block the event loop for a long time.
QByteArray ba = m_socket->readLine().trimmed();
//qDebug() << "socket read: " << ba;
//qDebug() << "from local8bit: " << QString::fromLocal8Bit(ba);
QTextCodec::ConverterState state;
QTextCodec *codec = QTextCodec::codecForName("UTF-8");
QString text = codec->toUnicode(ba.constData(), ba.size(), &state);
if (state.invalidChars > 0)
{
qDebug() << "It is gbk";
processCommand(QString::fromLocal8Bit(ba));
}
else
{
//qDebug() << "It is Utf8";
processCommand(text);
}
QTimer::singleShot(0, this, SLOT(acceptNewData()));
}
void FtpControlConnection::disconnectFromHost()
{
m_socket->disconnectFromHost();
}
bool FtpControlConnection::verifyAuthentication(const QString &command)
{
if (m_isLoggedIn)
{
return true;
}
// cmd ftp在登录之前就会发送OPTS UTF8 ON命令,所以注释掉,避免cmd使用gbk编码导致中文乱码
const char *commandsRequiringAuth[] =
{
"PWD", "CWD", "TYPE", "PORT", "PASV", "LIST", "RETR", "REST",
"NLST", "SIZE", "SYST", "PROT", "CDUP", /*"OPTS",*/ "PBSZ", "NOOP",
"STOR", "MKD", "RMD", "DELE", "RNFR", "RNTO", "APPE",
"XPWD"
};
for (size_t ii = 0; ii < sizeof(commandsRequiringAuth)/sizeof(commandsRequiringAuth[0]); ++ii)
{
if (command == commandsRequiringAuth[ii])
{
reply("530 You must log in first.");
return false;
}
}
return true;
}
bool FtpControlConnection::verifyWritePermission(const QString &command)
{
if (!m_readOnly)
{
return true;
}
const char *commandsRequiringWritePermission[] =
{
"STOR", "MKD", "RMD", "DELE", "RNFR", "RNTO", "APPE"
};
for (size_t ii = 0; ii < sizeof(commandsRequiringWritePermission)/sizeof(commandsRequiringWritePermission[0]); ++ii)
{
if (command == commandsRequiringWritePermission[ii])
{
reply("550 Can't do that in read-only mode.");
return false;
}
}
return true;
}
QString FtpControlConnection::stripFlagL(const QString &fileName)
{
QString a = fileName.toUpper();
if (a == "-L")
{
return "";
}
if (a.startsWith("-L "))
{
return fileName.mid(3);
}
return fileName;
}
void FtpControlConnection::parseCommand(const QString &entireCommand, QString *command, QString *commandParameters)
{
// Split parameters and command.
int pos = entireCommand.indexOf(' ');
if (-1 != pos)
{
*command = entireCommand.left(pos).trimmed().toUpper();
*commandParameters = entireCommand.mid(pos+1).trimmed();
} else
{
*command = entireCommand.trimmed().toUpper();
}
}
QString FtpControlConnection::toLocalPath(const QString &fileName) const
{
QString localPath = fileName;
// Some FTP clients send backslashes.
localPath.replace('\\', '/');
// If this is a relative path, we prepend the current directory.
if (!localPath.startsWith('/'))
{
localPath = m_currentDirectory + '/' + localPath;
}
// Evaluate all the ".." and ".", "/path/././to/dir/../.." becomes "/path".
// Note we do this **before** prepending the root path, in order to avoid
// "jailbreaking" out of the "chroot".
QStringList components;
foreach (const QString &component, localPath.split('/', QString::SkipEmptyParts))
{
if (component == "..")
{
if (!components.isEmpty())
{
components.pop_back();
}
}
else if (component != ".")
{
components += component;
}
}
// Prepend the root path.
localPath = QDir::cleanPath(m_rootPath + '/' + components.join("/"));
qDebug() << "to local path" << fileName << "->" << localPath;
return localPath;
}
void FtpControlConnection::reply(const QString &replyCode)
{
qDebug() << "reply" << replyCode;
m_socket->write((replyCode + "\r\n").toUtf8());
}
void FtpControlConnection::processCommand(const QString &entireCommand)
{
if (!entireCommand.contains("PASS"))
{
qDebug() << "command" << entireCommand;
}
else
{
qDebug() << "command \"PASS XXX\"";
}
QString command;
QString commandParameters;
parseCommand(entireCommand, &command, &commandParameters);
if (!verifyAuthentication(command))
{
return;
}
if (!verifyWritePermission(command))
{
return;
}
if ("USER" == command)
{
reply("331 User name OK, need password.");
}
else if ("PASS" == command)
{
pass(commandParameters);
}
else if ("QUIT" == command)
{
quit();
}
else if ("AUTH" == command && "TLS" == commandParameters.toUpper())
{
auth();
}
else if ("FEAT" == command)
{
feat();
}
else if ("PWD" == command || "XPWD" == command)
{
reply(QString("257 \"%1\"").arg(m_currentDirectory));
}
else if ("CWD" == command)
{
cwd(commandParameters);
}
else if ("TYPE" == command)
{
reply("200 Command okay.");
}
else if ("PORT" == command)
{
port(commandParameters);
}
else if ("PASV" == command)
{
pasv();
}
else if ("LIST" == command)
{
list(toLocalPath(stripFlagL(commandParameters)), false);
}
else if ("RETR" == command)
{
retr(toLocalPath(commandParameters));
}
else if ("REST" == command)
{
reply("350 Requested file action pending further information.");
}
else if ("NLST" == command)
{
list(toLocalPath(stripFlagL(commandParameters)), true);
}
else if ("SIZE" == command)
{
size(toLocalPath(commandParameters));
}
else if ("SYST" == command)
{
reply("215 Windows");
}
else if ("PROT" == command)
{
prot(commandParameters.toUpper());
}
else if ("CDUP" == command)
{
cdup();
}
else if ("OPTS" == command && "UTF8 ON" == commandParameters.toUpper())
{
reply("200 Command okay.");
}
else if ("PBSZ" == command && "0" == commandParameters.toUpper())
{
reply("200 Command okay.");
}
else if ("NOOP" == command)
{
reply("200 Command okay.");
}
else if ("STOR" == command)
{
stor(toLocalPath(commandParameters));
}
else if ("MKD" == command)
{
mkd(toLocalPath(commandParameters));
}
else if ("RMD" == command)
{
rmd(toLocalPath(commandParameters));
}
else if ("DELE" == command)
{
dele(toLocalPath(commandParameters));
}
else if ("RNFR" == command)
{
reply("350 Requested file action pending further information.");
}
else if ("RNTO" == command)
{
rnto(toLocalPath(commandParameters));
}
else if ("APPE" == command)
{
stor(toLocalPath(commandParameters), true);
}
else
{
reply("502 Command not implemented.");
}
m_lastProcessedCommand = entireCommand;
}
void FtpControlConnection::startOrScheduleCommand(FtpCommand *ftpCommand)
{
connect(ftpCommand, SIGNAL(reply(QString)), this, SLOT(reply(QString)));
if (!m_dataConnection->setFtpCommand(ftpCommand))
{
delete ftpCommand;
reply("425 Can't open data connection.");
return;
}
}
void FtpControlConnection::port(const QString &addressAndPort)
{
// Example PORT command:
// PORT h1,h2,h3,h4,p1,p2
// Get IP and port.
QRegExp exp("\\s*(\\d+,\\d+,\\d+,\\d+),(\\d+),(\\d+)");
exp.indexIn(addressAndPort);
QString hostName = exp.cap(1).replace(',', '.');
int port = exp.cap(2).toInt() * 256 + exp.cap(3).toInt();
m_dataConnection->scheduleConnectToHost(hostName, port, m_encryptDataConnection);
reply("200 Command okay.");
}
void FtpControlConnection::pasv()
{
int port = m_dataConnection->listen(m_encryptDataConnection);
reply(QString("227 Entering Passive Mode (%1,%2,%3).").arg(m_socket->localAddress().toString().replace('.',',')).arg(port/256).arg(port%256));
}
void FtpControlConnection::list(const QString &dir, bool nameListOnly)
{
startOrScheduleCommand(new FtpListCommand(this, dir, nameListOnly));
}
void FtpControlConnection::retr(const QString &fileName)
{
startOrScheduleCommand(new FtpRetrCommand(this, fileName, seekTo()));
}
void FtpControlConnection::stor(const QString &fileName, bool appendMode)
{
startOrScheduleCommand(new FtpStorCommand(this, fileName, appendMode, seekTo()));
}
void FtpControlConnection::cwd(const QString &dir)
{
QFileInfo fi(toLocalPath(dir));
if (fi.exists() && fi.isDir())
{
QFileInfo fi(dir);
if (fi.isAbsolute())
{
m_currentDirectory = QDir::cleanPath(dir);
} else
{
m_currentDirectory = QDir::cleanPath(m_currentDirectory + '/' + dir);
}
reply("250 Requested file action okay, completed.");
}
else
{
if (!fi.isDir())
{
qWarning() << QStringLiteral("%1不是目录,cwd不执行").arg(dir);
reply("550 CWD failed. directory not found.");
}
else
{
reply("550 Requested action not taken; file unavailable.");
}
}
//if (!fi.exists())
//{
// reply("550 Requested action not taken; file unavailable.");
// return;
//}
//if (!fi.isDir())
//{
// reply("550 Requested action not taken; file unavailable.");
//}
}
void FtpControlConnection::mkd(const QString &dir)
{
if (QDir().mkdir(dir)) {
reply(QString("257 \"%1\" created.").arg(dir));
} else {
reply("550 Requested action not taken; file unavailable.");
}
}
void FtpControlConnection::rmd(const QString &dir)
{
if (QDir().rmdir(dir)) {
reply("250 Requested file action okay, completed.");
} else {
reply("550 Requested action not taken; file unavailable.");
}
}
void FtpControlConnection::dele(const QString &fileName)
{
if (QDir().remove(fileName)) {
reply("250 Requested file action okay, completed.");
} else {
reply("550 Requested action not taken; file unavailable.");
}
}
void FtpControlConnection::rnto(const QString &fileName)
{
QString command;
QString commandParameters;
parseCommand(m_lastProcessedCommand, &command, &commandParameters);
if ("RNFR" == command && QDir().rename(toLocalPath(commandParameters), fileName))
{
reply("250 Requested file action okay, completed.");
} else
{
reply("550 Requested action not taken; file unavailable.");
}
}
void FtpControlConnection::quit()
{
reply("221 Quitting...");
// If we have a running download or upload, we will wait until it's
// finished before closing the control connection.
if (m_dataConnection->ftpCommand())
{
connect(m_dataConnection->ftpCommand(), SIGNAL(destroyed()), this, SLOT(disconnectFromHost()));
} else
{
disconnectFromHost();
}
}
void FtpControlConnection::size(const QString &fileName)
{
QFileInfo fi(fileName);
if (!fi.exists() || fi.isDir())
{
reply("550 Requested action not taken; file unavailable.");
}
else
{
reply(QString("213 %1").arg(fi.size()));
}
}
void FtpControlConnection::pass(const QString &password)
{
QString command;
QString commandParameters;
parseCommand(m_lastProcessedCommand, &command, &commandParameters);
if (this->m_password.isEmpty() || ("USER" == command && this->m_userName == commandParameters && this->m_password == password))
{
reply("230 You are logged in.");
m_isLoggedIn = true;
}
else
{
reply("530 User name or password was incorrect.");
}
}
void FtpControlConnection::auth()
{
reply("234 Initializing SSL connection.");
SslServer::setLocalCertificateAndPrivateKey(m_socket);
m_socket->startServerEncryption();
}
void FtpControlConnection::prot(const QString &protectionLevel)
{
if ("C" == protectionLevel)
{
m_encryptDataConnection = false;
}
else if ("P" == protectionLevel)
{
m_encryptDataConnection = true;
}
else
{
reply("502 Command not implemented.");
return;
}
reply("200 Command okay.");
}
void FtpControlConnection::cdup()
{
if ("/" == m_currentDirectory)
{
reply("250 Requested file action okay, completed.");
}
else
{
cwd("..");
}
}
void FtpControlConnection::feat()
{
// We only report that we support UTF8 file names, this is needed because
// some clients will assume that we use ASCII otherwise, and will not
// encode the filenames properly.
m_socket->write(
"211-Features:\r\n"
" UTF8\r\n"
"211 End\r\n"
);
}
qint64 FtpControlConnection::seekTo()
{
qint64 seekTo = 0;
QString command;
QString commandParameters;
parseCommand(m_lastProcessedCommand, &command, &commandParameters);
if ("REST" == command)
{
QTextStream(commandParameters.toUtf8()) >> seekTo;
}
return seekTo;
}
You can’t perform that action at this time.
