Repository navigation
Expand file tree
/
Copy pathsftpclient.cpp
More file actions
1576 lines (1427 loc) · 49.7 KB
/
Copy pathsftpclient.cpp
File metadata and controls
1576 lines (1427 loc) · 49.7 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
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
#include "sftpclient.h"
#include <QAbstractSocket>
#include <QDateTime>
#include <QDebug>
#include <QElapsedTimer>
#include <QFile>
#include <QFileInfo>
#include <QHostAddress>
#include <QHostInfo>
#include <QQueue>
#include <QSocketNotifier>
#include <cstring>
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
namespace {
const int kBufferSize = 1024 * 1024;
const int kIoTimeoutMs = 10000;
const int kMaxTimeouts = 3;
const int kConnectTimeoutSeconds = 30;
// 进度上报间隔与速率统计窗口。
const int kProgressIntervalMs = 100;
const int kRateWindowMs = 1500;
// 取消检查粒度:runWithRetry() 把 socket 等待切这么长,保证点击“取消”后
// 最多 kCancelPollMs 就能从 select() 里出来,同时不改变整体超时语义。
const int kCancelPollMs = 200;
// 滑动窗口速率计。
//
// 只保留最近 kRateWindowMs 内的 (时间戳, 累计字节) 采样,用首尾差值算平均
// 速率:既比单次瞬时值平稳,又不会像"总字节 / 总耗时"那样在传输后期对速度
// 变化完全无反应。样本数在 100ms 节流下最多十几个。
class RateMeter {
public:
void reset() {
clock_.invalidate();
samples_.clear();
}
void addSample(qint64 totalBytes) {
if (!clock_.isValid()) {
clock_.start();
}
const qint64 now = clock_.elapsed();
samples_.enqueue(qMakePair(now, totalBytes));
while (samples_.size() > 2 && now - samples_.first().first > kRateWindowMs) {
samples_.dequeue();
}
}
// 返回 < 0 表示样本不足,还算不出速率。
qint64 bytesPerSecond() const {
if (samples_.size() < 2) {
return -1;
}
const qint64 elapsedMs = samples_.last().first - samples_.first().first;
if (elapsedMs <= 0) {
return -1;
}
const qint64 bytes = samples_.last().second - samples_.first().second;
return bytes * 1000 / elapsedMs;
}
private:
QElapsedTimer clock_;
QQueue<QPair<qint64, qint64>> samples_;
};
// libssh2 的全局初始化只需要执行一次。
bool ensureLibssh2Initialized() {
static const int initResult = libssh2_init(0);
return initResult == 0;
}
int socketLastError() {
#ifdef WIN32
return WSAGetLastError();
#else
return errno;
#endif
}
QString socketErrorString(int error) {
#ifdef WIN32
return QStringLiteral("socket 错误 %1").arg(error);
#else
return QString::fromLocal8Bit(std::strerror(error));
#endif
}
#ifdef WIN32
const int kConnectionRefused = WSAECONNREFUSED;
const int kConnectionTimedOut = WSAETIMEDOUT;
const int kNetworkUnreachable = WSAENETUNREACH;
const int kHostUnreachable = WSAEHOSTUNREACH;
const int kConnectionReset = WSAECONNRESET;
const int kAccessDenied = WSAEACCES;
#else
const int kConnectionRefused = ECONNREFUSED;
const int kConnectionTimedOut = ETIMEDOUT;
const int kNetworkUnreachable = ENETUNREACH;
const int kHostUnreachable = EHOSTUNREACH;
const int kConnectionReset = ECONNRESET;
const int kAccessDenied = EACCES;
#endif
void describeSocketFailure(int error, QString *reason, QString *hint) {
switch (error) {
case kConnectionRefused:
*reason = QStringLiteral("连接被拒绝");
*hint = QStringLiteral(
"目标端口没有 SSH/SFTP 服务在监听。请确认 sshd 已启动、端口号正确,"
"并检查服务器防火墙是否放行。");
break;
case kConnectionTimedOut:
*reason = QStringLiteral("连接超时");
*hint = QStringLiteral(
"目标主机在限定时间内没有响应。请检查网络连通性、防火墙规则,"
"或确认端口是否开放。");
break;
case kNetworkUnreachable:
*reason = QStringLiteral("网络不可达");
*hint = QStringLiteral(
"本机没有通往目标主机的路由。请检查网络、VPN 或代理设置。");
break;
case kHostUnreachable:
*reason = QStringLiteral("主机不可达");
*hint = QStringLiteral(
"目标主机无法访问。请确认地址是否正确、主机是否在线。");
break;
case kConnectionReset:
*reason = QStringLiteral("连接被重置");
*hint = QStringLiteral(
"连接被目标主机或中间网络设备中断,请稍后重试。");
break;
case kAccessDenied:
*reason = QStringLiteral("没有权限建立连接");
*hint = QStringLiteral("本机防火墙或安全策略拒绝了该连接。");
break;
default:
*reason = QStringLiteral("网络连接失败");
*hint = QStringLiteral("请检查主机地址、端口和网络设置后重试。");
break;
}
}
void describeHandshakeFailure(int rc, const QString &sessionText,
QString *reason, QString *hint) {
if (rc == -1 || rc == LIBSSH2_ERROR_TIMEOUT ||
rc == LIBSSH2_ERROR_SOCKET_TIMEOUT) {
*reason = QStringLiteral("SSH 握手超时");
*hint = QStringLiteral(
"服务器没有在限定时间内完成 SSH 协议握手,请检查网络状况和服务器负载。");
} else if (rc == LIBSSH2_ERROR_KEX_FAILURE ||
rc == LIBSSH2_ERROR_KEY_EXCHANGE_FAILURE ||
rc == LIBSSH2_ERROR_ALGO_UNSUPPORTED) {
*reason = QStringLiteral("SSH 加密算法不兼容");
*hint = QStringLiteral(
"客户端与服务器没有共同支持的密钥交换或加密算法,"
"请升级客户端/服务器,或调整服务器 sshd 的算法配置。");
} else if (rc == LIBSSH2_ERROR_BANNER_RECV ||
rc == LIBSSH2_ERROR_BANNER_SEND ||
rc == LIBSSH2_ERROR_PROTO ||
sessionText.contains(QStringLiteral("banner"),
Qt::CaseInsensitive)) {
*reason = QStringLiteral("目标端口不是 SSH 服务");
*hint = QStringLiteral(
"服务器返回了无法识别的数据。请确认端口号(默认 22)指向的是 SSH 服务,"
"而不是 HTTP、VNC 等其他服务。");
} else if (rc == LIBSSH2_ERROR_SOCKET_DISCONNECT ||
rc == LIBSSH2_ERROR_SOCKET_RECV) {
*reason = QStringLiteral("服务器中断了连接");
*hint = QStringLiteral(
"连接在握手阶段被关闭,服务器可能限制了来源 IP 或并发连接数。");
} else {
*reason = QStringLiteral("SSH 协议握手失败");
*hint = QStringLiteral(
"请确认目标端口运行的是 SSH 服务,并检查服务器与客户端的加密算法配置。");
}
}
void describePasswordAuthFailure(int rc, QString *reason, QString *hint) {
switch (rc) {
case LIBSSH2_ERROR_AUTHENTICATION_FAILED:
*reason = QStringLiteral("用户名或密码错误");
*hint = QStringLiteral(
"请核对用户名和密码;若服务器只允许公钥登录,请改用密钥认证。");
break;
case LIBSSH2_ERROR_PASSWORD_EXPIRED:
*reason = QStringLiteral("密码已过期");
*hint = QStringLiteral("请先在服务器上更新密码后再连接。");
break;
case LIBSSH2_ERROR_METHOD_NOT_SUPPORTED:
case LIBSSH2_ERROR_METHOD_NONE:
*reason = QStringLiteral("服务器不接受密码认证");
*hint = QStringLiteral(
"该账号可能只允许公钥登录,请在连接配置中改用密钥认证。");
break;
case LIBSSH2_ERROR_SOCKET_DISCONNECT:
*reason = QStringLiteral("服务器中断了连接");
*hint = QStringLiteral(
"认证过程中连接被关闭,服务器可能限制了登录尝试次数或来源 IP。");
break;
case -1:
*reason = QStringLiteral("认证过程中网络无响应");
*hint = QStringLiteral("请检查网络连接后重试。");
break;
case LIBSSH2_ERROR_TIMEOUT:
case LIBSSH2_ERROR_SOCKET_TIMEOUT:
*reason = QStringLiteral("身份认证超时");
*hint = QStringLiteral("服务器没有及时响应认证请求,请检查网络状况后重试。");
break;
default:
*reason = QStringLiteral("身份认证失败");
*hint = QStringLiteral("请检查用户名、密码以及服务器的认证配置。");
break;
}
}
void describePublicKeyAuthFailure(int rc, QString *reason, QString *hint) {
switch (rc) {
case LIBSSH2_ERROR_AUTHENTICATION_FAILED:
case LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED:
*reason = QStringLiteral("公钥认证失败");
*hint = QStringLiteral(
"请确认公钥已添加到服务器 ~/.ssh/authorized_keys,"
"且使用的私钥与公钥匹配。");
break;
case LIBSSH2_ERROR_FILE:
case LIBSSH2_ERROR_KEYFILE_AUTH_FAILED:
*reason = QStringLiteral("密钥文件无法使用");
*hint = QStringLiteral(
"请检查公钥/私钥路径、文件权限,以及私钥口令是否正确。");
break;
case LIBSSH2_ERROR_PUBLICKEY_PROTOCOL:
*reason = QStringLiteral("密钥格式不受支持");
*hint = QStringLiteral(
"请使用 OpenSSH 格式的密钥,或先将私钥转换为 PEM 格式。");
break;
case LIBSSH2_ERROR_METHOD_NOT_SUPPORTED:
case LIBSSH2_ERROR_METHOD_NONE:
*reason = QStringLiteral("服务器不接受公钥认证");
*hint = QStringLiteral("请确认服务器 sshd 已启用 PublicKeyAuthentication。");
break;
case LIBSSH2_ERROR_SOCKET_DISCONNECT:
*reason = QStringLiteral("服务器中断了连接");
*hint = QStringLiteral(
"认证过程中连接被关闭,服务器可能限制了登录尝试次数或来源 IP。");
break;
case -1:
*reason = QStringLiteral("认证过程中网络无响应");
*hint = QStringLiteral("请检查网络连接后重试。");
break;
case LIBSSH2_ERROR_TIMEOUT:
case LIBSSH2_ERROR_SOCKET_TIMEOUT:
*reason = QStringLiteral("身份认证超时");
*hint = QStringLiteral("服务器没有及时响应认证请求,请检查网络状况后重试。");
break;
default:
*reason = QStringLiteral("公钥认证失败");
*hint = QStringLiteral("请检查密钥配置,并查看服务器 sshd 的认证日志。");
break;
}
}
} // namespace
SFTPClient::SFTPClient(const ConnectInfo &info)
: QThread(), connectInfo(info) {
qRegisterMetaType<FileInfo_S>("FileInfo_S");
qRegisterMetaType<QList<FileInfo_S>>("QList<FileInfo_S>");
QObject::connect(this, &SFTPClient::asyncSftpUpload, this,
&SFTPClient::sftpUpload);
QObject::connect(this, &SFTPClient::asyncSftpDownload, this,
&SFTPClient::sftpDownload);
QObject::connect(this, &SFTPClient::asyncScpUpload, this,
&SFTPClient::scpUpload);
QObject::connect(this, &SFTPClient::asyncScpDownload, this,
&SFTPClient::scpDownload);
QObject::connect(this, &SFTPClient::asyncOpendir, this, &SFTPClient::opendir);
this->moveToThread(this);
}
SFTPClient::~SFTPClient() { stop(); }
void SFTPClient::run() {
if (!ensureLibssh2Initialized()) {
reportConnectionFailure(
QStringLiteral("SSH 组件初始化失败"),
QStringLiteral("请重新启动应用;若问题依旧,请检查 libssh2 是否正确安装。"));
return;
}
if (!connectToHost() || stopRequested.load() || !openSession() ||
stopRequested.load() || !auth() || stopRequested.load() ||
!initSftpSession() || stopRequested.load()) {
cleanupSession();
return;
}
socketNotifier =
new QSocketNotifier(sock.load(), QSocketNotifier::Exception, this);
QObject::connect(socketNotifier, &QSocketNotifier::activated, this,
[this](int) {
if (socketNotifier) {
socketNotifier->setEnabled(false);
}
sessionReady.store(false);
emit disconnected();
// 连接已不可用,结束事件循环让 run() 清理会话。
quit();
});
exec();
if (socketNotifier) {
socketNotifier->setEnabled(false);
delete socketNotifier;
socketNotifier = nullptr;
}
sessionReady.store(false);
cleanupSession();
}
bool SFTPClient::connectToHost() {
if (stopRequested.load()) {
return false;
}
const QString hostName = connectInfo.hostName.trimmed();
if (hostName.isEmpty()) {
reportConnectionFailure(QStringLiteral("主机地址为空"),
QStringLiteral("请在连接配置中填写主机地址。"));
return false;
}
if (connectInfo.port <= 0 || connectInfo.port > 65535) {
reportConnectionFailure(
QStringLiteral("端口号无效"),
QStringLiteral("端口号必须在 1–65535 之间,SSH 默认端口是 22。"),
QStringLiteral("当前端口:%1").arg(connectInfo.port));
return false;
}
if (connectInfo.username.trimmed().isEmpty()) {
reportConnectionFailure(QStringLiteral("用户名为空"),
QStringLiteral("请在连接配置中填写登录用户名。"));
return false;
}
const int fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
const int error = socketLastError();
reportConnectionFailure(
QStringLiteral("无法创建网络连接"),
QStringLiteral("系统资源不足或网络栈异常,请稍后重试。"),
socketErrorString(error));
return false;
}
sock.store(fd);
int enable = 1;
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE,
reinterpret_cast<const char *>(&enable), sizeof(enable));
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<const char *>(&enable), sizeof(enable));
#ifdef Q_OS_UNIX
// 连接空闲 10 秒后开始探测,间隔 10 秒,探测 3 次。
int keepIdle = 10;
int keepInterval = 10;
int keepCount = 3;
#ifdef TCP_KEEPIDLE
setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keepIdle, sizeof(keepIdle));
#elif defined(TCP_KEEPALIVE)
setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &keepIdle, sizeof(keepIdle));
#endif
#ifdef TCP_KEEPINTVL
setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &keepInterval,
sizeof(keepInterval));
#endif
#ifdef TCP_KEEPCNT
setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &keepCount, sizeof(keepCount));
#endif
unsigned long nonBlocking = 1;
ioctl(fd, FIONBIO, &nonBlocking);
#else
u_long nonBlocking = 1;
ioctlsocket(fd, FIONBIO, &nonBlocking);
#endif
QHostAddress address;
if (!address.setAddress(hostName)) {
const QHostInfo hostInfo = QHostInfo::fromName(hostName);
if (hostInfo.error() != QHostInfo::NoError) {
reportConnectionFailure(
QStringLiteral("无法解析主机名“%1”").arg(hostName),
QStringLiteral(
"请检查主机地址拼写和 DNS 设置,或直接使用 IPv4 地址连接。"),
hostInfo.errorString());
return false;
}
for (const QHostAddress &candidate : hostInfo.addresses()) {
if (candidate.protocol() == QAbstractSocket::IPv4Protocol) {
address = candidate;
break;
}
}
if (address.isNull()) {
reportConnectionFailure(
QStringLiteral("无法解析主机名“%1”").arg(hostName),
QStringLiteral(
"解析结果中没有可用的 IPv4 地址;当前版本暂不支持 IPv6,"
"请改用服务器的 IPv4 地址。"));
return false;
}
}
if (address.protocol() != QAbstractSocket::IPv4Protocol) {
reportConnectionFailure(
QStringLiteral("暂不支持 IPv6 地址"),
QStringLiteral("请改用服务器的 IPv4 地址;IPv6 连接将在后续版本支持。"),
hostName);
return false;
}
struct sockaddr_in sin;
std::memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(static_cast<quint16>(connectInfo.port));
sin.sin_addr.s_addr = htonl(address.toIPv4Address());
const int connectResult =
::connect(fd, reinterpret_cast<struct sockaddr *>(&sin), sizeof(sin));
if (connectResult != 0) {
const int error = socketLastError();
#ifdef WIN32
const bool inProgress =
(error == WSAEINPROGRESS || error == WSAEWOULDBLOCK);
#else
const bool inProgress =
(error == EINPROGRESS || error == EWOULDBLOCK);
#endif
if (!inProgress) {
QString reason;
QString hint;
describeSocketFailure(error, &reason, &hint);
reportConnectionFailure(reason, hint, socketErrorString(error));
return false;
}
fd_set writeSet;
FD_ZERO(&writeSet);
FD_SET(fd, &writeSet);
struct timeval timeout;
timeout.tv_sec = kConnectTimeoutSeconds;
timeout.tv_usec = 0;
const int selected = select(fd + 1, nullptr, &writeSet, nullptr, &timeout);
if (selected == 0) {
reportConnectionFailure(
QStringLiteral("连接超时"),
QStringLiteral(
"目标主机在 30 秒内没有响应。请检查网络连通性、防火墙规则,"
"或确认端口是否开放。"),
QStringLiteral("连接 %1:%2 超时")
.arg(hostName)
.arg(connectInfo.port));
return false;
}
if (selected < 0) {
const int error = socketLastError();
QString reason;
QString hint;
describeSocketFailure(error, &reason, &hint);
reportConnectionFailure(reason, hint, socketErrorString(error));
return false;
}
int socketError = 0;
#ifdef WIN32
int socketErrorLength = sizeof(socketError);
#else
socklen_t socketErrorLength = sizeof(socketError);
#endif
if (getsockopt(fd, SOL_SOCKET, SO_ERROR,
reinterpret_cast<char *>(&socketError),
&socketErrorLength) != 0 ||
socketError != 0) {
const int error =
socketError != 0 ? socketError : socketLastError();
QString reason;
QString hint;
describeSocketFailure(error, &reason, &hint);
reportConnectionFailure(reason, hint, socketErrorString(error));
return false;
}
}
return true;
}
bool SFTPClient::openSession() {
session = libssh2_session_init();
if (!session) {
reportConnectionFailure(
QStringLiteral("无法创建 SSH 会话"),
QStringLiteral("SSH 组件初始化失败,请重启应用后重试。"));
return false;
}
libssh2_session_set_blocking(session, 0);
libssh2_session_set_timeout(session, 30000);
const int rc = runWithRetry(
[this]() { return libssh2_session_handshake(session, sock.load()); });
if (rc != 0) {
const QString sessionText = lastErrorString();
QString reason;
QString hint;
describeHandshakeFailure(rc, sessionText, &reason, &hint);
reportConnectionFailure(reason, hint, sessionText);
return false;
}
return true;
}
bool SFTPClient::auth() {
const QByteArray username = connectInfo.username.toUtf8();
const AuthType authType = static_cast<AuthType>(connectInfo.authType);
int rc = 0;
if (authType == AuthType::Password) {
const QByteArray password = connectInfo.password.toUtf8();
rc = runWithRetry([this, &username, &password]() {
return libssh2_userauth_password(session, username.constData(),
password.constData());
});
} else if (authType == AuthType::PublicKey) {
const QByteArray publicKey = connectInfo.publicKeyPath.toUtf8();
const QByteArray privateKey = connectInfo.privateKeyPath.toUtf8();
const QByteArray passPhrase = connectInfo.passPhrase.toUtf8();
rc = runWithRetry([this, &username, &publicKey, &privateKey, &passPhrase]() {
return libssh2_userauth_publickey_fromfile(
session, username.constData(), publicKey.constData(),
privateKey.constData(), passPhrase.constData());
});
} else {
reportConnectionFailure(
QStringLiteral("未知的认证方式"),
QStringLiteral("请在连接配置中选择密码认证或公钥认证。"),
QStringLiteral("认证类型:%1").arg(connectInfo.authType));
return false;
}
if (rc != 0) {
QString reason;
QString hint;
if (authType == AuthType::Password) {
describePasswordAuthFailure(rc, &reason, &hint);
} else {
describePublicKeyAuthFailure(rc, &reason, &hint);
}
QString detail = lastErrorString();
if (detail.isEmpty()) {
detail = QStringLiteral("libssh2 错误码:%1").arg(rc);
} else {
detail = QStringLiteral("libssh2 错误码:%1\n%2").arg(rc).arg(detail);
}
reportConnectionFailure(reason, hint, detail);
return false;
}
emit authSuccess();
return true;
}
bool SFTPClient::initSftpSession() {
const int rc = runWithRetry([this]() {
sftp_session = libssh2_sftp_init(session);
if (sftp_session) {
return 0;
}
const int error = libssh2_session_last_errno(session);
return error == 0 ? -1 : error;
});
if (!sftp_session) {
if (rc == -1 || rc == LIBSSH2_ERROR_TIMEOUT ||
rc == LIBSSH2_ERROR_SOCKET_TIMEOUT) {
reportConnectionFailure(
QStringLiteral("初始化 SFTP 会话超时"),
QStringLiteral("服务器没有及时响应 SFTP 初始化请求,请检查网络状况后重试。"),
lastErrorString());
} else {
reportConnectionFailure(
QStringLiteral("无法启动 SFTP 会话"),
QStringLiteral(
"服务器可能未启用 SFTP 子系统(sshd 的 Subsystem sftp),"
"或该账号没有访问 SFTP 的权限。"),
lastErrorString());
}
return false;
}
sessionReady.store(true);
emit initSftpSessionSuccess();
return true;
}
int SFTPClient::waitSocket(int timeoutMs) const {
const int fd = sock.load();
if (fd < 0 || !session) {
return -1;
}
fd_set fdSet;
FD_ZERO(&fdSet);
FD_SET(fd, &fdSet);
struct timeval timeout;
timeout.tv_sec = timeoutMs / 1000;
timeout.tv_usec = (timeoutMs % 1000) * 1000;
const int direction = libssh2_session_block_directions(session);
fd_set *readSet = (direction & LIBSSH2_SESSION_BLOCK_INBOUND) ? &fdSet : nullptr;
fd_set *writeSet =
(direction & LIBSSH2_SESSION_BLOCK_OUTBOUND) ? &fdSet : nullptr;
if (!readSet && !writeSet) {
// 方向未知时同时等待读/写,避免无谓地睡满整个超时时间。
readSet = &fdSet;
writeSet = &fdSet;
}
return select(fd + 1, readSet, writeSet, nullptr, &timeout);
}
int SFTPClient::runWithRetry(const std::function<int()> &operation) {
int rc = 0;
int timeouts = 0;
qint64 idleMs = 0;
while ((rc = operation()) == LIBSSH2_ERROR_EAGAIN) {
if (stopRequested.load() || transferCancelRequested.load()) {
return rc;
}
// 分段等待 socket,保证“取消”最多 kCancelPollMs 后就能从 select() 出来;
// 累计等待满 kIoTimeoutMs 才计一次超时,整体超时语义与分块前一致。
QElapsedTimer slice;
slice.start();
const int waitResult = waitSocket(kCancelPollMs);
if (waitResult > 0) {
timeouts = 0;
idleMs = 0;
} else if (waitResult == 0) {
idleMs += slice.elapsed();
if (idleMs >= kIoTimeoutMs) {
idleMs = 0;
if (++timeouts >= kMaxTimeouts) {
qWarning() << "SFTPClient: 网络操作超时";
return -1;
}
}
} else {
#ifdef WIN32
if (socketLastError() == WSAEINTR) {
continue;
}
#else
if (errno == EINTR) {
continue;
}
#endif
return -1;
}
}
return rc;
}
bool SFTPClient::isReady() const {
return isRunning() && sessionReady.load();
}
bool SFTPClient::runBlocking(const std::function<bool()> &operation) {
if (QThread::currentThread() == this) {
return operation();
}
if (!isRunning() || !sessionReady.load()) {
return false;
}
bool result = false;
const bool invoked =
QMetaObject::invokeMethod(this, [&operation]() { return operation(); },
Qt::BlockingQueuedConnection, &result);
return invoked && result;
}
void SFTPClient::cancelTransfer() { transferCancelRequested.store(true); }
QString SFTPClient::transferCancelledMessage() {
return QStringLiteral("传输已取消");
}
void SFTPClient::reportConnectionFailure(const QString &reason,
const QString &hint,
const QString &detail) {
if (stopRequested.load()) {
return;
}
emit connectionFailed(reason, hint, detail);
}
QString SFTPClient::lastErrorString() const {
if (!session) {
return QString();
}
char *message = nullptr;
int messageLength = 0;
libssh2_session_last_error(session, &message, &messageLength, 0);
if (!message || messageLength <= 0) {
return QString();
}
return QString::fromUtf8(message, messageLength);
}
void SFTPClient::opendir(const QString &sftpPath) {
const QString dirPath = normalizeRemotePath(sftpPath);
if (!sessionReady.load()) {
emit directoryLoadFailed(dirPath, QStringLiteral("SFTP 会话未就绪"));
return;
}
QByteArray pathBytes = dirPath.toUtf8();
LIBSSH2_SFTP_HANDLE *handle = nullptr;
runWithRetry([this, &handle, &pathBytes]() {
handle = libssh2_sftp_opendir(sftp_session, pathBytes.constData());
if (handle) {
return 0;
}
const int error = libssh2_session_last_errno(session);
return error == 0 ? -1 : error;
});
if (!handle) {
emit directoryLoadFailed(
dirPath, QStringLiteral("无法打开目录 %1: %2")
.arg(dirPath, lastErrorString()));
return;
}
QList<FileInfo_S> entries;
entries.reserve(256);
bool succeeded = true;
QString failure;
while (!stopRequested.load()) {
char fileName[1024] = {0};
char longEntry[1024] = {0};
LIBSSH2_SFTP_ATTRIBUTES attrs;
std::memset(&attrs, 0, sizeof(attrs));
const int rc = runWithRetry([this, handle, &fileName, &longEntry, &attrs]() {
return libssh2_sftp_readdir_ex(handle, fileName, sizeof(fileName),
longEntry, sizeof(longEntry), &attrs);
});
if (rc == 0) {
break;
}
if (rc < 0) {
succeeded = false;
failure = lastErrorString();
break;
}
const QString name = QString::fromUtf8(fileName);
if (name.isEmpty() || name == QLatin1String(".") ||
name == QLatin1String("..")) {
continue;
}
const qint64 size =
(attrs.flags & LIBSSH2_SFTP_ATTR_SIZE)
? static_cast<qint64>(attrs.filesize)
: 0;
const qint64 mtime =
(attrs.flags & LIBSSH2_SFTP_ATTR_ACMODTIME)
? static_cast<qint64>(attrs.mtime)
: 0;
const unsigned long mode = (attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS)
? attrs.permissions
: 0;
unsigned long uid = 0;
unsigned long gid = 0;
if (attrs.flags & LIBSSH2_SFTP_ATTR_UIDGID) {
uid = attrs.uid;
gid = attrs.gid;
}
FileInfo_S info =
makeFileInfo(dirPath, name, size, mtime, mode, uid, gid,
QString::fromUtf8(longEntry));
// 符号链接保留自身类型,只额外记录目标类型:
// 这样既能显示目录图标,又不会在删除时误删链接指向的目录。
if (info.fileType == RemoteFileSymlink) {
LIBSSH2_SFTP_ATTRIBUTES targetAttrs;
std::memset(&targetAttrs, 0, sizeof(targetAttrs));
if (getFileStat(info.filePath, &targetAttrs) &&
(targetAttrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS)) {
info.targetFileType = fileTypeFromMode(targetAttrs.permissions);
}
}
entries.append(info);
}
runWithRetry([this, handle]() { return libssh2_sftp_close(handle); });
if (stopRequested.load()) {
return;
}
if (!succeeded) {
emit directoryLoadFailed(
dirPath, QStringLiteral("读取目录 %1 失败: %2").arg(dirPath, failure));
return;
}
emit directoryLoaded(dirPath, entries);
}
bool SFTPClient::getFileStat(const QString &filePath,
LIBSSH2_SFTP_ATTRIBUTES *attrs) {
if (!attrs || !sessionReady.load()) {
return false;
}
QByteArray pathBytes = filePath.toUtf8();
return runWithRetry([this, &pathBytes, attrs]() {
return libssh2_sftp_stat(sftp_session, pathBytes.constData(), attrs);
}) == 0;
}
bool SFTPClient::mkdir(const QString &path) {
const QString dirPath = normalizeRemotePath(path);
if (!isRunning() || !sessionReady.load()) {
emit errorMsg(QStringLiteral("SFTP 会话未就绪"));
return false;
}
const bool succeeded = runBlocking([this, dirPath]() {
if (!sessionReady.load()) {
return false;
}
QByteArray pathBytes = dirPath.toUtf8();
return runWithRetry([this, &pathBytes]() {
return libssh2_sftp_mkdir(
sftp_session, pathBytes.constData(),
LIBSSH2_SFTP_S_IRWXU | LIBSSH2_SFTP_S_IRGRP |
LIBSSH2_SFTP_S_IXGRP | LIBSSH2_SFTP_S_IROTH |
LIBSSH2_SFTP_S_IXOTH);
}) == 0;
});
if (!succeeded) {
emit errorMsg(QStringLiteral("创建文件夹失败: ") + dirPath);
} else {
emit successMsg(QStringLiteral("文件夹创建成功"));
}
return succeeded;
}
bool SFTPClient::removeFile(const QString &path) {
const QString filePath = normalizeRemotePath(path);
return runBlocking([this, filePath]() {
if (!sessionReady.load()) {
return false;
}
QByteArray pathBytes = filePath.toUtf8();
return runWithRetry([this, &pathBytes]() {
return libssh2_sftp_unlink(sftp_session, pathBytes.constData());
}) == 0;
});
}
bool SFTPClient::rmdir(const QString &path, bool reportError) {
const QString dirPath = normalizeRemotePath(path);
if (!isRunning() || !sessionReady.load()) {
if (reportError) {
emit errorMsg(QStringLiteral("SFTP 会话未就绪"));
}
return false;
}
const bool succeeded = runBlocking([this, dirPath]() {
return sessionReady.load() && removeDirectoryRecursive(dirPath);
});
if (!succeeded && reportError) {
emit errorMsg(QStringLiteral("删除失败: ") + dirPath);
}
return succeeded;
}
bool SFTPClient::removeDirectoryRecursive(const QString &path) {
if (!sessionReady.load() || stopRequested.load()) {
return false;
}
QByteArray pathBytes = path.toUtf8();
LIBSSH2_SFTP_HANDLE *handle = nullptr;
runWithRetry([this, &handle, &pathBytes]() {
handle = libssh2_sftp_opendir(sftp_session, pathBytes.constData());
if (handle) {
return 0;
}
const int error = libssh2_session_last_errno(session);
return error == 0 ? -1 : error;
});
if (!handle) {
return false;
}
bool succeeded = true;
while (!stopRequested.load()) {
char fileName[1024] = {0};
LIBSSH2_SFTP_ATTRIBUTES attrs;
std::memset(&attrs, 0, sizeof(attrs));
const int rc = runWithRetry([this, handle, &fileName, &attrs]() {
return libssh2_sftp_readdir(handle, fileName, sizeof(fileName), &attrs);
});
if (rc == 0) {
break;
}
if (rc < 0) {
succeeded = false;
break;
}
const QString name = QString::fromUtf8(fileName);
if (name == QLatin1String(".") || name == QLatin1String("..")) {
continue;
}
const QString childPath = joinRemotePath(path, name);
if (LIBSSH2_SFTP_S_ISDIR(attrs.permissions) &&
!LIBSSH2_SFTP_S_ISLNK(attrs.permissions)) {
if (!removeDirectoryRecursive(childPath)) {
succeeded = false;
break;
}
} else if (!removeFile(childPath)) {
succeeded = false;
break;
}
}
runWithRetry([this, handle]() { return libssh2_sftp_close(handle); });
if (!succeeded || stopRequested.load()) {
return false;
}
return runWithRetry([this, &pathBytes]() {
return libssh2_sftp_rmdir(sftp_session, pathBytes.constData());
}) == 0;
}
bool SFTPClient::rename(const QString &sourceName, const QString &targetName) {
const QString sourcePath = normalizeRemotePath(sourceName);
const QString targetPath = normalizeRemotePath(targetName);
if (!isRunning() || !sessionReady.load()) {
emit errorMsg(QStringLiteral("SFTP 会话未就绪"));
return false;
}
const bool succeeded = runBlocking([this, sourcePath, targetPath]() {
if (!sessionReady.load()) {
return false;
}
QByteArray sourceBytes = sourcePath.toUtf8();
QByteArray targetBytes = targetPath.toUtf8();
return runWithRetry([this, &sourceBytes, &targetBytes]() {
return libssh2_sftp_rename(sftp_session, sourceBytes.constData(),
targetBytes.constData());
}) == 0;
});
if (!succeeded) {
emit errorMsg(QStringLiteral("重命名失败: ") + sourcePath);
}
return succeeded;
}