-
-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathgetput.cpp
More file actions
1731 lines (1544 loc) · 57.3 KB
/
getput.cpp
File metadata and controls
1731 lines (1544 loc) · 57.3 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
/*=============================================================================
*
* ダウンロード/アップロード
*
===============================================================================
/ Copyright (C) 1997-2007 Sota. All rights reserved.
/
/ Redistribution and use in source and binary forms, with or without
/ modification, are permitted provided that the following conditions
/ are met:
/
/ 1. Redistributions of source code must retain the above copyright
/ notice, this list of conditions and the following disclaimer.
/ 2. Redistributions in binary form must reproduce the above copyright
/ notice, this list of conditions and the following disclaimer in the
/ documentation and/or other materials provided with the distribution.
/
/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
/ IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
/ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
/ IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
/ USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
/ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
/ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/============================================================================*/
/* このソースは一部、WS_FTP Version 93.12.05 のソースを参考にしました。 */
/* スレッドの作成/終了に関して、樋口殿作成のパッチを組み込みました。 */
/*
一部、高速化のためのコード追加 by H.Shirouzu at 2002/10/02
*/
#include "common.h"
#include <process.h>
#define SET_BUFFER_SIZE
/* Add by H.Shirouzu at 2002/10/02 */
#define BUFSIZE (32 * 1024)
#define SOCKBUF_SIZE (256 * 1024)
/* End */
#ifdef DISABLE_TRANSFER_NETWORK_BUFFERS
#undef BUFSIZE
#define BUFSIZE (64 * 1024) // RWIN値以下で充分な大きさが望ましいと思われる。
#undef SET_BUFFER_SIZE
#endif
#define TIMER_DISPLAY 1 /* 表示更新用タイマのID */
#define DISPLAY_TIMING 500 /* 表示更新時間 0.5秒 */
#define ERR_MSG_LEN 1024
/*===== プロトタイプ =====*/
static void DispTransPacket(TRANSPACKET const& item);
static void EraseTransFileList();
static unsigned __stdcall TransferThread(void *Dummy);
static int MakeNonFullPath(TRANSPACKET& item, std::wstring& CurDir);
static int DownloadFile(TRANSPACKET *Pkt, std::shared_ptr<SocketContext> dSkt, int CreateMode, int *CancelCheckWork);
static void DispDownloadFinishMsg(TRANSPACKET *Pkt, int iRetCode);
static bool DispUpDownErrDialog(int ResID, TRANSPACKET *Pkt) noexcept;
static int DoUpload(std::shared_ptr<SocketContext> cSkt, TRANSPACKET& item);
static int UploadFile(TRANSPACKET *Pkt, std::shared_ptr<SocketContext> dSkt, int Resume, int* CancelCheckWork);
static int TermCodeConvAndSend(SocketContext& s, char *Data, int Size, int Ascii, int *CancelCheckWork);
static void DispUploadFinishMsg(TRANSPACKET *Pkt, int iRetCode);
static LRESULT CALLBACK TransDlgProc(HWND hDlg, UINT Msg, WPARAM wParam, LPARAM lParam);
static void DispTransferStatus(HWND hWnd, int End, TRANSPACKET *Pkt);
static void DispTransFileInfo(TRANSPACKET const& item, UINT titleId, int SkipButton, int Info);
static std::optional<std::tuple<std::wstring, int>> GetAdrsAndPort(SocketContext& s, std::wstring const& reply);
static bool IsSpecialDevice(std::wstring_view filename);
static int MirrorDelNotify(int Cur, int Notify, TRANSPACKET const& item) noexcept;
/*===== ローカルなワーク =====*/
// 同時接続対応
//static HANDLE hTransferThread;
static HANDLE hTransferThread[MAX_DATA_CONNECTION];
static bool fTransferThreadExit = false;
static int TransFiles = 0; /* 転送待ちファイル数 */
static Concurrency::concurrent_queue<TRANSPACKET> TransPacketBase; /* 転送ファイルリスト */
// 同時接続対応
//static int Canceled; /* 中止フラグ YES/NO */
static int Canceled[MAX_DATA_CONNECTION]; /* 中止フラグ YES/NO */
static int ClearAll; /* 全て中止フラグ YES/NO */
static int ForceAbort; /* 転送中止フラグ */
/* このフラグはスレッドを終了させるときに使う */
extern HANDLE initialized;
// 同時接続対応
//static LONGLONG AllTransSizeNow; /* 今回の転送で転送したサイズ */
//static time_t TimeStart; /* 転送開始時間 */
static LONGLONG AllTransSizeNow[MAX_DATA_CONNECTION]; /* 今回の転送で転送したサイズ */
static time_t TimeStart[MAX_DATA_CONNECTION]; /* 転送開始時間 */
static int KeepDlg = NO; /* 転送中ダイアログを消さないかどうか (YES/NO) */
static int MoveToForeground = NO; /* ウインドウを前面に移動するかどうか (YES/NO) */
static std::wstring CurDir[MAX_DATA_CONNECTION];
static thread_local std::wstring ErrMsg;
// 送受信の完了を検出する。
// [0..MAX_DATA_CONNECTION-1]: manual reset、各スレッドの状態。開始時にreset、完了したらset
// [MAX_DATA_CONNECTION]: auto reset、送受信開始時にset
// これら全てをWaitForMultipleObjectsで待つ。auto resetなので1スレッドだけが送受信完了の通知を受ける。
static HANDLE completed[MAX_DATA_CONNECTION + 1];
// 再転送対応
static int TransferErrorMode = EXIST_OVW;
static int TransferErrorNotify = NO;
// タスクバー進捗表示
static LONGLONG TransferSizeLeft = 0;
static LONGLONG TransferSizeTotal = 0;
static int TransferErrorDisplay = 0;
static void SetErrorMsg(std::wstring&& msg) {
if (empty(ErrMsg))
ErrMsg = std::move(msg);
}
// ファイル転送スレッドを起動する
int MakeTransferThread() noexcept {
ClearAll = NO;
ForceAbort = NO;
fTransferThreadExit = false;
for (int i = 0; i < MAX_DATA_CONNECTION; i++) {
completed[i] = CreateEventW(nullptr, true, true, nullptr);
hTransferThread[i] = (HANDLE)_beginthreadex(nullptr, 0, TransferThread, IntToPtr(i), 0, nullptr);
if (hTransferThread[i] == (HANDLE)-1)
return FFFTP_FAIL;
}
completed[MAX_DATA_CONNECTION] = CreateEventW(nullptr, false, false, nullptr);
return FFFTP_SUCCESS;
}
// ファイル転送スレッドを終了する
void CloseTransferThread() noexcept {
for (int i = 0; i < MAX_DATA_CONNECTION; i++)
Canceled[i] = YES;
ClearAll = YES;
fTransferThreadExit = true;
SetEvent(initialized);
for (int i = 0; i < MAX_DATA_CONNECTION; i++) {
while (WaitForSingleObject(hTransferThread[i], 10) == WAIT_TIMEOUT) {
BackgrndMessageProc();
Canceled[i] = YES;
}
CloseHandle(hTransferThread[i]);
CloseHandle(completed[i]);
}
}
// 同時接続対応
void AbortAllTransfer()
{
int i;
while(!empty(TransPacketBase))
{
for(i = 0; i < MAX_DATA_CONNECTION; i++)
Canceled[i] = YES;
ClearAll = YES;
if(BackgrndMessageProc() == YES)
break;
Sleep(10);
}
ClearAll = NO;
}
/*----- 転送するファイル情報を転送ファイルリストに登録する --------------------
*
* Parameter
* TRANSPACKET *Pkt : 転送ファイル情報
*
* Return Value
* なし
*----------------------------------------------------------------------------*/
void AddTransFileList(TRANSPACKET *Pkt)
{
DispTransPacket(*Pkt);
TransPacketBase.push(*Pkt);
SetEvent(completed[MAX_DATA_CONNECTION]);
if (Pkt->Command.starts_with(L"RETR"sv) || Pkt->Command.starts_with(L"STOR"sv)) {
TransFiles++;
// タスクバー進捗表示
TransferSizeLeft += Pkt->Size;
TransferSizeTotal += Pkt->Size;
PostMessageW(GetMainHwnd(), WM_CHANGE_COND, 0, 0);
}
}
// バグ対策
void AddNullTransFileList()
{
TRANSPACKET Pkt{};
Pkt.Command = L"NULL"s;
AddTransFileList(&Pkt);
}
// 転送ファイル情報を転送ファイルリストに追加する
void AppendTransFileList(std::vector<TRANSPACKET>&& list) {
for (auto& Pkt : list)
AddTransFileList(&Pkt);
}
// 転送ファイル情報を表示する
static void DispTransPacket(TRANSPACKET const& item) {
if (item.Command.starts_with(L"RETR"sv) || item.Command.starts_with(L"STOR"sv))
Debug(L"TransList Cmd={} : {} : {}"sv, item.Command, item.Remote, item.Local.native());
else if (item.Command.starts_with(L"R-"sv))
Debug(L"TransList Cmd={} : {}"sv, item.Command, item.Remote);
else if (item.Command.starts_with(L"L-"sv))
Debug(L"TransList Cmd={} : {}"sv, item.Command, item.Local.native());
else if (item.Command.starts_with(L"MKD"sv))
Debug(L"TransList Cmd={} : {}"sv, item.Command, item.Local.empty() ? item.Remote : item.Local.native());
else
Debug(L"TransList Cmd={}"sv, item.Command);
}
// 転送ファイルリストをクリアする
static void EraseTransFileList() {
/* 最後の"BACKCUR"は必要なので消さない */
// TODO: 一時的に全要素が消えるため、不整合が生じる可能性がある。try_popが速いのでEraseを排除できるのではないか?
std::optional<TRANSPACKET> backcur;
for (TRANSPACKET pkt; TransPacketBase.try_pop(pkt);)
if (pkt.Command == L"BACKCUR"sv)
backcur = pkt;
if (backcur)
TransPacketBase.push(*std::move(backcur));
TransFiles = 0;
TransferSizeLeft = 0;
TransferSizeTotal = 0;
PostMessageW(GetMainHwnd(), WM_CHANGE_COND, 0, 0);
}
// 転送中ダイアログを消さないようにするかどうかを設定
void KeepTransferDialog(int Sw) noexcept {
KeepDlg = Sw;
}
/*----- 現在転送中かどうかを返す ----------------------------------------------
*
* Parameter
* なし
*
* Return Value
* int ステータス (YES/NO=転送中ではない)
*----------------------------------------------------------------------------*/
int AskTransferNow(void)
{
return !empty(TransPacketBase) ? YES : NO;
}
// 転送するファイルの数を返す
int AskTransferFileNum() noexcept {
return TransFiles;
}
// 転送中ウインドウを前面に出す
void GoForwardTransWindow() noexcept {
MoveToForeground = YES;
}
// 転送ソケットのカレントディレクトリ情報を初期化
void InitTransCurDir() noexcept {
for (auto& dir : CurDir)
dir.clear();
}
/*----- ファイル転送スレッドのメインループ ------------------------------------
*
* Parameter
* void *Dummy : 使わない
*
* Return Value
* なし
*----------------------------------------------------------------------------*/
static unsigned __stdcall TransferThread(void *Dummy)
{
HWND hWndTrans;
int CwdSts;
// int Down;
// int Up;
static int Down;
static int Up;
int DelNotify;
int ThreadCount;
std::shared_ptr<SocketContext> TrnSkt;
RECT WndRect;
int i;
DWORD LastUsed = timeGetTime();
int LastError;
int Sts;
hWndTrans = NULL;
Down = NO;
Up = NO;
DelNotify = NO;
// 同時接続対応
// ソケットは各転送スレッドが管理
ThreadCount = PtrToInt(Dummy);
LastError = NO;
SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
auto const result = WaitForSingleObject(initialized, INFINITE);
assert(result == WAIT_OBJECT_0);
while (!fTransferThreadExit) {
ErrMsg.clear();
// Canceled = NO;
Canceled[ThreadCount] = NO;
if (GetCurHost().ReuseCmdSkt == YES && ThreadCount == 0) {
TrnSkt = AskTrnCtrlSkt();
// セッションあたりの転送量制限対策
if (TrnSkt && GetCurHost().TransferErrorReconnect == YES && LastError == YES) {
PostMessageW(GetMainHwnd(), WM_RECONNECTSOCKET, 0, 0);
Sleep(100);
TrnSkt.reset();
}
}
else
{
// セッションあたりの転送量制限対策
if (TrnSkt && GetCurHost().TransferErrorReconnect == YES && LastError == YES) {
DoQUIT(TrnSkt, &Canceled[ThreadCount]);
TrnSkt.reset();
}
if (!empty(TransPacketBase) && AskConnecting() == YES && ThreadCount < GetCurHost().MaxThreadCount) {
if (!TrnSkt)
ReConnectTrnSkt(TrnSkt, &Canceled[ThreadCount]);
else
CheckClosedAndReconnectTrnSkt(TrnSkt, &Canceled[ThreadCount]);
// 同時ログイン数制限対策
if (!TrnSkt)
{
// 同時ログイン数制限に引っかかった可能性あり
// 負荷を下げるために約10秒間待機
i = 1000;
while(i > 0)
{
BackgrndMessageProc();
Sleep(10);
i--;
}
}
LastUsed = timeGetTime();
}
else
{
if (TrnSkt) {
// 同時ログイン数制限対策
// 60秒間使用されなければログアウト
if (timeGetTime() - LastUsed > 60000 || AskConnecting() == NO || ThreadCount >= GetCurHost().MaxThreadCount) {
DoQUIT(TrnSkt, &Canceled[ThreadCount]);
TrnSkt.reset();
}
}
}
}
LastError = NO;
ResetEvent(completed[ThreadCount]);
if (TRANSPACKET pkt; TrnSkt && TransPacketBase.try_pop(pkt)) {
auto Pos = &pkt;
if(hWndTrans == NULL)
{
if (Pos->Command.starts_with(L"RETR"sv) || Pos->Command.starts_with(L"STOR"sv) || Pos->Command.starts_with(L"MKD"sv) || Pos->Command.starts_with(L"L-"sv) || Pos->Command.starts_with(L"R-"sv)) {
hWndTrans = CreateDialogW(GetFtpInst(), MAKEINTRESOURCEW(transfer_dlg), HWND_DESKTOP, (DLGPROC)TransDlgProc);
if(MoveToForeground == YES)
SetForegroundWindow(hWndTrans);
ShowWindow(hWndTrans, SW_SHOWNOACTIVATE);
GetWindowRect(hWndTrans, &WndRect);
SetWindowPos(hWndTrans, NULL, WndRect.left, WndRect.top + (WndRect.bottom - WndRect.top) * ThreadCount - (WndRect.bottom - WndRect.top) * (GetCurHost().MaxThreadCount - 1) / 2, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
}
Pos->hWndTrans = hWndTrans;
Pos->ctrl_skt = TrnSkt;
Pos->Abort = ABORT_NONE;
Pos->ThreadCount = ThreadCount;
if(hWndTrans != NULL)
{
if(MoveToForeground == YES)
{
SetForegroundWindow(hWndTrans);
MoveToForeground = NO;
}
}
if(hWndTrans != NULL)
SendMessageW(hWndTrans, WM_SET_PACKET, 0, (LPARAM)&*Pos);
// 中断後に受信バッファに応答が残っていると次のコマンドの応答が正しく処理できない
TrnSkt->ClearReadBuffer();
/* ダウンロード */
if(Pos->Command.starts_with(L"RETR"sv))
{
/* 不正なパスを検出 */
if(CheckPathViolation(*Pos) == NO)
{
/* フルパスを使わないための処理 */
if(MakeNonFullPath(*Pos, CurDir[Pos->ThreadCount]) == FFFTP_SUCCESS)
{
if(Pos->Command.starts_with(L"RETR-S"sv))
{
/* サイズと日付を取得 */
DoSIZE(TrnSkt, Pos->Remote, &Pos->Size, &Canceled[Pos->ThreadCount]);
DoMDTM(TrnSkt, Pos->Remote, &Pos->Time, &Canceled[Pos->ThreadCount]);
Pos->Command = L"RETR "s;
}
Down = YES;
// ミラーリング設定追加
if(Pos->NoTransfer == NO)
{
Sts = DoDownload(TrnSkt, *Pos, NO, &Canceled[Pos->ThreadCount]) / 100;
if(Sts != FTP_COMPLETE)
LastError = YES;
// ゾーンID設定追加
if(MarkAsInternet == YES && IsZoneIDLoaded() == YES)
MarkFileAsDownloadedFromInternet(Pos->Local);
}
if (SaveTimeStamp == YES && (Pos->Time.dwLowDateTime != 0 || Pos->Time.dwHighDateTime != 0))
if (auto handle = CreateFileW(Pos->Local.c_str(), FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, 0); handle != INVALID_HANDLE_VALUE) {
SetFileTime(handle, &Pos->Time, &Pos->Time, &Pos->Time);
CloseHandle(handle);
}
}
}
}
/* アップロード */
else if(Pos->Command.starts_with(L"STOR"sv))
{
/* フルパスを使わないための処理 */
if(MakeNonFullPath(*Pos, CurDir[Pos->ThreadCount]) == FFFTP_SUCCESS)
{
Up = YES;
// ミラーリング設定追加
if(Pos->NoTransfer == NO)
{
Sts = DoUpload(TrnSkt, *Pos) / 100;
if(Sts != FTP_COMPLETE)
LastError = YES;
}
// ホスト側の日時設定
/* ファイルのタイムスタンプを合わせる */
if((SaveTimeStamp == YES) &&
((Pos->Time.dwLowDateTime != 0) || (Pos->Time.dwHighDateTime != 0)))
{
DoMFMT(TrnSkt, Pos->Remote, &Pos->Time, &Canceled[Pos->ThreadCount]);
}
}
}
/* フォルダ作成(ローカルまたはホスト) */
else if(Pos->Command.starts_with(L"MKD"sv))
{
DispTransFileInfo(*Pos, IDS_MSGJPN078, FALSE, YES);
if (!empty(Pos->Remote)) {
/* フルパスを使わないための処理 */
CwdSts = FTP_COMPLETE;
auto dir = Pos->Remote;
if (ProcForNonFullpath(TrnSkt, dir, CurDir[Pos->ThreadCount], hWndTrans, &Canceled[Pos->ThreadCount]) == FFFTP_FAIL) {
ClearAll = YES;
CwdSts = FTP_ERROR;
}
if(CwdSts == FTP_COMPLETE)
{
Up = YES;
Command(TrnSkt, &Canceled[Pos->ThreadCount], L"MKD {}"sv, dir);
/* すでにフォルダがある場合もあるので、 */
/* ここではエラーチェックはしない */
if(FolderAttr)
Command(TrnSkt, &Canceled[Pos->ThreadCount], L"{} {:03d} {}"sv, GetConnectingHost().ChmodCmd, FolderAttrNum, dir);
}
} else if (!Pos->Local.empty()) {
Down = YES;
DoLocalMKD(Pos->Local);
}
}
/* ディレクトリ作成(常にホスト側) */
else if(Pos->Command.starts_with(L"R-MKD"sv))
{
DispTransFileInfo(*Pos, IDS_MSGJPN078, FALSE, YES);
/* フルパスを使わないための処理 */
if(MakeNonFullPath(*Pos, CurDir[Pos->ThreadCount]) == FFFTP_SUCCESS)
{
Up = YES;
Command(TrnSkt, &Canceled[Pos->ThreadCount], L"{}{}"sv, std::wstring_view{ Pos->Command }.substr(2), Pos->Remote);
if(FolderAttr)
Command(TrnSkt, &Canceled[Pos->ThreadCount], L"{} {:03d} {}"sv, GetConnectingHost().ChmodCmd, FolderAttrNum, Pos->Remote);
}
}
/* ディレクトリ削除(常にホスト側) */
else if(Pos->Command.starts_with(L"R-RMD"sv))
{
DispTransFileInfo(*Pos, IDS_MSGJPN080, FALSE, YES);
DelNotify = MirrorDelNotify(WIN_REMOTE, DelNotify, *Pos);
if((DelNotify == YES) || (DelNotify == YES_ALL))
{
/* フルパスを使わないための処理 */
if(MakeNonFullPath(*Pos, CurDir[Pos->ThreadCount]) == FFFTP_SUCCESS)
{
Up = YES;
Command(TrnSkt, &Canceled[Pos->ThreadCount], L"{}{}"sv, std::wstring_view{ Pos->Command }.substr(2), Pos->Remote);
}
}
}
/* ファイル削除(常にホスト側) */
else if(Pos->Command.starts_with(L"R-DELE"sv))
{
DispTransFileInfo(*Pos, IDS_MSGJPN081, FALSE, YES);
DelNotify = MirrorDelNotify(WIN_REMOTE, DelNotify, *Pos);
if((DelNotify == YES) || (DelNotify == YES_ALL))
{
/* フルパスを使わないための処理 */
if(MakeNonFullPath(*Pos, CurDir[Pos->ThreadCount]) == FFFTP_SUCCESS)
{
Up = YES;
Command(TrnSkt, &Canceled[Pos->ThreadCount], L"{}{}"sv, std::wstring_view{ Pos->Command }.substr(2), Pos->Remote);
}
}
}
/* ディレクトリ作成(常にローカル側) */
else if(Pos->Command.starts_with(L"L-MKD"sv))
{
DispTransFileInfo(*Pos, IDS_MSGJPN078, FALSE, YES);
Down = YES;
DoLocalMKD(Pos->Local);
}
/* ディレクトリ削除(常にローカル側) */
else if(Pos->Command.starts_with(L"L-RMD"sv))
{
DispTransFileInfo(*Pos, IDS_MSGJPN080, FALSE, YES);
DelNotify = MirrorDelNotify(WIN_LOCAL, DelNotify, *Pos);
if((DelNotify == YES) || (DelNotify == YES_ALL))
{
Down = YES;
DoLocalRMD(Pos->Local);
}
}
/* ファイル削除(常にローカル側) */
else if(Pos->Command.starts_with(L"L-DELE"sv))
{
DispTransFileInfo(*Pos, IDS_MSGJPN081, FALSE, YES);
DelNotify = MirrorDelNotify(WIN_LOCAL, DelNotify, *Pos);
if((DelNotify == YES) || (DelNotify == YES_ALL))
{
Down = YES;
DoLocalDELE(Pos->Local);
}
}
/* カレントディレクトリを設定 */
else if(Pos->Command == L"SETCUR"sv)
{
if (GetCurHost().ReuseCmdSkt == NO || AskShareProh() == YES) {
if (CurDir[Pos->ThreadCount] != Pos->Remote) {
if (std::get<0>(Command(TrnSkt, &Canceled[Pos->ThreadCount], L"CWD {}"sv, Pos->Remote)) / 100 != FTP_COMPLETE) {
DispCWDerror(hWndTrans);
ClearAll = YES;
}
}
}
CurDir[Pos->ThreadCount] = Pos->Remote;
}
/* カレントディレクトリを戻す */
else if(Pos->Command == L"BACKCUR"sv)
{
if (GetCurHost().ReuseCmdSkt == YES && AskShareProh() == NO) {
if (CurDir[Pos->ThreadCount] != Pos->Remote)
Command(TrnSkt, &Canceled[Pos->ThreadCount], L"CWD {}"sv, Pos->Remote);
CurDir[Pos->ThreadCount] = Pos->Remote;
}
}
else if(Pos->Command == L"NULL"sv)
{
Sleep(0);
Sleep(100);
}
/*===== 1つの処理終わり =====*/
if(ForceAbort == NO)
{
if(ClearAll == YES)
// EraseTransFileList();
{
for(i = 0; i < MAX_DATA_CONNECTION; i++)
Canceled[i] = YES;
EraseTransFileList();
}
else
{
if (Pos->Command.starts_with(L"RETR"sv) || Pos->Command.starts_with(L"STOR"sv) || Pos->Command.starts_with(L"STOU"sv)) {
// TransFiles--;
if(TransFiles > 0)
TransFiles--;
// タスクバー進捗表示
if(TransferSizeLeft > 0)
TransferSizeLeft -= Pos->Size;
if(TransferSizeLeft < 0)
TransferSizeLeft = 0;
if(TransFiles == 0)
TransferSizeTotal = 0;
PostMessageW(GetMainHwnd(), WM_CHANGE_COND, 0, 0);
}
}
// ClearAll = NO;
if(BackgrndMessageProc() == YES)
EraseTransFileList();
}
if(hWndTrans != NULL)
SendMessageW(hWndTrans, WM_SET_PACKET, 0, 0);
LastUsed = timeGetTime();
}
// else
else if (empty(TransPacketBase))
{
ClearAll = NO;
DelNotify = NO;
SetEvent(completed[ThreadCount]);
if (WaitForMultipleObjects(size_as<DWORD>(completed), completed, true, 0) == WAIT_OBJECT_0) {
Sound::Transferred.Play();
if(AskAutoExit() == NO)
{
if(Down == YES)
PostMessageW(GetMainHwnd(), WM_REFRESH_LOCAL_FLG, 0, 0);
if(Up == YES)
PostMessageW(GetMainHwnd(), WM_REFRESH_REMOTE_FLG, 0, 0);
}
Down = NO;
Up = NO;
PostMessageW(GetMainHwnd(), WM_COMMAND, MAKEWPARAM(MENU_AUTO_EXIT, 0), 0);
}
if(KeepDlg == NO)
{
if(hWndTrans != NULL)
{
DestroyWindow(hWndTrans);
hWndTrans = NULL;
}
}
BackgrndMessageProc();
// Sleep(1);
Sleep(100);
// 再転送対応
TransferErrorMode = GetCurHost().TransferErrorMode;
TransferErrorNotify = GetCurHost().TransferErrorNotify;
}
else
{
if(hWndTrans != NULL)
{
DestroyWindow(hWndTrans);
hWndTrans = NULL;
}
BackgrndMessageProc();
if (ThreadCount < GetCurHost().MaxThreadCount)
Sleep(1);
else
Sleep(100);
}
}
if (GetCurHost().ReuseCmdSkt == NO || ThreadCount > 0) {
if (TrnSkt) {
TrnSkt->Send("QUIT\r\n", 6, 0, &Canceled[ThreadCount]);
TrnSkt.reset();
}
}
return 0;
}
/*----- フルパスを使わないファイルアクセスの準備 ------------------------------
*
* Parameter
* TRANSPACKET *Pkt : 転送パケット
* char *Cur : カレントディレクトリ
* char *Tmp : 作業用エリア
*
* Return Value
* int ステータス(FFFTP_SUCCESS/FFFTP_FAIL)
*
* Note
* フルパスを使わない時は、
* このモジュール内で CWD を行ない、
* Pkt->Remote にファイル名のみ残す。(パス名は消す)
*----------------------------------------------------------------------------*/
static int MakeNonFullPath(TRANSPACKET& item, std::wstring& Cur) {
auto const result = ProcForNonFullpath(item.ctrl_skt, item.Remote, Cur, item.hWndTrans, &Canceled[item.ThreadCount]);
if (result == FFFTP_FAIL)
ClearAll = YES;
return result;
}
static int SendDownloadCommand(TRANSPACKET* Pkt, int& CreateMode, int* CancelCheckWork) {
struct Data {
using result_t = bool;
void OnCommand(HWND hDlg, WORD id) noexcept {
switch (id) {
case IDOK:
EndDialog(hDlg, true);
break;
case RESUME_CANCEL_ALL:
ClearAll = YES;
[[fallthrough]];
case IDCANCEL:
EndDialog(hDlg, false);
break;
}
}
};
auto tempSize = std::exchange(Pkt->ExistSize, 0);
CreateMode = CREATE_ALWAYS;
if (Pkt->Mode == EXIST_RESUME) {
if (auto [code, text] = Command(Pkt->ctrl_skt, CancelCheckWork, L"REST {}"sv, tempSize); code / 100 < FTP_RETRY) {
/* リジューム */
if (Pkt->hWndTrans != NULL)
Pkt->ExistSize = tempSize;
CreateMode = OPEN_ALWAYS;
} else {
if (!Dialog(GetFtpInst(), noresume_dlg, Pkt->hWndTrans, Data{})) {
Pkt->Abort = ABORT_USER;
return 500;
}
}
}
auto [code, text] = Command(Pkt->ctrl_skt, CancelCheckWork, L"{}{}"sv, Pkt->Command, Pkt->Remote);
if (code / 100 != FTP_PRELIM) {
SetErrorMsg(std::move(text));
Notice(IDS_MSGJPN090);
return 500;
}
return code;
}
static int SendUploadCommand(TRANSPACKET* Pkt, int& Resume, int* CancelCheckWork) {
Resume = Pkt->Mode == EXIST_RESUME && Pkt->hWndTrans != NULL ? YES : NO;
auto cmd = L"APPE "sv;
std::wstring extra;
if (Resume == NO) {
cmd = Pkt->Command;
Pkt->ExistSize = 0;
#if defined(HAVE_TANDEM)
if (AskHostType() == HTYPE_TANDEM && AskOSS() == NO && Pkt->Type != TYPE_A)
extra = std::vformat(Pkt->PriExt == DEF_PRIEXT && Pkt->SecExt == DEF_SECEXT && Pkt->MaxExt == DEF_MAXEXT ? L",{}"sv : L",{},{},{},{}"sv, std::make_wformat_args(Pkt->FileCode, Pkt->PriExt, Pkt->SecExt, Pkt->MaxExt));
#endif
}
auto [code, text] = Command(Pkt->ctrl_skt, CancelCheckWork, L"{}{}{}"sv, cmd, Pkt->Remote, extra);
if (code / 100 != FTP_PRELIM) {
SetErrorMsg(std::move(text));
Notice(IDS_MSGJPN090);
return 500;
}
return code;
}
static int TransferActive(TRANSPACKET* Pkt, int (*SendTransferCommand)(TRANSPACKET* Pkt, int& mode, int* CancelCheckWork), int (*TransferFile)(TRANSPACKET* Pkt, std::shared_ptr<SocketContext> dSkt, int mode, int* CancelCheckWork), int* CancelCheckWork) {
auto listen_socket = GetFTPListenSocket(Pkt->ctrl_skt, CancelCheckWork);
if (!listen_socket) {
SetErrorMsg(GetString(IDS_MSGJPN279));
return 500;
}
int mode;
int code = SendTransferCommand(Pkt, mode, CancelCheckWork);
if (code / 100 == FTP_PRELIM) {
std::shared_ptr<SocketContext> data_socket;
if (GetCurHost().FireWall == YES && (FwallType == FWALL_SOCKS4 || FwallType == FWALL_SOCKS5_NOAUTH || FwallType == FWALL_SOCKS5_USER)) {
if (SocksReceiveReply(*listen_socket, CancelCheckWork))
data_socket = listen_socket;
} else {
sockaddr_storage sa;
int salen = sizeof(sockaddr_storage);
data_socket = listen_socket->Accept(reinterpret_cast<sockaddr*>(&sa), &salen);
if (shutdown(listen_socket->handle, 1) != 0)
WSAError(L"shutdown(listen)"sv);
if (!data_socket) {
SetErrorMsg(GetString(IDS_MSGJPN280));
WSAError(L"accept()"sv);
code = 500;
} else
Debug(L"Skt={} : accept from {}"sv, data_socket->handle, AddressPortToString(&sa, salen));
}
if (data_socket)
code = TransferFile(Pkt, data_socket, mode, CancelCheckWork);
}
if (IsUPnPLoaded() == YES)
RemovePortMapping(listen_socket->mapPort);
return code;
}
static int TransferPassive(TRANSPACKET* Pkt, int (*SendTransferCommand)(TRANSPACKET* Pkt, int& mode, int* CancelCheckWork), int (*TransferFile)(TRANSPACKET* Pkt, std::shared_ptr<SocketContext> dSkt, int mode, int* CancelCheckWork), int* CancelCheckWork) {
auto [code, text] = Command(Pkt->ctrl_skt, CancelCheckWork, GetCurHost().CurNetType == NTYPE_IPV4 ? L"PASV"sv : L"EPSV"sv);
if (code / 100 == FTP_COMPLETE) {
if (auto const target = GetAdrsAndPort(*Pkt->ctrl_skt, text)) {
if (auto [host, port] = *target; auto data_socket = connectsock(*Pkt->ctrl_skt, std::move(host), port, CancelCheckWork)) {
if (constexpr BOOL optval = 1; setsockopt(data_socket->handle, IPPROTO_TCP, TCP_NODELAY, (LPSTR)&optval, sizeof(optval)) == SOCKET_ERROR)
WSAError(L"setsockopt(IPPROTO_TCP, TCP_NODELAY)"sv);
int mode;
code = SendTransferCommand(Pkt, mode, CancelCheckWork);
if (code / 100 == FTP_PRELIM)
code = TransferFile(Pkt, data_socket, mode, CancelCheckWork);
} else {
SetErrorMsg(GetString(IDS_MSGJPN281)); // ダウンロードにはない
return 500;
}
} else {
SetErrorMsg(GetString(IDS_MSGJPN093));
Notice(IDS_MSGJPN093);
return 500;
}
} else
SetErrorMsg(std::move(text));
return code;
}
/*----- ダウンロードを行なう --------------------------------------------------
*
* Parameter
* SOCKET cSkt : コントロールソケット
* TRANSPACKET *Pkt : 転送ファイル情報
* int DirList : ディレクトリリストのダウンロード(YES/NO)
*
* Return Value
* int 応答コード
*
* Note
* このモジュールは、ファイル一覧の取得などを行なう際にメインのスレッド
* からも呼ばれる。メインのスレッドから呼ばれる時は Pkt->hWndTrans == NULL。
*----------------------------------------------------------------------------*/
int DoDownload(std::shared_ptr<SocketContext> cSkt, TRANSPACKET& item, int DirList, int *CancelCheckWork)
{
int iRetCode;
item.ctrl_skt = cSkt;
if (IsSpecialDevice(GetFileName(item.Local.native()))) {
iRetCode = 500;
Notice(IDS_MSGJPN085, GetFileName(item.Local.native()));
}
else if(item.Mode != EXIST_IGNORE)
{
if(item.Type == TYPE_I)
item.KanjiCode = KANJI_NOCNV;
std::wstring text;
std::tie(iRetCode, text) = Command(item.ctrl_skt, CancelCheckWork, L"TYPE {}"sv, (wchar_t)item.Type);
if(iRetCode/100 < FTP_RETRY)
{
if(item.hWndTrans != NULL)
{
// 同時接続対応
// AllTransSizeNow = 0;
AllTransSizeNow[item.ThreadCount] = 0;
if(DirList == NO)
DispTransFileInfo(item, IDS_MSGJPN086, TRUE, YES);
else
DispTransFileInfo(item, IDS_MSGJPN087, FALSE, NO);
}
if(BackgrndMessageProc() == NO)
{
if (GetCurHost().Pasv != YES)
iRetCode = TransferActive(&item, SendDownloadCommand, DownloadFile, CancelCheckWork);
else
iRetCode = TransferPassive(&item, SendDownloadCommand, DownloadFile, CancelCheckWork);
}
else
iRetCode = 500;
}
else
SetErrorMsg(std::move(text));
// エラーによってはダイアログが表示されない場合があるバグ対策
DispDownloadFinishMsg(&item, iRetCode);
}
else
{
DispTransFileInfo(item, IDS_MSGJPN088, TRUE, YES);
Notice(IDS_MSGJPN089, item.Remote);
iRetCode = 200;
}
return(iRetCode);
}
/*----- ダウンロードの実行 ----------------------------------------------------
*
* Parameter
* TRANSPACKET *Pkt : 転送ファイル情報
* SOCKET dSkt : データソケット
* int CreateMode : ファイル作成モード (CREATE_ALWAYS/OPEN_ALWAYS)
*
* Return Value
* int 応答コード
*
* Note
* 転送の経過表示は
* ダイアログを出す(Pkt->hWndTrans!=NULL)場合、インターバルタイマで経過を表示する
* ダイアログを出さない場合、このルーチンからDispDownloadSize()を呼ぶ
*----------------------------------------------------------------------------*/
static int DownloadFile(TRANSPACKET *Pkt, std::shared_ptr<SocketContext> dSkt, int CreateMode, int *CancelCheckWork) {
assert(dSkt);
assert(Pkt->ctrl_skt);
if (Pkt->ctrl_skt->IsSSLAttached() && !dSkt->AttachSSL(CancelCheckWork))
return 500;
#ifdef DISABLE_TRANSFER_NETWORK_BUFFERS
int buf_size = 0;
setsockopt(dSkt, SOL_SOCKET, SO_RCVBUF, (char*)&buf_size, sizeof(buf_size));
#elif defined(SET_BUFFER_SIZE)
for (int buf_size = SOCKBUF_SIZE; buf_size > 0; buf_size /= 2)
if (setsockopt(dSkt->handle, SOL_SOCKET, SO_RCVBUF, (char*)&buf_size, sizeof(buf_size)) == 0)
break;
#endif
Pkt->Abort = ABORT_NONE;
if (auto const attr = GetFileAttributesW(Pkt->Local.c_str()); attr != INVALID_FILE_ATTRIBUTES && (attr & FILE_ATTRIBUTE_READONLY))
if (Message<IDS_MSGJPN086>(IDS_REMOVE_READONLY, MB_YESNO) == IDYES)
SetFileAttributesW(Pkt->Local.c_str(), attr & ~FILE_ATTRIBUTE_READONLY);
auto opened = false;
if (std::ofstream os{ Pkt->Local, std::ios::binary | (CreateMode == OPEN_ALWAYS ? std::ios::ate : std::ios::trunc) }) {
opened = true;
if (Pkt->hWndTrans != NULL) {
TimeStart[Pkt->ThreadCount] = time(NULL);
SetTimer(Pkt->hWndTrans, TIMER_DISPLAY, DISPLAY_TIMING, NULL);
}
CodeConverter cc{ Pkt->KanjiCode, Pkt->KanjiCodeDesired, Pkt->KanaCnv != NO };
auto const result = dSkt->ReadAll(CancelCheckWork, [&Pkt, &cc, &os](std::vector<char> const& buf) {
if (auto converted = cc.Convert({ begin(buf), end(buf) }); !os.write(data(converted), size(converted))) {
Pkt->Abort = ABORT_DISKFULL;
return true;
}
Pkt->ExistSize += size_as<LONGLONG>(buf);
if (Pkt->hWndTrans != NULL)
AllTransSizeNow[Pkt->ThreadCount] += size_as<LONGLONG>(buf);
else
DispDownloadSize(Pkt->ExistSize); /* 転送ダイアログを出さない時の経過表示 */
return false;
});
if (result != ERROR_HANDLE_EOF) {
if (result == ERROR_OPERATION_ABORTED)
ForceAbort = YES;
if (Pkt->Abort == ABORT_NONE)
Pkt->Abort = ABORT_ERROR;
}
/* グラフ表示を更新 */
if (Pkt->hWndTrans != NULL) {