1
0

ScpFileSystem.cpp 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "ScpFileSystem.h"
  5. #include "Terminal.h"
  6. #include "Common.h"
  7. #include "Exceptions.h"
  8. #include "Interface.h"
  9. #include "TextsCore.h"
  10. #include "HelpCore.h"
  11. #include "SecureShell.h"
  12. #include <StrUtils.hpp>
  13. #include <stdio.h>
  14. //---------------------------------------------------------------------------
  15. #pragma package(smart_init)
  16. //---------------------------------------------------------------------------
  17. #define FILE_OPERATION_LOOP_TERMINAL FTerminal
  18. //---------------------------------------------------------------------------
  19. const int coRaiseExcept = 1;
  20. const int coExpectNoOutput = 2;
  21. const int coWaitForLastLine = 4;
  22. const int coOnlyReturnCode = 8;
  23. const int coIgnoreWarnings = 16;
  24. const int coReadProgress = 32;
  25. const int coIgnoreStdErr = 64;
  26. const int ecRaiseExcept = 1;
  27. const int ecIgnoreWarnings = 2;
  28. const int ecReadProgress = 4;
  29. const int ecIgnoreStdErr = 8;
  30. const int ecDefault = ecRaiseExcept;
  31. //---------------------------------------------------------------------------
  32. DERIVE_EXT_EXCEPTION(EScpFileSkipped, ESkipFile);
  33. //===========================================================================
  34. #define MaxShellCommand fsLang
  35. #define ShellCommandCount MaxShellCommand + 1
  36. #define MaxCommandLen 40
  37. struct TCommandType
  38. {
  39. int MinLines;
  40. int MaxLines;
  41. bool ModifiesFiles;
  42. bool ChangesDirectory;
  43. bool InteractiveCommand;
  44. wchar_t Command[MaxCommandLen];
  45. };
  46. // Only one character! See TSCPFileSystem::ReadCommandOutput()
  47. #define LastLineSeparator L":"
  48. #define LAST_LINE L"WinSCP: this is end-of-file"
  49. #define FIRST_LINE L"WinSCP: this is begin-of-file"
  50. extern const TCommandType DefaultCommandSet[];
  51. #define CHECK_CMD DebugAssert((Cmd >=0) && (Cmd <= MaxShellCommand))
  52. class TSessionData;
  53. //---------------------------------------------------------------------------
  54. class TCommandSet
  55. {
  56. private:
  57. TCommandType CommandSet[ShellCommandCount];
  58. TSessionData * FSessionData;
  59. UnicodeString FReturnVar;
  60. int __fastcall GetMaxLines(TFSCommand Cmd);
  61. int __fastcall GetMinLines(TFSCommand Cmd);
  62. bool __fastcall GetModifiesFiles(TFSCommand Cmd);
  63. bool __fastcall GetChangesDirectory(TFSCommand Cmd);
  64. bool __fastcall GetOneLineCommand(TFSCommand Cmd);
  65. void __fastcall SetCommands(TFSCommand Cmd, UnicodeString value);
  66. UnicodeString __fastcall GetCommands(TFSCommand Cmd);
  67. UnicodeString __fastcall GetFirstLine();
  68. bool __fastcall GetInteractiveCommand(TFSCommand Cmd);
  69. UnicodeString __fastcall GetLastLine();
  70. UnicodeString __fastcall GetReturnVar();
  71. public:
  72. __fastcall TCommandSet(TSessionData *aSessionData);
  73. void __fastcall Default();
  74. void __fastcall CopyFrom(TCommandSet * Source);
  75. UnicodeString __fastcall Command(TFSCommand Cmd, const TVarRec * args, int size);
  76. TStrings * __fastcall CreateCommandList();
  77. UnicodeString __fastcall FullCommand(TFSCommand Cmd, const TVarRec * args, int size);
  78. static UnicodeString __fastcall ExtractCommand(UnicodeString Command);
  79. __property int MaxLines[TFSCommand Cmd] = { read=GetMaxLines};
  80. __property int MinLines[TFSCommand Cmd] = { read=GetMinLines };
  81. __property bool ModifiesFiles[TFSCommand Cmd] = { read=GetModifiesFiles };
  82. __property bool ChangesDirectory[TFSCommand Cmd] = { read=GetChangesDirectory };
  83. __property bool OneLineCommand[TFSCommand Cmd] = { read=GetOneLineCommand };
  84. __property UnicodeString Commands[TFSCommand Cmd] = { read=GetCommands, write=SetCommands };
  85. __property UnicodeString FirstLine = { read = GetFirstLine };
  86. __property bool InteractiveCommand[TFSCommand Cmd] = { read = GetInteractiveCommand };
  87. __property UnicodeString LastLine = { read=GetLastLine };
  88. __property TSessionData * SessionData = { read=FSessionData, write=FSessionData };
  89. __property UnicodeString ReturnVar = { read=GetReturnVar, write=FReturnVar };
  90. };
  91. //===========================================================================
  92. const wchar_t NationalVars[][15] =
  93. {L"LANG", L"LANGUAGE", L"LC_CTYPE", L"LC_COLLATE", L"LC_MONETARY", L"LC_NUMERIC",
  94. L"LC_TIME", L"LC_MESSAGES", L"LC_ALL", L"HUMAN_BLOCKS", L"BLOCK_SIZE", L"LS_BLOCK_SIZE" };
  95. const wchar_t FullTimeOption[] = L"--full-time";
  96. //---------------------------------------------------------------------------
  97. #define F false
  98. #define T true
  99. // TODO: remove "mf" and "cd", it is implemented in TTerminal already
  100. const TCommandType DefaultCommandSet[ShellCommandCount] = {
  101. // min max mf cd ia command
  102. /*Null*/ { -1, -1, F, F, F, L"" },
  103. /*VarValue*/ { -1, -1, F, F, F, L"echo \"$%s\"" /* variable */ },
  104. /*LastLine*/ { -1, -1, F, F, F, L"echo \"%s" LastLineSeparator "%s\"" /* last line, return var */ },
  105. /*FirstLine*/ { -1, -1, F, F, F, L"echo \"%s\"" /* first line */ },
  106. /*CurrentDirectory*/ { 1, 1, F, F, F, L"pwd" },
  107. /*ChangeDirectory*/ { 0, 0, F, T, F, L"cd %s" /* directory */ },
  108. // list directory can be empty on permission denied, this is handled in ReadDirectory
  109. /*ListDirectory*/ { -1, -1, F, F, F, L"%s %s \"%s\"" /* listing command, options, directory */ },
  110. /*ListCurrentDirectory*/{ -1, -1, F, F, F, L"%s %s" /* listing command, options */ },
  111. /*ListFile*/ { 1, 1, F, F, F, L"%s -d %s \"%s\"" /* listing command, options, file/directory */ },
  112. /*LookupUserGroups*/ { 0, 1, F, F, F, L"groups" },
  113. /*CopyToRemote*/ { -1, -1, T, F, T, L"scp -r %s -d -t \"%s\"" /* options, directory */ },
  114. /*CopyToLocal*/ { -1, -1, F, F, T, L"scp -r %s -d -f \"%s\"" /* options, file */ },
  115. /*DeleteFile*/ { 0, 0, T, F, F, L"rm -f -r \"%s\"" /* file/directory */},
  116. /*RenameFile*/ { 0, 0, T, F, F, L"mv -f \"%s\" \"%s\"" /* file/directory, new name*/},
  117. /*CreateDirectory*/ { 0, 0, T, F, F, L"mkdir \"%s\"" /* new directory */},
  118. /*ChangeMode*/ { 0, 0, T, F, F, L"chmod %s %s \"%s\"" /* options, mode, filename */},
  119. /*ChangeGroup*/ { 0, 0, T, F, F, L"chgrp %s \"%s\" \"%s\"" /* options, group, filename */},
  120. /*ChangeOwner*/ { 0, 0, T, F, F, L"chown %s \"%s\" \"%s\"" /* options, owner, filename */},
  121. /*HomeDirectory*/ { 0, 0, F, T, F, L"cd" },
  122. /*Unset*/ { 0, 0, F, F, F, L"unset \"%s\"" /* variable */ },
  123. /*Unalias*/ { 0, 0, F, F, F, L"unalias \"%s\"" /* alias */ },
  124. /*CreateLink*/ { 0, 0, T, F, F, L"ln %s \"%s\" \"%s\"" /*symbolic (-s), filename, point to*/},
  125. /*CopyFile*/ { 0, 0, T, F, F, L"cp -p -r -f %s \"%s\" \"%s\"" /* file/directory, target name*/},
  126. /*AnyCommand*/ { 0, -1, T, T, F, L"%s" },
  127. /*Lang*/ { 0, 1, F, F, F, L"printenv LANG"}
  128. };
  129. #undef F
  130. #undef T
  131. //---------------------------------------------------------------------------
  132. __fastcall TCommandSet::TCommandSet(TSessionData *aSessionData):
  133. FSessionData(aSessionData), FReturnVar(L"")
  134. {
  135. DebugAssert(FSessionData);
  136. Default();
  137. }
  138. //---------------------------------------------------------------------------
  139. void __fastcall TCommandSet::CopyFrom(TCommandSet * Source)
  140. {
  141. memmove(&CommandSet, Source->CommandSet, sizeof(CommandSet));
  142. }
  143. //---------------------------------------------------------------------------
  144. void __fastcall TCommandSet::Default()
  145. {
  146. DebugAssert(sizeof(CommandSet) == sizeof(DefaultCommandSet));
  147. memmove(&CommandSet, &DefaultCommandSet, sizeof(CommandSet));
  148. }
  149. //---------------------------------------------------------------------------
  150. int __fastcall TCommandSet::GetMaxLines(TFSCommand Cmd)
  151. {
  152. CHECK_CMD;
  153. return CommandSet[Cmd].MaxLines;
  154. }
  155. //---------------------------------------------------------------------------
  156. int __fastcall TCommandSet::GetMinLines(TFSCommand Cmd)
  157. {
  158. CHECK_CMD;
  159. return CommandSet[Cmd].MinLines;
  160. }
  161. //---------------------------------------------------------------------------
  162. bool __fastcall TCommandSet::GetModifiesFiles(TFSCommand Cmd)
  163. {
  164. CHECK_CMD;
  165. return CommandSet[Cmd].ModifiesFiles;
  166. }
  167. //---------------------------------------------------------------------------
  168. bool __fastcall TCommandSet::GetChangesDirectory(TFSCommand Cmd)
  169. {
  170. CHECK_CMD;
  171. return CommandSet[Cmd].ChangesDirectory;
  172. }
  173. //---------------------------------------------------------------------------
  174. bool __fastcall TCommandSet::GetInteractiveCommand(TFSCommand Cmd)
  175. {
  176. CHECK_CMD;
  177. return CommandSet[Cmd].InteractiveCommand;
  178. }
  179. //---------------------------------------------------------------------------
  180. bool __fastcall TCommandSet::GetOneLineCommand(TFSCommand /*Cmd*/)
  181. {
  182. //CHECK_CMD;
  183. // #56: we send "echo last line" from all commands on same line
  184. // just as it was in 1.0
  185. return True; //CommandSet[Cmd].OneLineCommand;
  186. }
  187. //---------------------------------------------------------------------------
  188. void __fastcall TCommandSet::SetCommands(TFSCommand Cmd, UnicodeString value)
  189. {
  190. CHECK_CMD;
  191. wcscpy(CommandSet[Cmd].Command, value.SubString(1, MaxCommandLen - 1).c_str());
  192. }
  193. //---------------------------------------------------------------------------
  194. UnicodeString __fastcall TCommandSet::GetCommands(TFSCommand Cmd)
  195. {
  196. CHECK_CMD;
  197. return CommandSet[Cmd].Command;
  198. }
  199. //---------------------------------------------------------------------------
  200. UnicodeString __fastcall TCommandSet::Command(TFSCommand Cmd, const TVarRec * args, int size)
  201. {
  202. if (args) return Format(Commands[Cmd], args, size);
  203. else return Commands[Cmd];
  204. }
  205. //---------------------------------------------------------------------------
  206. UnicodeString __fastcall TCommandSet::FullCommand(TFSCommand Cmd, const TVarRec * args, int size)
  207. {
  208. UnicodeString Separator;
  209. if (OneLineCommand[Cmd]) Separator = L" ; ";
  210. else Separator = L"\n";
  211. UnicodeString Line = Command(Cmd, args, size);
  212. UnicodeString LastLineCmd =
  213. Command(fsLastLine, ARRAYOFCONST((LastLine, ReturnVar)));
  214. UnicodeString FirstLineCmd;
  215. if (InteractiveCommand[Cmd])
  216. FirstLineCmd = Command(fsFirstLine, ARRAYOFCONST((FirstLine))) + Separator;
  217. UnicodeString Result;
  218. if (!Line.IsEmpty())
  219. Result = FORMAT(L"%s%s%s%s", (FirstLineCmd, Line, Separator, LastLineCmd));
  220. else
  221. Result = FORMAT(L"%s%s", (FirstLineCmd, LastLineCmd));
  222. return Result;
  223. }
  224. //---------------------------------------------------------------------------
  225. UnicodeString __fastcall TCommandSet::GetFirstLine()
  226. {
  227. return FIRST_LINE;
  228. }
  229. //---------------------------------------------------------------------------
  230. UnicodeString __fastcall TCommandSet::GetLastLine()
  231. {
  232. return LAST_LINE;
  233. }
  234. //---------------------------------------------------------------------------
  235. UnicodeString __fastcall TCommandSet::GetReturnVar()
  236. {
  237. DebugAssert(SessionData);
  238. if (!FReturnVar.IsEmpty())
  239. {
  240. return UnicodeString(L'$') + FReturnVar;
  241. }
  242. else if (SessionData->DetectReturnVar)
  243. {
  244. return L'0';
  245. }
  246. else
  247. {
  248. return UnicodeString(L'$') + SessionData->ReturnVar;
  249. }
  250. }
  251. //---------------------------------------------------------------------------
  252. UnicodeString __fastcall TCommandSet::ExtractCommand(UnicodeString Command)
  253. {
  254. int P = Command.Pos(L" ");
  255. if (P > 0)
  256. {
  257. Command.SetLength(P-1);
  258. }
  259. return Command;
  260. }
  261. //---------------------------------------------------------------------------
  262. TStrings * __fastcall TCommandSet::CreateCommandList()
  263. {
  264. TStrings * CommandList = new TStringList();
  265. for (Integer Index = 0; Index < ShellCommandCount; Index++)
  266. {
  267. UnicodeString Cmd = Commands[(TFSCommand)Index];
  268. if (!Cmd.IsEmpty())
  269. {
  270. Cmd = ExtractCommand(Cmd);
  271. if ((Cmd != L"%s") && (CommandList->IndexOf(Cmd) < 0))
  272. CommandList->Add(Cmd);
  273. }
  274. }
  275. return CommandList;
  276. }
  277. //===========================================================================
  278. __fastcall TSCPFileSystem::TSCPFileSystem(TTerminal * ATerminal, TSecureShell * SecureShell):
  279. TCustomFileSystem(ATerminal)
  280. {
  281. FSecureShell = SecureShell;
  282. FCommandSet = new TCommandSet(FTerminal->SessionData);
  283. FLsFullTime = FTerminal->SessionData->SCPLsFullTime;
  284. FOutput = new TStringList();
  285. FProcessingCommand = false;
  286. FOnCaptureOutput = NULL;
  287. FFileSystemInfo.ProtocolBaseName = L"SCP";
  288. FFileSystemInfo.ProtocolName = FFileSystemInfo.ProtocolBaseName;
  289. }
  290. //---------------------------------------------------------------------------
  291. __fastcall TSCPFileSystem::~TSCPFileSystem()
  292. {
  293. delete FCommandSet;
  294. delete FOutput;
  295. delete FSecureShell;
  296. }
  297. //---------------------------------------------------------------------------
  298. void __fastcall TSCPFileSystem::Open()
  299. {
  300. // this is used for reconnects only
  301. FSecureShell->Open();
  302. }
  303. //---------------------------------------------------------------------------
  304. void __fastcall TSCPFileSystem::Close()
  305. {
  306. FSecureShell->Close();
  307. }
  308. //---------------------------------------------------------------------------
  309. bool __fastcall TSCPFileSystem::GetActive()
  310. {
  311. return FSecureShell->Active;
  312. }
  313. //---------------------------------------------------------------------------
  314. void __fastcall TSCPFileSystem::CollectUsage()
  315. {
  316. FSecureShell->CollectUsage();
  317. }
  318. //---------------------------------------------------------------------------
  319. const TSessionInfo & __fastcall TSCPFileSystem::GetSessionInfo()
  320. {
  321. return FSecureShell->GetSessionInfo();
  322. }
  323. //---------------------------------------------------------------------------
  324. const TFileSystemInfo & __fastcall TSCPFileSystem::GetFileSystemInfo(bool Retrieve)
  325. {
  326. if (FFileSystemInfo.AdditionalInfo.IsEmpty() && Retrieve)
  327. {
  328. UnicodeString UName;
  329. FTerminal->ExceptionOnFail = true;
  330. try
  331. {
  332. try
  333. {
  334. AnyCommand(L"uname -a", NULL);
  335. for (int Index = 0; Index < Output->Count; Index++)
  336. {
  337. if (Index > 0)
  338. {
  339. UName += L"; ";
  340. }
  341. UName += Output->Strings[Index];
  342. }
  343. }
  344. catch(...)
  345. {
  346. if (!FTerminal->Active)
  347. {
  348. throw;
  349. }
  350. }
  351. }
  352. __finally
  353. {
  354. FTerminal->ExceptionOnFail = false;
  355. }
  356. FFileSystemInfo.RemoteSystem = UName;
  357. }
  358. return FFileSystemInfo;
  359. }
  360. //---------------------------------------------------------------------------
  361. bool __fastcall TSCPFileSystem::TemporaryTransferFile(const UnicodeString & /*FileName*/)
  362. {
  363. return false;
  364. }
  365. //---------------------------------------------------------------------------
  366. bool __fastcall TSCPFileSystem::GetStoredCredentialsTried()
  367. {
  368. return FSecureShell->GetStoredCredentialsTried();
  369. }
  370. //---------------------------------------------------------------------------
  371. UnicodeString __fastcall TSCPFileSystem::GetUserName()
  372. {
  373. return FSecureShell->UserName;
  374. }
  375. //---------------------------------------------------------------------------
  376. void __fastcall TSCPFileSystem::Idle()
  377. {
  378. // Keep session alive
  379. if ((FTerminal->SessionData->PingType != ptOff) &&
  380. (Now() - FSecureShell->LastDataSent > FTerminal->SessionData->PingIntervalDT))
  381. {
  382. if ((FTerminal->SessionData->PingType == ptDummyCommand) &&
  383. FSecureShell->Ready)
  384. {
  385. if (!FProcessingCommand)
  386. {
  387. ExecCommand(fsNull, NULL, 0, 0);
  388. }
  389. else
  390. {
  391. FTerminal->LogEvent(L"Cannot send keepalive, command is being executed");
  392. // send at least SSH-level keepalive, if nothing else, it at least updates
  393. // LastDataSent, no the next keepalive attempt is postponed
  394. FSecureShell->KeepAlive();
  395. }
  396. }
  397. else
  398. {
  399. FSecureShell->KeepAlive();
  400. }
  401. }
  402. FSecureShell->Idle();
  403. }
  404. //---------------------------------------------------------------------------
  405. UnicodeString __fastcall TSCPFileSystem::AbsolutePath(UnicodeString Path, bool /*Local*/)
  406. {
  407. return ::AbsolutePath(CurrentDirectory, Path);
  408. }
  409. //---------------------------------------------------------------------------
  410. bool __fastcall TSCPFileSystem::IsCapable(int Capability) const
  411. {
  412. DebugAssert(FTerminal);
  413. switch (Capability) {
  414. case fcUserGroupListing:
  415. case fcModeChanging:
  416. case fcModeChangingUpload:
  417. case fcPreservingTimestampUpload:
  418. case fcGroupChanging:
  419. case fcOwnerChanging:
  420. case fcAnyCommand:
  421. case fcShellAnyCommand:
  422. case fcHardLink:
  423. case fcSymbolicLink:
  424. case fcResolveSymlink:
  425. case fcRename:
  426. case fcRemoteMove:
  427. case fcRemoteCopy:
  428. case fcRemoveCtrlZUpload:
  429. case fcRemoveBOMUpload:
  430. case fcCalculatingChecksum:
  431. case fcMoveOverExistingFile:
  432. return true;
  433. case fcTextMode:
  434. return FTerminal->SessionData->EOLType != FTerminal->Configuration->LocalEOLType;
  435. case fcAclChangingFiles:
  436. case fcNativeTextMode:
  437. case fcNewerOnlyUpload:
  438. case fcTimestampChanging:
  439. case fcLoadingAdditionalProperties:
  440. case fcCheckingSpaceAvailable:
  441. case fcIgnorePermErrors:
  442. case fcSecondaryShell: // has fcShellAnyCommand
  443. case fcGroupOwnerChangingByID: // by name
  444. case fcMoveToQueue:
  445. case fcLocking:
  446. case fcPreservingTimestampDirs:
  447. case fcResumeSupport:
  448. case fcSkipTransfer:
  449. case fcParallelTransfers: // does not implement cpNoRecurse
  450. case fcParallelFileTransfers:
  451. case fcTransferOut:
  452. case fcTransferIn:
  453. return false;
  454. case fcChangePassword:
  455. return FSecureShell->CanChangePassword();
  456. default:
  457. DebugFail();
  458. return false;
  459. }
  460. }
  461. //---------------------------------------------------------------------------
  462. void __fastcall TSCPFileSystem::EnsureLocation()
  463. {
  464. if (!FCachedDirectoryChange.IsEmpty())
  465. {
  466. FTerminal->LogEvent(FORMAT(L"Locating to cached directory \"%s\".",
  467. (FCachedDirectoryChange)));
  468. UnicodeString Directory = FCachedDirectoryChange;
  469. FCachedDirectoryChange = L"";
  470. try
  471. {
  472. ChangeDirectory(Directory);
  473. }
  474. catch(...)
  475. {
  476. // when location to cached directory fails, pretend again
  477. // location in cached directory
  478. // here used to be check (CurrentDirectory != Directory), but it is
  479. // false always (current directory is already set to cached directory),
  480. // making the condition below useless. check removed.
  481. if (FTerminal->Active)
  482. {
  483. FCachedDirectoryChange = Directory;
  484. }
  485. throw;
  486. }
  487. }
  488. }
  489. //---------------------------------------------------------------------------
  490. void __fastcall TSCPFileSystem::SendCommand(const UnicodeString Cmd)
  491. {
  492. EnsureLocation();
  493. UnicodeString Line;
  494. FSecureShell->ClearStdError();
  495. FReturnCode = 0;
  496. FOutput->Clear();
  497. // We suppose, that 'Cmd' already contains command that ensures,
  498. // that 'LastLine' will be printed
  499. FSecureShell->SendLine(Cmd);
  500. FProcessingCommand = true;
  501. }
  502. //---------------------------------------------------------------------------
  503. bool __fastcall TSCPFileSystem::IsTotalListingLine(const UnicodeString Line)
  504. {
  505. // On some hosts there is not "total" but "totalt". What's the reason??
  506. // see mail from "Jan Wiklund (SysOp)" <[email protected]>
  507. return !Line.SubString(1, 5).CompareIC(L"total");
  508. }
  509. //---------------------------------------------------------------------------
  510. bool __fastcall TSCPFileSystem::RemoveLastLine(UnicodeString & Line,
  511. int & ReturnCode, UnicodeString LastLine)
  512. {
  513. bool IsLastLine = false;
  514. if (LastLine.IsEmpty()) LastLine = LAST_LINE;
  515. // #55: fixed so, even when last line of command output does not
  516. // contain CR/LF, we can recognize last line
  517. int Pos = Line.Pos(LastLine);
  518. if (Pos)
  519. {
  520. // 2003-07-14: There must be nothing after return code number to
  521. // consider string as last line. This fixes bug with 'set' command
  522. // in console window
  523. UnicodeString ReturnCodeStr = Line.SubString(Pos + LastLine.Length() + 1,
  524. Line.Length() - Pos + LastLine.Length());
  525. if (TryStrToInt(ReturnCodeStr, ReturnCode))
  526. {
  527. IsLastLine = true;
  528. Line.SetLength(Pos - 1);
  529. }
  530. }
  531. return IsLastLine;
  532. }
  533. //---------------------------------------------------------------------------
  534. bool __fastcall TSCPFileSystem::IsLastLine(UnicodeString & Line)
  535. {
  536. bool Result = false;
  537. try
  538. {
  539. Result = RemoveLastLine(Line, FReturnCode, FCommandSet->LastLine);
  540. }
  541. catch (Exception &E)
  542. {
  543. FTerminal->TerminalError(&E, LoadStr(CANT_DETECT_RETURN_CODE));
  544. }
  545. return Result;
  546. }
  547. //---------------------------------------------------------------------------
  548. void __fastcall TSCPFileSystem::SkipFirstLine()
  549. {
  550. UnicodeString Line = FSecureShell->ReceiveLine();
  551. if (Line != FCommandSet->FirstLine)
  552. {
  553. FTerminal->TerminalError(NULL, FMTLOAD(FIRST_LINE_EXPECTED, (Line)));
  554. }
  555. }
  556. //---------------------------------------------------------------------------
  557. void __fastcall TSCPFileSystem::ReadCommandOutput(int Params, const UnicodeString * Cmd)
  558. {
  559. try
  560. {
  561. if (FLAGSET(Params, coWaitForLastLine))
  562. {
  563. UnicodeString Line;
  564. bool IsLast;
  565. unsigned int Total = 0;
  566. // #55: fixed so, even when last line of command output does not
  567. // contain CR/LF, we can recognize last line
  568. do
  569. {
  570. Line = FSecureShell->ReceiveLine();
  571. IsLast = IsLastLine(Line);
  572. if (!IsLast || !Line.IsEmpty())
  573. {
  574. FOutput->Add(Line);
  575. if (FLAGSET(Params, coReadProgress))
  576. {
  577. Total++;
  578. if (Total % 10 == 0)
  579. {
  580. bool Cancel; //dummy
  581. FTerminal->DoReadDirectoryProgress(Total, 0, Cancel);
  582. }
  583. }
  584. }
  585. }
  586. while (!IsLast);
  587. }
  588. if (FLAGSET(Params, coRaiseExcept))
  589. {
  590. UnicodeString Message = FSecureShell->GetStdError();
  591. if (FLAGSET(Params, coExpectNoOutput) && (FOutput->Count > 0))
  592. {
  593. AddToList(Message, FOutput->Text, L"\n");
  594. }
  595. while (!Message.IsEmpty() && (Message.LastDelimiter(L"\n\r") == Message.Length()))
  596. {
  597. Message.SetLength(Message.Length() - 1);
  598. }
  599. bool WrongReturnCode =
  600. (ReturnCode > 1) ||
  601. ((ReturnCode == 1) && FLAGCLEAR(Params, coIgnoreWarnings));
  602. if (FOnCaptureOutput != NULL)
  603. {
  604. FOnCaptureOutput(IntToStr(ReturnCode), cotExitCode);
  605. }
  606. if (FLAGSET(Params, coOnlyReturnCode))
  607. {
  608. if (WrongReturnCode)
  609. {
  610. FTerminal->TerminalError(FMTLOAD(COMMAND_FAILED_CODEONLY, (ReturnCode)));
  611. }
  612. }
  613. else
  614. {
  615. bool IsStdErrOnlyError = (FLAGCLEAR(Params, coIgnoreWarnings) && FLAGCLEAR(Params, coIgnoreStdErr));
  616. bool WrongOutput = !Message.IsEmpty() && ((FOutput->Count == 0) || IsStdErrOnlyError);
  617. if (WrongOutput || WrongReturnCode)
  618. {
  619. DebugAssert(Cmd != NULL);
  620. if (Message.IsEmpty())
  621. {
  622. FTerminal->TerminalError(FMTLOAD(COMMAND_FAILED_CODEONLY, (ReturnCode)));
  623. }
  624. else
  625. {
  626. throw ETerminal(MainInstructions(FMTLOAD(COMMAND_FAILED2, (*Cmd, ReturnCode))), Message);
  627. }
  628. }
  629. }
  630. }
  631. }
  632. __finally
  633. {
  634. FProcessingCommand = false;
  635. }
  636. }
  637. //---------------------------------------------------------------------------
  638. void __fastcall TSCPFileSystem::ExecCommand(const UnicodeString & Cmd, int Params,
  639. const UnicodeString & CmdString)
  640. {
  641. if (Params < 0)
  642. {
  643. Params = ecDefault;
  644. }
  645. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  646. SendCommand(Cmd);
  647. int COParams =
  648. coWaitForLastLine |
  649. FLAGMASK(FLAGSET(Params, ecRaiseExcept), coRaiseExcept) |
  650. FLAGMASK(FLAGSET(Params, ecIgnoreWarnings), coIgnoreWarnings) |
  651. FLAGMASK(FLAGSET(Params, ecReadProgress), coReadProgress) |
  652. FLAGMASK(FLAGSET(Params, ecIgnoreStdErr), coIgnoreStdErr);
  653. ReadCommandOutput(COParams, &CmdString);
  654. }
  655. //---------------------------------------------------------------------------
  656. void TSCPFileSystem::InvalidOutputError(const UnicodeString & Command)
  657. {
  658. FTerminal->TerminalError(FMTLOAD(INVALID_OUTPUT_ERROR, (Command, Output->Text)));
  659. }
  660. //---------------------------------------------------------------------------
  661. void __fastcall TSCPFileSystem::ExecCommand(TFSCommand Cmd, const TVarRec * args,
  662. int size, int Params)
  663. {
  664. if (Params < 0) Params = ecDefault;
  665. UnicodeString FullCommand = FCommandSet->FullCommand(Cmd, args, size);
  666. UnicodeString Command = FCommandSet->Command(Cmd, args, size);
  667. ExecCommand(FullCommand, Params, Command);
  668. if (Params & ecRaiseExcept)
  669. {
  670. Integer MinL = FCommandSet->MinLines[Cmd];
  671. Integer MaxL = FCommandSet->MaxLines[Cmd];
  672. if (((MinL >= 0) && (MinL > FOutput->Count)) ||
  673. ((MaxL >= 0) && (MaxL > FOutput->Count)))
  674. {
  675. InvalidOutputError(FullCommand);
  676. }
  677. }
  678. }
  679. //---------------------------------------------------------------------------
  680. UnicodeString __fastcall TSCPFileSystem::GetCurrentDirectory()
  681. {
  682. return FCurrentDirectory;
  683. }
  684. //---------------------------------------------------------------------------
  685. void __fastcall TSCPFileSystem::DoStartup()
  686. {
  687. // Capabilities of SCP protocol are fixed
  688. FTerminal->SaveCapabilities(FFileSystemInfo);
  689. // SkipStartupMessage and DetectReturnVar must succeed,
  690. // otherwise session is to be closed.
  691. try
  692. {
  693. FTerminal->ExceptionOnFail = true;
  694. SkipStartupMessage();
  695. if (FTerminal->SessionData->DetectReturnVar) DetectReturnVar();
  696. FTerminal->ExceptionOnFail = false;
  697. }
  698. catch (Exception & E)
  699. {
  700. FTerminal->FatalError(&E, L"");
  701. }
  702. // Needs to be done before UnsetNationalVars()
  703. DetectUtf();
  704. #define COND_OPER(OPER) if (FTerminal->SessionData->OPER) OPER()
  705. COND_OPER(ClearAliases);
  706. COND_OPER(UnsetNationalVars);
  707. #undef COND_OPER
  708. }
  709. //---------------------------------------------------------------------------
  710. void __fastcall TSCPFileSystem::DetectUtf()
  711. {
  712. switch (FTerminal->SessionData->NotUtf)
  713. {
  714. case asOn:
  715. FSecureShell->UtfStrings = false; // noop
  716. break;
  717. case asOff:
  718. FSecureShell->UtfStrings = true;
  719. break;
  720. default:
  721. DebugFail();
  722. case asAuto:
  723. FSecureShell->UtfStrings = false; // noop
  724. try
  725. {
  726. ExecCommand(fsLang, NULL, 0, false);
  727. if ((FOutput->Count >= 1) &&
  728. ContainsText(FOutput->Strings[0], L"UTF-8"))
  729. {
  730. FSecureShell->UtfStrings = true;
  731. }
  732. }
  733. catch (Exception & E)
  734. {
  735. // ignore non-fatal errors
  736. if (!FTerminal->Active)
  737. {
  738. throw;
  739. }
  740. }
  741. break;
  742. }
  743. if (FSecureShell->UtfStrings)
  744. {
  745. FTerminal->LogEvent(L"We will use UTF-8");
  746. }
  747. else
  748. {
  749. FTerminal->LogEvent(L"We will not use UTF-8");
  750. }
  751. }
  752. //---------------------------------------------------------------------------
  753. void __fastcall TSCPFileSystem::SkipStartupMessage()
  754. {
  755. try
  756. {
  757. FTerminal->LogEvent(L"Skipping host startup message (if any).");
  758. ExecCommand(fsNull, NULL, 0, 0);
  759. }
  760. catch (Exception & E)
  761. {
  762. FTerminal->CommandError(&E, LoadStr(SKIP_STARTUP_MESSAGE_ERROR), 0, HELP_SKIP_STARTUP_MESSAGE_ERROR);
  763. }
  764. }
  765. //---------------------------------------------------------------------------
  766. void __fastcall TSCPFileSystem::LookupUsersGroups()
  767. {
  768. ExecCommand(fsLookupUsersGroups);
  769. FTerminal->FUsers.Clear();
  770. FTerminal->FGroups.Clear();
  771. if (FOutput->Count > 0)
  772. {
  773. UnicodeString Groups = FOutput->Strings[0];
  774. while (!Groups.IsEmpty())
  775. {
  776. UnicodeString NewGroup = CutToChar(Groups, L' ', false);
  777. FTerminal->FGroups.Add(TRemoteToken(NewGroup));
  778. FTerminal->FMembership.Add(TRemoteToken(NewGroup));
  779. }
  780. }
  781. }
  782. //---------------------------------------------------------------------------
  783. void __fastcall TSCPFileSystem::DetectReturnVar()
  784. {
  785. // This suppose that something was already executed (probably SkipStartupMessage())
  786. // or return code variable is already set on start up.
  787. try
  788. {
  789. // #60 17.10.01: "status" and "?" switched
  790. UnicodeString ReturnVars[2] = { L"status", L"?" };
  791. UnicodeString NewReturnVar = L"";
  792. FTerminal->LogEvent(L"Detecting variable containing return code of last command.");
  793. for (int Index = 0; Index < 2; Index++)
  794. {
  795. bool Success = true;
  796. try
  797. {
  798. FTerminal->LogEvent(FORMAT(L"Trying \"$%s\".", (ReturnVars[Index])));
  799. ExecCommand(fsVarValue, ARRAYOFCONST((ReturnVars[Index])));
  800. if ((Output->Count != 1) || (StrToIntDef(Output->Strings[0], 256) > 255))
  801. {
  802. FTerminal->LogEvent(L"The response is not numerical exit code");
  803. Abort();
  804. }
  805. }
  806. catch (EFatal &E)
  807. {
  808. // if fatal error occurs, we need to exit ...
  809. throw;
  810. }
  811. catch (Exception &E)
  812. {
  813. // ...otherwise, we will try next variable (if any)
  814. Success = false;
  815. }
  816. if (Success)
  817. {
  818. NewReturnVar = ReturnVars[Index];
  819. break;
  820. }
  821. }
  822. if (NewReturnVar.IsEmpty())
  823. {
  824. EXCEPTION;
  825. }
  826. else
  827. {
  828. FCommandSet->ReturnVar = NewReturnVar;
  829. FTerminal->LogEvent(FORMAT(L"Return code variable \"%s\" selected.",
  830. (FCommandSet->ReturnVar)));
  831. }
  832. }
  833. catch (Exception &E)
  834. {
  835. FTerminal->CommandError(&E, LoadStr(DETECT_RETURNVAR_ERROR));
  836. }
  837. }
  838. //---------------------------------------------------------------------------
  839. void __fastcall TSCPFileSystem::ClearAlias(UnicodeString Alias)
  840. {
  841. if (!Alias.IsEmpty())
  842. {
  843. // this command usually fails, because there will never be
  844. // aliases on all commands -> see last False parameter
  845. ExecCommand(fsUnalias, ARRAYOFCONST((Alias)), false);
  846. }
  847. }
  848. //---------------------------------------------------------------------------
  849. void __fastcall TSCPFileSystem::ClearAliases()
  850. {
  851. try
  852. {
  853. FTerminal->LogEvent(L"Clearing all aliases.");
  854. ClearAlias(TCommandSet::ExtractCommand(FTerminal->SessionData->ListingCommand));
  855. TStrings * CommandList = FCommandSet->CreateCommandList();
  856. try
  857. {
  858. for (int Index = 0; Index < CommandList->Count; Index++)
  859. {
  860. ClearAlias(CommandList->Strings[Index]);
  861. }
  862. }
  863. __finally
  864. {
  865. delete CommandList;
  866. }
  867. }
  868. catch (Exception &E)
  869. {
  870. FTerminal->CommandError(&E, LoadStr(UNALIAS_ALL_ERROR));
  871. }
  872. }
  873. //---------------------------------------------------------------------------
  874. void __fastcall TSCPFileSystem::UnsetNationalVars()
  875. {
  876. try
  877. {
  878. FTerminal->LogEvent(L"Clearing national user variables.");
  879. for (size_t Index = 0; Index < LENOF(NationalVars); Index++)
  880. {
  881. ExecCommand(fsUnset, ARRAYOFCONST((NationalVars[Index])), false);
  882. }
  883. }
  884. catch (Exception &E)
  885. {
  886. FTerminal->CommandError(&E, LoadStr(UNSET_NATIONAL_ERROR));
  887. }
  888. }
  889. //---------------------------------------------------------------------------
  890. void __fastcall TSCPFileSystem::ReadCurrentDirectory()
  891. {
  892. if (FCachedDirectoryChange.IsEmpty())
  893. {
  894. ExecCommand(fsCurrentDirectory);
  895. FCurrentDirectory = UnixExcludeTrailingBackslash(FOutput->Strings[0]);
  896. }
  897. else
  898. {
  899. FCurrentDirectory = FCachedDirectoryChange;
  900. }
  901. }
  902. //---------------------------------------------------------------------------
  903. void __fastcall TSCPFileSystem::HomeDirectory()
  904. {
  905. ExecCommand(fsHomeDirectory);
  906. }
  907. //---------------------------------------------------------------------------
  908. void __fastcall TSCPFileSystem::AnnounceFileListOperation()
  909. {
  910. // noop
  911. }
  912. //---------------------------------------------------------------------------
  913. void __fastcall TSCPFileSystem::ChangeDirectory(const UnicodeString Directory)
  914. {
  915. UnicodeString ToDir;
  916. // This effectivelly disallows entering subdirectories starting with ~ and containing space
  917. if (!Directory.IsEmpty() &&
  918. ((Directory[1] != L'~') || (Directory.SubString(1, 2) == L"~ ")))
  919. {
  920. ToDir = ShellQuoteStr(Directory);
  921. }
  922. else
  923. {
  924. ToDir = DelimitStr(Directory);
  925. }
  926. ExecCommand(fsChangeDirectory, ARRAYOFCONST((ToDir)));
  927. FCachedDirectoryChange = L"";
  928. }
  929. //---------------------------------------------------------------------------
  930. void __fastcall TSCPFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  931. {
  932. FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
  933. }
  934. //---------------------------------------------------------------------------
  935. void __fastcall TSCPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  936. {
  937. DebugAssert(FileList);
  938. // emptying file list moved before command execution
  939. FileList->Reset();
  940. bool Again;
  941. do
  942. {
  943. Again = false;
  944. try
  945. {
  946. int Params = ecDefault | ecReadProgress |
  947. FLAGMASK(FTerminal->SessionData->IgnoreLsWarnings, ecIgnoreWarnings);
  948. const wchar_t * Options =
  949. ((FLsFullTime == asAuto) || (FLsFullTime == asOn)) ? FullTimeOption : L"";
  950. bool ListCurrentDirectory = (FileList->Directory == FTerminal->CurrentDirectory);
  951. if (ListCurrentDirectory)
  952. {
  953. FTerminal->LogEvent(L"Listing current directory.");
  954. ExecCommand(fsListCurrentDirectory,
  955. ARRAYOFCONST((FTerminal->SessionData->ListingCommand, Options)), Params);
  956. }
  957. else
  958. {
  959. FTerminal->LogEvent(FORMAT(L"Listing directory \"%s\".",
  960. (FileList->Directory)));
  961. ExecCommand(fsListDirectory,
  962. ARRAYOFCONST((FTerminal->SessionData->ListingCommand, Options,
  963. DelimitStr(FileList->Directory))),
  964. Params);
  965. }
  966. // If output is not empty, we have successfully got file listing,
  967. // otherwise there was an error, in case it was "permission denied"
  968. // we try to get at least parent directory (see "else" statement below)
  969. if (FOutput->Count > 0)
  970. {
  971. // Copy LS command output, because eventual symlink analysis would
  972. // modify FTerminal->Output
  973. TStringList * OutputCopy = new TStringList();
  974. try
  975. {
  976. OutputCopy->Assign(FOutput);
  977. // delete leading "total xxx" line
  978. // On some hosts there is not "total" but "totalt". What's the reason??
  979. // see mail from "Jan Wiklund (SysOp)" <[email protected]>
  980. if (IsTotalListingLine(OutputCopy->Strings[0]))
  981. {
  982. OutputCopy->Delete(0);
  983. }
  984. for (int Index = 0; Index < OutputCopy->Count; Index++)
  985. {
  986. UnicodeString OutputLine = OutputCopy->Strings[Index];
  987. if (!OutputLine.IsEmpty())
  988. {
  989. std::unique_ptr<TRemoteFile> File(CreateRemoteFile(OutputCopy->Strings[Index]));
  990. if (FTerminal->IsValidFile(File.get()))
  991. {
  992. FileList->AddFile(File.release());
  993. }
  994. }
  995. }
  996. }
  997. __finally
  998. {
  999. delete OutputCopy;
  1000. }
  1001. }
  1002. else
  1003. {
  1004. bool Empty;
  1005. if (ListCurrentDirectory)
  1006. {
  1007. // Empty file list -> probably "permission denied", we
  1008. // at least get link to parent directory ("..")
  1009. TRemoteFile * File = FTerminal->ReadFile(UnixCombinePaths(FTerminal->FFiles->Directory, PARENTDIRECTORY));
  1010. Empty = (File == NULL);
  1011. if (!Empty)
  1012. {
  1013. DebugAssert(File->IsParentDirectory);
  1014. FileList->AddFile(File);
  1015. }
  1016. }
  1017. else
  1018. {
  1019. Empty = true;
  1020. }
  1021. if (Empty)
  1022. {
  1023. throw ExtException(
  1024. NULL, FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)),
  1025. HELP_EMPTY_DIRECTORY);
  1026. }
  1027. }
  1028. if (FLsFullTime == asAuto)
  1029. {
  1030. FTerminal->LogEvent(
  1031. FORMAT(L"Directory listing with %s succeed, next time all errors during "
  1032. "directory listing will be displayed immediately.",
  1033. (FullTimeOption)));
  1034. FLsFullTime = asOn;
  1035. }
  1036. }
  1037. catch(Exception & E)
  1038. {
  1039. if (FTerminal->Active)
  1040. {
  1041. if (FLsFullTime == asAuto)
  1042. {
  1043. FTerminal->Log->AddException(&E);
  1044. FLsFullTime = asOff;
  1045. Again = true;
  1046. FTerminal->LogEvent(
  1047. FORMAT(L"Directory listing with %s failed, try again regular listing.",
  1048. (FullTimeOption)));
  1049. }
  1050. else
  1051. {
  1052. throw;
  1053. }
  1054. }
  1055. else
  1056. {
  1057. throw;
  1058. }
  1059. }
  1060. }
  1061. while (Again);
  1062. }
  1063. //---------------------------------------------------------------------------
  1064. void __fastcall TSCPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  1065. TRemoteFile *& File)
  1066. {
  1067. CustomReadFile(SymlinkFile->LinkTo, File, SymlinkFile);
  1068. }
  1069. //---------------------------------------------------------------------------
  1070. void __fastcall TSCPFileSystem::ReadFile(const UnicodeString FileName,
  1071. TRemoteFile *& File)
  1072. {
  1073. CustomReadFile(FileName, File, NULL);
  1074. }
  1075. //---------------------------------------------------------------------------
  1076. TRemoteFile * __fastcall TSCPFileSystem::CreateRemoteFile(
  1077. const UnicodeString & ListingStr, TRemoteFile * LinkedByFile)
  1078. {
  1079. TRemoteFile * File = new TRemoteFile(LinkedByFile);
  1080. try
  1081. {
  1082. File->Terminal = FTerminal;
  1083. File->ListingStr = ListingStr;
  1084. File->ShiftTimeInSeconds(TimeToSeconds(FTerminal->SessionData->TimeDifference));
  1085. File->Complete();
  1086. }
  1087. catch(...)
  1088. {
  1089. delete File;
  1090. throw;
  1091. }
  1092. return File;
  1093. }
  1094. //---------------------------------------------------------------------------
  1095. void __fastcall TSCPFileSystem::CustomReadFile(const UnicodeString FileName,
  1096. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  1097. {
  1098. File = NULL;
  1099. int Params = ecDefault |
  1100. FLAGMASK(FTerminal->SessionData->IgnoreLsWarnings, ecIgnoreWarnings);
  1101. // the auto-detection of --full-time support is not implemented for fsListFile,
  1102. // so we use it only if we already know that it is supported (asOn).
  1103. const wchar_t * Options = (FLsFullTime == asOn) ? FullTimeOption : L"";
  1104. ExecCommand(fsListFile,
  1105. ARRAYOFCONST((FTerminal->SessionData->ListingCommand, Options, DelimitStr(FileName))),
  1106. Params);
  1107. if (FOutput->Count)
  1108. {
  1109. int LineIndex = 0;
  1110. if (IsTotalListingLine(FOutput->Strings[LineIndex]) && FOutput->Count > 1)
  1111. {
  1112. LineIndex++;
  1113. }
  1114. File = CreateRemoteFile(FOutput->Strings[LineIndex], ALinkedByFile);
  1115. }
  1116. }
  1117. //---------------------------------------------------------------------------
  1118. void __fastcall TSCPFileSystem::DeleteFile(const UnicodeString FileName,
  1119. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  1120. {
  1121. DebugUsedParam(File);
  1122. DebugUsedParam(Params);
  1123. Action.Recursive();
  1124. DebugAssert(FLAGCLEAR(Params, dfNoRecursive) || (File && File->IsSymLink));
  1125. ExecCommand(fsDeleteFile, ARRAYOFCONST((DelimitStr(FileName))));
  1126. }
  1127. //---------------------------------------------------------------------------
  1128. void __fastcall TSCPFileSystem::RenameFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  1129. const UnicodeString NewName)
  1130. {
  1131. ExecCommand(fsRenameFile, ARRAYOFCONST((DelimitStr(FileName), DelimitStr(NewName))));
  1132. }
  1133. //---------------------------------------------------------------------------
  1134. void __fastcall TSCPFileSystem::CopyFile(const UnicodeString FileName, const TRemoteFile * /*File*/,
  1135. const UnicodeString NewName)
  1136. {
  1137. UnicodeString DelimitedFileName = DelimitStr(FileName);
  1138. UnicodeString DelimitedNewName = DelimitStr(NewName);
  1139. const UnicodeString AdditionalSwitches = L"-T";
  1140. try
  1141. {
  1142. ExecCommand(fsCopyFile, ARRAYOFCONST((AdditionalSwitches, DelimitedFileName, DelimitedNewName)));
  1143. }
  1144. catch (Exception & E)
  1145. {
  1146. if (FTerminal->Active)
  1147. {
  1148. // The -T is GNU switch and may not be available on all platforms.
  1149. // https://lists.gnu.org/archive/html/bug-coreutils/2004-07/msg00000.html
  1150. FTerminal->LogEvent(FORMAT(L"Attempt with %s failed, trying without", (AdditionalSwitches)));
  1151. ExecCommand(fsCopyFile, ARRAYOFCONST((L"", DelimitedFileName, DelimitedNewName)));
  1152. }
  1153. else
  1154. {
  1155. throw;
  1156. }
  1157. }
  1158. }
  1159. //---------------------------------------------------------------------------
  1160. void __fastcall TSCPFileSystem::CreateDirectory(const UnicodeString & DirName, bool /*Encrypt*/)
  1161. {
  1162. ExecCommand(fsCreateDirectory, ARRAYOFCONST((DelimitStr(DirName))));
  1163. }
  1164. //---------------------------------------------------------------------------
  1165. void __fastcall TSCPFileSystem::CreateLink(const UnicodeString FileName,
  1166. const UnicodeString PointTo, bool Symbolic)
  1167. {
  1168. ExecCommand(fsCreateLink,
  1169. ARRAYOFCONST((Symbolic ? L"-s" : L"", DelimitStr(PointTo), DelimitStr(FileName))));
  1170. }
  1171. //---------------------------------------------------------------------------
  1172. void __fastcall TSCPFileSystem::ChangeFileToken(const UnicodeString & DelimitedName,
  1173. const TRemoteToken & Token, TFSCommand Cmd, const UnicodeString & RecursiveStr)
  1174. {
  1175. UnicodeString Str;
  1176. if (Token.IDValid)
  1177. {
  1178. Str = IntToStr(int(Token.ID));
  1179. }
  1180. else if (Token.NameValid)
  1181. {
  1182. Str = Token.Name;
  1183. }
  1184. if (!Str.IsEmpty())
  1185. {
  1186. ExecCommand(Cmd, ARRAYOFCONST((RecursiveStr, Str, DelimitedName)));
  1187. }
  1188. }
  1189. //---------------------------------------------------------------------------
  1190. void __fastcall TSCPFileSystem::ChangeFileProperties(const UnicodeString FileName,
  1191. const TRemoteFile * File, const TRemoteProperties * Properties,
  1192. TChmodSessionAction & Action)
  1193. {
  1194. DebugAssert(Properties);
  1195. int Directory = ((File == NULL) ? -1 : (File->IsDirectory ? 1 : 0));
  1196. bool IsDirectory = (Directory > 0);
  1197. bool Recursive = Properties->Recursive && IsDirectory;
  1198. UnicodeString RecursiveStr = Recursive ? L"-R" : L"";
  1199. UnicodeString DelimitedName = DelimitStr(FileName);
  1200. // change group before permissions as chgrp change permissions
  1201. if (Properties->Valid.Contains(vpGroup))
  1202. {
  1203. ChangeFileToken(DelimitedName, Properties->Group, fsChangeGroup, RecursiveStr);
  1204. }
  1205. if (Properties->Valid.Contains(vpOwner))
  1206. {
  1207. ChangeFileToken(DelimitedName, Properties->Owner, fsChangeOwner, RecursiveStr);
  1208. }
  1209. if (Properties->Valid.Contains(vpRights))
  1210. {
  1211. TRights Rights = Properties->Rights;
  1212. // if we don't set modes recursively, we may add X at once with other
  1213. // options. Otherwise we have to add X after recursive command
  1214. if (!Recursive && IsDirectory && Properties->AddXToDirectories)
  1215. Rights.AddExecute();
  1216. Action.Rights(Rights);
  1217. if (Recursive)
  1218. {
  1219. Action.Recursive();
  1220. }
  1221. if ((Rights.NumberSet | Rights.NumberUnset) != TRights::rfNo)
  1222. {
  1223. ExecCommand(fsChangeMode,
  1224. ARRAYOFCONST((RecursiveStr, Rights.GetChmodStr(Directory), DelimitedName)));
  1225. }
  1226. // if file is directory and we do recursive mode settings with
  1227. // add-x-to-directories option on, add those X
  1228. if (Recursive && IsDirectory && Properties->AddXToDirectories)
  1229. {
  1230. Rights.AddExecute();
  1231. ExecCommand(fsChangeMode,
  1232. ARRAYOFCONST((L"", Rights.GetChmodStr(Directory), DelimitedName)));
  1233. }
  1234. }
  1235. else
  1236. {
  1237. Action.Cancel();
  1238. }
  1239. DebugAssert(!Properties->Valid.Contains(vpLastAccess));
  1240. DebugAssert(!Properties->Valid.Contains(vpModification));
  1241. }
  1242. //---------------------------------------------------------------------------
  1243. bool __fastcall TSCPFileSystem::LoadFilesProperties(TStrings * /*FileList*/ )
  1244. {
  1245. DebugFail();
  1246. return false;
  1247. }
  1248. //---------------------------------------------------------------------------
  1249. UnicodeString TSCPFileSystem::CalculateFilesChecksumInitialize(const UnicodeString & Alg)
  1250. {
  1251. std::unique_ptr<TStrings> Algs(new TStringList());
  1252. GetSupportedChecksumAlgs(Algs.get());
  1253. return FindIdent(Alg, Algs.get());
  1254. }
  1255. //---------------------------------------------------------------------------
  1256. UnicodeString TSCPFileSystem::ParseFileChecksum(
  1257. const UnicodeString & Line, const UnicodeString & FileName, const UnicodeString & Command)
  1258. {
  1259. int P = Line.Pos(L" ");
  1260. if ((P < 0) ||
  1261. (P == Line.Length()) ||
  1262. ((Line[P + 1] != L' ') && (Line[P + 1] != L'*')) ||
  1263. (Line.SubString(P + 2, Line.Length() - P - 1) != FileName))
  1264. {
  1265. InvalidOutputError(Command);
  1266. }
  1267. return Line.SubString(1, P - 1);
  1268. }
  1269. //---------------------------------------------------------------------------
  1270. void TSCPFileSystem::ProcessFileChecksum(
  1271. TCalculatedChecksumEvent OnCalculatedChecksum, TChecksumSessionAction & Action, TFileOperationProgressType * OperationProgress,
  1272. bool FirstLevel, const UnicodeString & FileName, const UnicodeString & Alg, const UnicodeString & Checksum)
  1273. {
  1274. bool Success = !Checksum.IsEmpty();
  1275. if (Success)
  1276. {
  1277. if (OnCalculatedChecksum != NULL)
  1278. {
  1279. OnCalculatedChecksum(UnixExtractFileName(FileName), Alg, Checksum);
  1280. }
  1281. Action.Checksum(Alg, Checksum);
  1282. }
  1283. if (FirstLevel)
  1284. {
  1285. TOnceDoneOperation OnceDoneOperation; // not used
  1286. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1287. }
  1288. }
  1289. //---------------------------------------------------------------------------
  1290. void __fastcall TSCPFileSystem::CalculateFilesChecksum(
  1291. const UnicodeString & Alg, TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  1292. TFileOperationProgressType * OperationProgress, bool FirstLevel)
  1293. {
  1294. FTerminal->CalculateSubFoldersChecksum(Alg, FileList, OnCalculatedChecksum, OperationProgress, FirstLevel);
  1295. TStrings * AlgDefs = FTerminal->GetShellChecksumAlgDefs();
  1296. int AlgIndex = AlgDefs->IndexOfName(Alg);
  1297. UnicodeString AlgCommand = (AlgIndex >= 0) ? AlgDefs->ValueFromIndex[AlgIndex] : Alg;
  1298. int Index = 0;
  1299. while ((Index < FileList->Count) && !OperationProgress->Cancel)
  1300. {
  1301. std::unique_ptr<TStrings> BatchFileList(new TStringList());
  1302. UnicodeString FileListCommandLine;
  1303. __int64 BatchSize = 0;
  1304. while (Index < FileList->Count)
  1305. {
  1306. TRemoteFile * File = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]));
  1307. if (!File->IsDirectory)
  1308. {
  1309. UnicodeString FileName = FileList->Strings[Index];
  1310. UnicodeString FileListCommandLineBak = FileListCommandLine;
  1311. AddToShellFileListCommandLine(FileListCommandLine, FileName);
  1312. BatchSize += File->Size;
  1313. if (!FileListCommandLineBak.IsEmpty() &&
  1314. ((FileListCommandLine.Length() > 2048) ||
  1315. (BatchSize > 1024*1024*1024)))
  1316. {
  1317. FileListCommandLine = FileListCommandLineBak;
  1318. break;
  1319. }
  1320. else
  1321. {
  1322. BatchFileList->AddObject(FileName, File);
  1323. }
  1324. }
  1325. Index++;
  1326. }
  1327. if (!FileListCommandLine.IsEmpty())
  1328. {
  1329. bool IndividualCommands = false;
  1330. std::unique_ptr<TStrings> BatchChecksums(new TStringList());
  1331. try
  1332. {
  1333. UnicodeString BatchCommand = FORMAT(L"%s %s", (AlgCommand, FileListCommandLine));
  1334. AnyCommand(BatchCommand, NULL);
  1335. if (Output->Count != BatchFileList->Count)
  1336. {
  1337. InvalidOutputError(BatchCommand);
  1338. }
  1339. // First do everything that can throw.
  1340. // Only once everything is checked, distribute the results.
  1341. for (int BatchIndex = 0; BatchIndex < BatchFileList->Count; BatchIndex++)
  1342. {
  1343. UnicodeString FileName = BatchFileList->Strings[BatchIndex];
  1344. UnicodeString Line = Output->Strings[BatchIndex];
  1345. UnicodeString Checksum = ParseFileChecksum(Line, FileName, BatchCommand);
  1346. BatchChecksums->Add(Checksum);
  1347. }
  1348. }
  1349. catch (Exception & E)
  1350. {
  1351. if (!FTerminal->Active)
  1352. {
  1353. throw;
  1354. }
  1355. else
  1356. {
  1357. IndividualCommands = true;
  1358. }
  1359. }
  1360. if (!IndividualCommands)
  1361. {
  1362. // None of this should throw
  1363. for (int BatchIndex = 0; BatchIndex < BatchFileList->Count; BatchIndex++)
  1364. {
  1365. UnicodeString FileName = BatchFileList->Strings[BatchIndex];
  1366. TRemoteFile * File = DebugNotNull(dynamic_cast<TRemoteFile *>(BatchFileList->Objects[BatchIndex]));
  1367. TChecksumSessionAction Action(FTerminal->ActionLog);
  1368. Action.FileName(File->FullFileName);
  1369. OperationProgress->SetFile(FileName);
  1370. UnicodeString Checksum = BatchChecksums->Strings[BatchIndex];
  1371. ProcessFileChecksum(OnCalculatedChecksum, Action, OperationProgress, FirstLevel, FileName, Alg, Checksum);
  1372. }
  1373. }
  1374. else
  1375. {
  1376. FTerminal->LogEvent(
  1377. L"Batch checksum calculation failed, falling back to calculating checksum individually for each file...");
  1378. for (int BatchIndex = 0; BatchIndex < BatchFileList->Count; BatchIndex++)
  1379. {
  1380. TRemoteFile * File = DebugNotNull(dynamic_cast<TRemoteFile *>(BatchFileList->Objects[BatchIndex]));
  1381. TChecksumSessionAction Action(FTerminal->ActionLog);
  1382. try
  1383. {
  1384. UnicodeString FileName = BatchFileList->Strings[BatchIndex];
  1385. OperationProgress->SetFile(FileName);
  1386. Action.FileName(File->FullFileName);
  1387. UnicodeString Checksum;
  1388. try
  1389. {
  1390. UnicodeString Command = FORMAT(L"%s %s", (AlgCommand, ShellQuoteStr(FileName)));
  1391. AnyCommand(Command, NULL);
  1392. if (Output->Count != 1)
  1393. {
  1394. InvalidOutputError(Command);
  1395. }
  1396. UnicodeString Line = Output->Strings[0];
  1397. Checksum = ParseFileChecksum(Line, FileName, Command);
  1398. }
  1399. __finally
  1400. {
  1401. ProcessFileChecksum(OnCalculatedChecksum, Action, OperationProgress, FirstLevel, FileName, Alg, Checksum);
  1402. }
  1403. }
  1404. catch (Exception & E)
  1405. {
  1406. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1407. UnicodeString Error = FMTLOAD(CHECKSUM_ERROR, (File->FullFileName));
  1408. FTerminal->CommandError(&E, Error);
  1409. // Abort loop.
  1410. // TODO: retries? resume?
  1411. BatchIndex = BatchFileList->Count;
  1412. Index = FileList->Count;
  1413. }
  1414. }
  1415. }
  1416. }
  1417. }
  1418. }
  1419. //---------------------------------------------------------------------------
  1420. void __fastcall TSCPFileSystem::CustomCommandOnFile(const UnicodeString FileName,
  1421. const TRemoteFile * File, UnicodeString Command, int Params,
  1422. TCaptureOutputEvent OutputEvent)
  1423. {
  1424. DebugAssert(File);
  1425. bool Dir = File->IsDirectory && FTerminal->CanRecurseToDirectory(File);
  1426. if (Dir && (Params & ccRecursive))
  1427. {
  1428. TCustomCommandParams AParams;
  1429. AParams.Command = Command;
  1430. AParams.Params = Params;
  1431. AParams.OutputEvent = OutputEvent;
  1432. FTerminal->ProcessDirectory(FileName, FTerminal->CustomCommandOnFile,
  1433. &AParams);
  1434. }
  1435. if (!Dir || (Params & ccApplyToDirectories))
  1436. {
  1437. TCustomCommandData Data(FTerminal);
  1438. UnicodeString Cmd = TRemoteCustomCommand(
  1439. Data, FTerminal->CurrentDirectory, FileName, L"").
  1440. Complete(Command, true);
  1441. if (!FTerminal->DoOnCustomCommand(Cmd))
  1442. {
  1443. AnyCommand(Cmd, OutputEvent);
  1444. }
  1445. }
  1446. }
  1447. //---------------------------------------------------------------------------
  1448. void __fastcall TSCPFileSystem::CaptureOutput(const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  1449. {
  1450. int ReturnCode;
  1451. UnicodeString Line = AddedLine;
  1452. // TSecureShell never uses cotExitCode
  1453. DebugAssert((OutputType == cotOutput) || (OutputType == cotError));
  1454. if ((OutputType == cotError) || DebugAlwaysFalse(OutputType == cotExitCode) ||
  1455. !RemoveLastLine(Line, ReturnCode) ||
  1456. !Line.IsEmpty())
  1457. {
  1458. DebugAssert(FOnCaptureOutput != NULL);
  1459. FOnCaptureOutput(Line, OutputType);
  1460. }
  1461. }
  1462. //---------------------------------------------------------------------------
  1463. void __fastcall TSCPFileSystem::AnyCommand(const UnicodeString Command,
  1464. TCaptureOutputEvent OutputEvent)
  1465. {
  1466. DebugAssert(FSecureShell->OnCaptureOutput == NULL);
  1467. if (OutputEvent != NULL)
  1468. {
  1469. FSecureShell->OnCaptureOutput = CaptureOutput;
  1470. FOnCaptureOutput = OutputEvent;
  1471. }
  1472. try
  1473. {
  1474. int Params =
  1475. ecDefault |
  1476. (FTerminal->SessionData->ExitCode1IsError ? ecIgnoreStdErr : ecIgnoreWarnings);
  1477. ExecCommand(fsAnyCommand, ARRAYOFCONST((Command)), Params);
  1478. }
  1479. __finally
  1480. {
  1481. FOnCaptureOutput = NULL;
  1482. FSecureShell->OnCaptureOutput = NULL;
  1483. }
  1484. }
  1485. //---------------------------------------------------------------------------
  1486. TStrings * __fastcall TSCPFileSystem::GetFixedPaths()
  1487. {
  1488. return NULL;
  1489. }
  1490. //---------------------------------------------------------------------------
  1491. void __fastcall TSCPFileSystem::SpaceAvailable(const UnicodeString Path,
  1492. TSpaceAvailable & /*ASpaceAvailable*/)
  1493. {
  1494. DebugFail();
  1495. }
  1496. //---------------------------------------------------------------------------
  1497. // transfer protocol
  1498. //---------------------------------------------------------------------------
  1499. unsigned int __fastcall TSCPFileSystem::ConfirmOverwrite(
  1500. const UnicodeString & SourceFullFileName, const UnicodeString & TargetFileName, TOperationSide Side,
  1501. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1502. int Params, TFileOperationProgressType * OperationProgress)
  1503. {
  1504. TSuspendFileOperationProgress Suspend(OperationProgress);
  1505. TQueryButtonAlias Aliases[3];
  1506. Aliases[0] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
  1507. Aliases[1] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
  1508. Aliases[2] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
  1509. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1510. QueryParams.Aliases = Aliases;
  1511. QueryParams.AliasesCount = LENOF(Aliases);
  1512. unsigned int Answer =
  1513. FTerminal->ConfirmFileOverwrite(
  1514. SourceFullFileName, TargetFileName, FileParams,
  1515. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll,
  1516. &QueryParams, Side, CopyParam, Params, OperationProgress);
  1517. return Answer;
  1518. }
  1519. //---------------------------------------------------------------------------
  1520. void __fastcall TSCPFileSystem::SCPResponse(bool * GotLastLine)
  1521. {
  1522. // Taken from scp.c response() and modified
  1523. unsigned char Resp;
  1524. FSecureShell->Receive(&Resp, 1);
  1525. switch (Resp)
  1526. {
  1527. case 0: /* ok */
  1528. FTerminal->LogEvent(L"SCP remote side confirmation (0)");
  1529. return;
  1530. default:
  1531. case 1: /* error */
  1532. case 2: /* fatal error */
  1533. // pscp adds 'Resp' to 'Msg', why?
  1534. UnicodeString Msg = FSecureShell->ReceiveLine();
  1535. UnicodeString Line = UnicodeString(static_cast<char>(Resp)) + Msg;
  1536. if (IsLastLine(Line))
  1537. {
  1538. if (GotLastLine != NULL)
  1539. {
  1540. *GotLastLine = true;
  1541. }
  1542. /* TODO 1 : Show stderror to user? */
  1543. FSecureShell->ClearStdError();
  1544. try
  1545. {
  1546. ReadCommandOutput(coExpectNoOutput | coRaiseExcept | coOnlyReturnCode);
  1547. }
  1548. catch(...)
  1549. {
  1550. // when ReadCommandOutput() fails than remote SCP is terminated already
  1551. if (GotLastLine != NULL)
  1552. {
  1553. *GotLastLine = true;
  1554. }
  1555. throw;
  1556. }
  1557. }
  1558. else if (Resp == 1)
  1559. {
  1560. // While the OpenSSH scp client distinguishes the 1 for error and 2 for fatal errors,
  1561. // the OpenSSH scp server always sends 1 even for fatal errors. Using the error message to tell
  1562. // which errors are fatal and which are not.
  1563. // This error list is valid for OpenSSH 5.3p1 and 7.2p2
  1564. if (SameText(Msg, L"scp: ambiguous target") ||
  1565. StartsText(L"scp: error: unexpected filename: ", Msg) ||
  1566. StartsText(L"scp: protocol error: ", Msg))
  1567. {
  1568. FTerminal->LogEvent(L"SCP remote side error (1), fatal error detected from error message");
  1569. Resp = 2;
  1570. FScpFatalError = true;
  1571. }
  1572. else
  1573. {
  1574. FTerminal->LogEvent(L"SCP remote side error (1)");
  1575. }
  1576. }
  1577. else
  1578. {
  1579. FTerminal->LogEvent(L"SCP remote side fatal error (2)");
  1580. FScpFatalError = true;
  1581. }
  1582. if (Resp == 1)
  1583. {
  1584. throw EScpFileSkipped(NULL, Msg);
  1585. }
  1586. else
  1587. {
  1588. throw EScp(NULL, Msg);
  1589. }
  1590. }
  1591. }
  1592. //---------------------------------------------------------------------------
  1593. void __fastcall TSCPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1594. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1595. int Params, TFileOperationProgressType * OperationProgress,
  1596. TOnceDoneOperation & OnceDoneOperation)
  1597. {
  1598. // scp.c: source(), toremote()
  1599. DebugAssert(FilesToCopy && OperationProgress);
  1600. Params &= ~(cpAppend | cpResume);
  1601. UnicodeString Options = L"";
  1602. bool CheckExistence = UnixSamePath(TargetDir, FTerminal->CurrentDirectory) &&
  1603. (FTerminal->FFiles != NULL) && FTerminal->FFiles->Loaded;
  1604. bool CopyBatchStarted = false;
  1605. bool Failed = true;
  1606. bool GotLastLine = false;
  1607. UnicodeString TargetDirFull = UnixIncludeTrailingBackslash(TargetDir);
  1608. if (CopyParam->PreserveRights) Options = L"-p";
  1609. if (FTerminal->SessionData->Scp1Compatibility) Options += L" -1";
  1610. FScpFatalError = false;
  1611. SendCommand(FCommandSet->FullCommand(fsCopyToRemote,
  1612. ARRAYOFCONST((Options, DelimitStr(UnixExcludeTrailingBackslash(TargetDir))))));
  1613. SkipFirstLine();
  1614. try
  1615. {
  1616. try
  1617. {
  1618. SCPResponse(&GotLastLine);
  1619. // This can happen only if SCP command is not executed and return code is 0
  1620. // It has never happened to me (return code is usually 127)
  1621. if (GotLastLine)
  1622. {
  1623. throw Exception(L"");
  1624. }
  1625. }
  1626. catch(Exception & E)
  1627. {
  1628. if (GotLastLine && FTerminal->Active)
  1629. {
  1630. FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
  1631. }
  1632. else
  1633. {
  1634. throw;
  1635. }
  1636. }
  1637. CopyBatchStarted = true;
  1638. for (int IFile = 0; (IFile < FilesToCopy->Count) &&
  1639. !OperationProgress->Cancel; IFile++)
  1640. {
  1641. UnicodeString FileName = FilesToCopy->Strings[IFile];
  1642. bool CanProceed;
  1643. UnicodeString FileNameOnly =
  1644. FTerminal->ChangeFileName(
  1645. CopyParam, ExtractFileName(FileName), osLocal, true);
  1646. if (CheckExistence)
  1647. {
  1648. // previously there was assertion on FTerminal->FFiles->Loaded, but it
  1649. // fails for scripting, if 'ls' is not issued before.
  1650. // formally we should call CheckRemoteFile here but as checking is for
  1651. // free here (almost) ...
  1652. TRemoteFile * File = FTerminal->FFiles->FindFile(FileNameOnly);
  1653. if (File != NULL)
  1654. {
  1655. unsigned int Answer;
  1656. if (File->IsDirectory)
  1657. {
  1658. UnicodeString Message = FMTLOAD(DIRECTORY_OVERWRITE, (FileNameOnly));
  1659. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1660. TSuspendFileOperationProgress Suspend(OperationProgress);
  1661. Answer = FTerminal->ConfirmFileOverwrite(
  1662. FileName, FileNameOnly, NULL,
  1663. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll,
  1664. &QueryParams, osRemote, CopyParam, Params, OperationProgress, Message);
  1665. }
  1666. else
  1667. {
  1668. __int64 MTime;
  1669. TOverwriteFileParams FileParams;
  1670. FTerminal->OpenLocalFile(FileName, GENERIC_READ,
  1671. NULL, NULL, NULL, &MTime, NULL,
  1672. &FileParams.SourceSize);
  1673. FileParams.SourceTimestamp = UnixToDateTime(MTime,
  1674. FTerminal->SessionData->DSTMode);
  1675. FileParams.DestSize = File->Size;
  1676. FileParams.DestTimestamp = File->Modification;
  1677. Answer = ConfirmOverwrite(FileName, FileNameOnly, osRemote,
  1678. &FileParams, CopyParam, Params, OperationProgress);
  1679. }
  1680. switch (Answer)
  1681. {
  1682. case qaYes:
  1683. CanProceed = true;
  1684. break;
  1685. case qaCancel:
  1686. OperationProgress->SetCancelAtLeast(csCancel);
  1687. case qaNo:
  1688. CanProceed = false;
  1689. break;
  1690. default:
  1691. DebugFail();
  1692. break;
  1693. }
  1694. }
  1695. else
  1696. {
  1697. CanProceed = true;
  1698. }
  1699. }
  1700. else
  1701. {
  1702. CanProceed = true;
  1703. }
  1704. if (CanProceed)
  1705. {
  1706. if (FTerminal->SessionData->CacheDirectories)
  1707. {
  1708. FTerminal->DirectoryModified(TargetDir, false);
  1709. if (DirectoryExists(ApiPath(FileName)))
  1710. {
  1711. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  1712. FileNameOnly, true);
  1713. }
  1714. }
  1715. void * Item = static_cast<void *>(FilesToCopy->Objects[IFile]);
  1716. try
  1717. {
  1718. SCPSource(FileName, TargetDirFull,
  1719. CopyParam, Params, OperationProgress, 0);
  1720. FTerminal->OperationFinish(OperationProgress, Item, FileName, true, OnceDoneOperation);
  1721. }
  1722. catch (EScpFileSkipped &E)
  1723. {
  1724. TQueryParams Params(qpAllowContinueOnError);
  1725. TSuspendFileOperationProgress Suspend(OperationProgress);
  1726. if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FileName)), &E,
  1727. qaOK | qaAbort, &Params, qtError) == qaAbort)
  1728. {
  1729. OperationProgress->SetCancel(csCancel);
  1730. }
  1731. FTerminal->OperationFinish(OperationProgress, Item, FileName, false, OnceDoneOperation);
  1732. if (!FTerminal->HandleException(&E))
  1733. {
  1734. throw;
  1735. }
  1736. }
  1737. catch (ESkipFile &E)
  1738. {
  1739. FTerminal->OperationFinish(OperationProgress, Item, FileName, false, OnceDoneOperation);
  1740. {
  1741. TSuspendFileOperationProgress Suspend(OperationProgress);
  1742. // If ESkipFile occurs, just log it and continue with next file
  1743. if (!FTerminal->HandleException(&E))
  1744. {
  1745. throw;
  1746. }
  1747. }
  1748. }
  1749. catch (...)
  1750. {
  1751. FTerminal->OperationFinish(OperationProgress, Item, FileName, false, OnceDoneOperation);
  1752. throw;
  1753. }
  1754. }
  1755. }
  1756. Failed = false;
  1757. }
  1758. __finally
  1759. {
  1760. // Tell remote side, that we're done.
  1761. if (FTerminal->Active)
  1762. {
  1763. try
  1764. {
  1765. if (!GotLastLine)
  1766. {
  1767. if (CopyBatchStarted && !FScpFatalError)
  1768. {
  1769. // What about case, remote side sends fatal error ???
  1770. // (Not sure, if it causes remote side to terminate scp)
  1771. FSecureShell->SendLine(L"E");
  1772. SCPResponse();
  1773. }
  1774. /* TODO 1 : Show stderror to user? */
  1775. FSecureShell->ClearStdError();
  1776. ReadCommandOutput(coExpectNoOutput | coWaitForLastLine | coOnlyReturnCode |
  1777. (Failed ? 0 : coRaiseExcept));
  1778. }
  1779. }
  1780. catch (Exception &E)
  1781. {
  1782. // Only log error message (it should always succeed, but
  1783. // some pending error maybe in queue) }
  1784. FTerminal->Log->AddException(&E);
  1785. }
  1786. }
  1787. }
  1788. }
  1789. //---------------------------------------------------------------------------
  1790. void __fastcall TSCPFileSystem::Source(
  1791. TLocalFileHandle & /*Handle*/, const UnicodeString & /*TargetDir*/, UnicodeString & /*DestFileName*/,
  1792. const TCopyParamType * /*CopyParam*/, int /*Params*/,
  1793. TFileOperationProgressType * /*OperationProgress*/, unsigned int /*Flags*/,
  1794. TUploadSessionAction & /*Action*/, bool & /*ChildError*/)
  1795. {
  1796. DebugFail();
  1797. }
  1798. //---------------------------------------------------------------------------
  1799. void __fastcall TSCPFileSystem::SCPSource(const UnicodeString FileName,
  1800. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  1801. TFileOperationProgressType * OperationProgress, int Level)
  1802. {
  1803. UnicodeString DestFileName =
  1804. FTerminal->ChangeFileName(
  1805. CopyParam, ExtractFileName(FileName), osLocal, Level == 0);
  1806. FTerminal->LogEvent(FORMAT(L"File: \"%s\"", (FileName)));
  1807. OperationProgress->SetFile(FileName, false);
  1808. if (!FTerminal->AllowLocalFileTransfer(FileName, NULL, CopyParam, OperationProgress))
  1809. {
  1810. throw ESkipFile();
  1811. }
  1812. TLocalFileHandle Handle;
  1813. FTerminal->OpenLocalFile(FileName, GENERIC_READ, Handle);
  1814. OperationProgress->SetFileInProgress();
  1815. if (Handle.Directory)
  1816. {
  1817. SCPDirectorySource(FileName, TargetDir, CopyParam, Params, OperationProgress, Level);
  1818. }
  1819. else
  1820. {
  1821. UnicodeString AbsoluteFileName = FTerminal->AbsolutePath(TargetDir + DestFileName, false);
  1822. DebugAssert(Handle.Handle);
  1823. std::unique_ptr<TStream> Stream(new TSafeHandleStream((THandle)Handle.Handle));
  1824. // File is regular file (not directory)
  1825. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  1826. OperationProgress->SetLocalSize(Handle.Size);
  1827. // Suppose same data size to transfer as to read
  1828. // (not true with ASCII transfer)
  1829. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1830. OperationProgress->SetTransferringFile(false);
  1831. if (Handle.Size > 512*1024*1024)
  1832. {
  1833. OperationProgress->SetAsciiTransfer(false);
  1834. FTerminal->LogEvent(FORMAT(L"Binary transfer mode selected as the file is too large (%s) to be uploaded in Ascii mode using SCP protocol.", (IntToStr(Handle.Size))));
  1835. }
  1836. else
  1837. {
  1838. FTerminal->SelectSourceTransferMode(Handle, CopyParam);
  1839. }
  1840. TUploadSessionAction Action(FTerminal->ActionLog);
  1841. Action.FileName(ExpandUNCFileName(FileName));
  1842. Action.Destination(AbsoluteFileName);
  1843. TRights Rights = CopyParam->RemoteFileRights(Handle.Attrs);
  1844. try
  1845. {
  1846. // During ASCII transfer we will load whole file to this buffer
  1847. // than convert EOL and send it at once, because before converting EOL
  1848. // we can't know its size
  1849. TFileBuffer AsciiBuf;
  1850. bool ConvertToken = false;
  1851. do
  1852. {
  1853. // Buffer for one block of data
  1854. TFileBuffer BlockBuf;
  1855. // This is crucial, if it fails during file transfer, it's fatal error
  1856. FILE_OPERATION_LOOP_BEGIN
  1857. {
  1858. BlockBuf.LoadStream(Stream.get(), OperationProgress->LocalBlockSize(), true);
  1859. }
  1860. FILE_OPERATION_LOOP_END_EX(
  1861. FMTLOAD(READ_ERROR, (FileName)),
  1862. FLAGMASK(!OperationProgress->TransferringFile, folAllowSkip));
  1863. OperationProgress->AddLocallyUsed(BlockBuf.Size);
  1864. // We do ASCII transfer: convert EOL of current block
  1865. // (we don't convert whole buffer, cause it would produce
  1866. // huge memory-transfers while inserting/deleting EOL characters)
  1867. // Than we add current block to file buffer
  1868. if (OperationProgress->AsciiTransfer)
  1869. {
  1870. int ConvertParams =
  1871. FLAGMASK(CopyParam->RemoveCtrlZ, cpRemoveCtrlZ) |
  1872. FLAGMASK(CopyParam->RemoveBOM, cpRemoveBOM);
  1873. BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
  1874. FTerminal->SessionData->EOLType,
  1875. ConvertParams, ConvertToken);
  1876. BlockBuf.Memory->Seek(0, soFromBeginning);
  1877. AsciiBuf.ReadStream(BlockBuf.Memory, BlockBuf.Size, true);
  1878. // We don't need it any more
  1879. BlockBuf.Memory->Clear();
  1880. // Calculate total size to sent (assume that ratio between
  1881. // size of source and size of EOL-transformed data would remain same)
  1882. // First check if file contains anything (div by zero!)
  1883. if (OperationProgress->LocallyUsed)
  1884. {
  1885. __int64 X = OperationProgress->LocalSize;
  1886. X *= AsciiBuf.Size;
  1887. X /= OperationProgress->LocallyUsed;
  1888. OperationProgress->ChangeTransferSize(X);
  1889. }
  1890. else
  1891. {
  1892. OperationProgress->ChangeTransferSize(0);
  1893. }
  1894. }
  1895. // We send file information on first pass during BINARY transfer
  1896. // and on last pass during ASCII transfer
  1897. // BINARY: We succeeded reading first buffer from file, hopefully
  1898. // we will be able to read whole, so we send file info to remote side
  1899. // This is done, because when reading fails we can't interrupt sending
  1900. // (don't know how to tell other side that it failed)
  1901. if (!OperationProgress->TransferringFile &&
  1902. (!OperationProgress->AsciiTransfer || OperationProgress->IsLocallyDone()))
  1903. {
  1904. UnicodeString Buf;
  1905. if (CopyParam->PreserveTime)
  1906. {
  1907. // Send last file access and modification time
  1908. // TVarRec don't understand 'unsigned int' -> we use sprintf()
  1909. Buf.sprintf(L"T%lu 0 %lu 0", static_cast<unsigned long>(Handle.MTime),
  1910. static_cast<unsigned long>(Handle.ATime));
  1911. FSecureShell->SendLine(Buf);
  1912. SCPResponse();
  1913. }
  1914. // Send file modes (rights), filesize and file name
  1915. // TVarRec don't understand 'unsigned int' -> we use sprintf()
  1916. Buf.sprintf(L"C%s %Ld %s",
  1917. Rights.Octal.data(),
  1918. (OperationProgress->AsciiTransfer ? (__int64)AsciiBuf.Size :
  1919. OperationProgress->LocalSize),
  1920. DestFileName.data());
  1921. FSecureShell->SendLine(Buf);
  1922. SCPResponse();
  1923. // Indicate we started transferring file, we need to finish it
  1924. // If not, it's fatal error
  1925. OperationProgress->SetTransferringFile(true);
  1926. // If we're doing ASCII transfer, this is last pass
  1927. // so we send whole file
  1928. /* TODO : We can't send file above 32bit size in ASCII mode! */
  1929. if (OperationProgress->AsciiTransfer)
  1930. {
  1931. FTerminal->LogEvent(FORMAT(L"Sending ASCII data (%u bytes)",
  1932. (AsciiBuf.Size)));
  1933. // Should be equal, just in case it's rounded (see above)
  1934. OperationProgress->ChangeTransferSize(AsciiBuf.Size);
  1935. while (!OperationProgress->IsTransferDoneChecked())
  1936. {
  1937. unsigned long BlockSize = OperationProgress->TransferBlockSize();
  1938. FSecureShell->Send(
  1939. reinterpret_cast<unsigned char *>(AsciiBuf.Data + (unsigned int)OperationProgress->TransferredSize),
  1940. BlockSize);
  1941. OperationProgress->AddTransferred(BlockSize);
  1942. if (OperationProgress->Cancel == csCancelTransfer)
  1943. {
  1944. throw Exception(MainInstructions(LoadStr(USER_TERMINATED)));
  1945. }
  1946. }
  1947. }
  1948. }
  1949. // At end of BINARY transfer pass, send current block
  1950. if (!OperationProgress->AsciiTransfer)
  1951. {
  1952. if (!OperationProgress->TransferredSize)
  1953. {
  1954. FTerminal->LogEvent(FORMAT(L"Sending BINARY data (first block, %u bytes)",
  1955. (BlockBuf.Size)));
  1956. }
  1957. else if (FTerminal->Configuration->ActualLogProtocol >= 1)
  1958. {
  1959. FTerminal->LogEvent(FORMAT(L"Sending BINARY data (%u bytes)",
  1960. (BlockBuf.Size)));
  1961. }
  1962. FSecureShell->Send(reinterpret_cast<const unsigned char *>(BlockBuf.Data), BlockBuf.Size);
  1963. OperationProgress->AddTransferred(BlockBuf.Size);
  1964. }
  1965. if ((OperationProgress->Cancel == csCancelTransfer) ||
  1966. (OperationProgress->Cancel == csCancel && !OperationProgress->TransferringFile))
  1967. {
  1968. throw Exception(MainInstructions(LoadStr(USER_TERMINATED)));
  1969. }
  1970. }
  1971. while (!OperationProgress->IsLocallyDone() || !OperationProgress->IsTransferDoneChecked());
  1972. FSecureShell->SendNull();
  1973. try
  1974. {
  1975. SCPResponse();
  1976. // If one of two following exceptions occurs, it means, that remote
  1977. // side already know, that file transfer finished, even if it failed
  1978. // so we don't have to throw EFatal
  1979. }
  1980. catch (EScp &E)
  1981. {
  1982. // SCP protocol fatal error
  1983. OperationProgress->SetTransferringFile(false);
  1984. throw;
  1985. }
  1986. catch (EScpFileSkipped &E)
  1987. {
  1988. // SCP protocol non-fatal error
  1989. OperationProgress->SetTransferringFile(false);
  1990. throw;
  1991. }
  1992. // We succeeded transferring file, from now we can handle exceptions
  1993. // normally -> no fatal error
  1994. OperationProgress->SetTransferringFile(false);
  1995. }
  1996. catch (Exception &E)
  1997. {
  1998. // EScpFileSkipped is derived from ESkipFile,
  1999. // but is does not indicate file skipped by user here
  2000. if (dynamic_cast<EScpFileSkipped *>(&E) != NULL)
  2001. {
  2002. Action.Rollback(&E);
  2003. }
  2004. else
  2005. {
  2006. FTerminal->RollbackAction(Action, OperationProgress, &E);
  2007. }
  2008. // Every exception during file transfer is fatal
  2009. if (OperationProgress->TransferringFile)
  2010. {
  2011. FTerminal->FatalError(&E, FMTLOAD(COPY_FATAL, (FileName)));
  2012. }
  2013. else
  2014. {
  2015. throw;
  2016. }
  2017. }
  2018. // With SCP we are not able to distinguish reason for failure
  2019. // (upload itself, touch or chmod).
  2020. // So we always report error with upload action and
  2021. // log touch and chmod actions only if upload succeeds.
  2022. if (CopyParam->PreserveTime)
  2023. {
  2024. TTouchSessionAction(FTerminal->ActionLog, AbsoluteFileName, Handle.Modification);
  2025. }
  2026. if (CopyParam->PreserveRights)
  2027. {
  2028. TChmodSessionAction(FTerminal->ActionLog, AbsoluteFileName,
  2029. Rights);
  2030. }
  2031. FTerminal->LogFileDone(OperationProgress, AbsoluteFileName, Action);
  2032. // Stream is disposed here
  2033. }
  2034. Handle.Release();
  2035. FTerminal->UpdateSource(Handle, CopyParam, Params);
  2036. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory finished.", (FileName)));
  2037. }
  2038. //---------------------------------------------------------------------------
  2039. void __fastcall TSCPFileSystem::SCPDirectorySource(const UnicodeString DirectoryName,
  2040. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  2041. TFileOperationProgressType * OperationProgress, int Level)
  2042. {
  2043. int Attrs;
  2044. FTerminal->LogEvent(FORMAT(L"Entering directory \"%s\".", (DirectoryName)));
  2045. OperationProgress->SetFile(DirectoryName);
  2046. UnicodeString DestFileName =
  2047. FTerminal->ChangeFileName(
  2048. CopyParam, ExtractFileName(DirectoryName), osLocal, Level == 0);
  2049. // Get directory attributes
  2050. FILE_OPERATION_LOOP_BEGIN
  2051. {
  2052. Attrs = FileGetAttrFix(ApiPath(DirectoryName));
  2053. if (Attrs < 0) RaiseLastOSError();
  2054. }
  2055. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (DirectoryName)));
  2056. UnicodeString TargetDirFull = UnixIncludeTrailingBackslash(TargetDir + DestFileName);
  2057. UnicodeString Buf;
  2058. /* TODO 1: maybe send filetime */
  2059. // Send directory modes (rights), filesize and file name
  2060. Buf = FORMAT(L"D%s 0 %s",
  2061. (CopyParam->RemoteFileRights(Attrs).Octal, DestFileName));
  2062. FSecureShell->SendLine(Buf);
  2063. SCPResponse();
  2064. try
  2065. {
  2066. TSearchRecOwned SearchRec;
  2067. bool FindOK = FTerminal->LocalFindFirstLoop(IncludeTrailingBackslash(DirectoryName) + L"*.*", SearchRec);
  2068. while (FindOK && !OperationProgress->Cancel)
  2069. {
  2070. UnicodeString FileName = SearchRec.GetFilePath();
  2071. try
  2072. {
  2073. if (SearchRec.IsRealFile())
  2074. {
  2075. SCPSource(FileName, TargetDirFull, CopyParam, Params, OperationProgress, Level + 1);
  2076. }
  2077. }
  2078. // Previously we caught ESkipFile, making error being displayed
  2079. // even when file was excluded by mask. Now the ESkipFile is special
  2080. // case without error message.
  2081. catch (EScpFileSkipped &E)
  2082. {
  2083. TQueryParams Params(qpAllowContinueOnError);
  2084. TSuspendFileOperationProgress Suspend(OperationProgress);
  2085. if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FileName)), &E,
  2086. qaOK | qaAbort, &Params, qtError) == qaAbort)
  2087. {
  2088. OperationProgress->SetCancel(csCancel);
  2089. }
  2090. if (!FTerminal->HandleException(&E))
  2091. {
  2092. throw;
  2093. }
  2094. }
  2095. catch (ESkipFile &E)
  2096. {
  2097. // If ESkipFile occurs, just log it and continue with next file
  2098. TSuspendFileOperationProgress Suspend(OperationProgress);
  2099. if (!FTerminal->HandleException(&E))
  2100. {
  2101. throw;
  2102. }
  2103. }
  2104. FindOK = FTerminal->LocalFindNextLoop(SearchRec);
  2105. }
  2106. SearchRec.Close();
  2107. /* TODO : Delete also read-only directories. */
  2108. /* TODO : Show error message on failure. */
  2109. if (!OperationProgress->Cancel)
  2110. {
  2111. if (FLAGSET(Params, cpDelete))
  2112. {
  2113. RemoveDir(ApiPath(DirectoryName));
  2114. }
  2115. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  2116. {
  2117. FILE_OPERATION_LOOP_BEGIN
  2118. {
  2119. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  2120. }
  2121. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  2122. }
  2123. }
  2124. }
  2125. __finally
  2126. {
  2127. if (FTerminal->Active)
  2128. {
  2129. // Tell remote side, that we're done.
  2130. FTerminal->LogEvent(FORMAT(L"Leaving directory \"%s\".", (DirectoryName)));
  2131. FSecureShell->SendLine(L"E");
  2132. SCPResponse();
  2133. }
  2134. }
  2135. }
  2136. //---------------------------------------------------------------------------
  2137. void __fastcall TSCPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  2138. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  2139. int Params, TFileOperationProgressType * OperationProgress,
  2140. TOnceDoneOperation & OnceDoneOperation)
  2141. {
  2142. bool CloseSCP = False;
  2143. Params &= ~(cpAppend | cpResume);
  2144. UnicodeString Options = L"";
  2145. if (CopyParam->PreserveRights || CopyParam->PreserveTime) Options = L"-p";
  2146. if (FTerminal->SessionData->Scp1Compatibility) Options += L" -1";
  2147. FTerminal->LogEvent(FORMAT(L"Copying %d files/directories to local directory "
  2148. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  2149. FTerminal->LogEvent(0, CopyParam->LogStr);
  2150. try
  2151. {
  2152. for (int IFile = 0; (IFile < FilesToCopy->Count) &&
  2153. !OperationProgress->Cancel; IFile++)
  2154. {
  2155. UnicodeString FileName = FilesToCopy->Strings[IFile];
  2156. TRemoteFile * File = (TRemoteFile *)FilesToCopy->Objects[IFile];
  2157. DebugAssert(File);
  2158. try
  2159. {
  2160. bool Success = true; // Have to be set to True (see ::SCPSink)
  2161. SendCommand(FCommandSet->FullCommand(fsCopyToLocal,
  2162. ARRAYOFCONST((Options, DelimitStr(FileName)))));
  2163. SkipFirstLine();
  2164. // Filename is used for error messaging and excluding files only
  2165. // Send in full path to allow path-based excluding
  2166. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  2167. SCPSink(TargetDir, FullFileName, UnixExtractFilePath(FullFileName),
  2168. CopyParam, Success, OperationProgress, Params, 0);
  2169. // operation succeeded (no exception), so it's ok that
  2170. // remote side closed SCP, but we continue with next file
  2171. if (OperationProgress->Cancel == csRemoteAbort)
  2172. {
  2173. OperationProgress->SetCancel(csContinue);
  2174. }
  2175. // Move operation -> delete file/directory afterwards
  2176. // but only if copying succeeded
  2177. if ((Params & cpDelete) && Success && !OperationProgress->Cancel)
  2178. {
  2179. try
  2180. {
  2181. FTerminal->ExceptionOnFail = true;
  2182. try
  2183. {
  2184. FILE_OPERATION_LOOP_BEGIN
  2185. {
  2186. // pass full file name in FileName, in case we are not moving
  2187. // from current directory
  2188. FTerminal->DeleteFile(FileName, File);
  2189. }
  2190. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  2191. }
  2192. __finally
  2193. {
  2194. FTerminal->ExceptionOnFail = false;
  2195. }
  2196. }
  2197. catch (EFatal &E)
  2198. {
  2199. throw;
  2200. }
  2201. catch (...)
  2202. {
  2203. // If user selects skip (or abort), nothing special actually occurs
  2204. // we just run DoFinished with Success = False, so file won't
  2205. // be deselected in panel (depends on assigned event handler)
  2206. // On csCancel we would later try to close remote SCP, but it
  2207. // is closed already
  2208. if (OperationProgress->Cancel == csCancel)
  2209. {
  2210. OperationProgress->SetCancel(csRemoteAbort);
  2211. }
  2212. Success = false;
  2213. }
  2214. }
  2215. FTerminal->OperationFinish(
  2216. OperationProgress, File, FileName, (!OperationProgress->Cancel && Success), OnceDoneOperation);
  2217. }
  2218. catch (...)
  2219. {
  2220. FTerminal->OperationFinish(OperationProgress, File, FileName, false, OnceDoneOperation);
  2221. CloseSCP = (OperationProgress->Cancel != csRemoteAbort);
  2222. throw;
  2223. }
  2224. }
  2225. }
  2226. __finally
  2227. {
  2228. // In case that copying doesn't cause fatal error (ie. connection is
  2229. // still active) but wasn't successful (exception or user termination)
  2230. // we need to ensure, that SCP on remote side is closed
  2231. if (FTerminal->Active && (CloseSCP ||
  2232. (OperationProgress->Cancel == csCancel) ||
  2233. (OperationProgress->Cancel == csCancelTransfer)))
  2234. {
  2235. bool LastLineRead;
  2236. // If we get LastLine, it means that remote side 'scp' is already
  2237. // terminated, so we need not to terminate it. There is also
  2238. // possibility that remote side waits for confirmation, so it will hang.
  2239. // This should not happen (hope)
  2240. UnicodeString Line = FSecureShell->ReceiveLine();
  2241. LastLineRead = IsLastLine(Line);
  2242. if (!LastLineRead)
  2243. {
  2244. SCPSendError((OperationProgress->Cancel ? L"Terminated by user." : L"Exception"), true);
  2245. }
  2246. // Just in case, remote side already sent some more data (it's probable)
  2247. // but we don't want to raise exception (user asked to terminate, it's not error)
  2248. int ECParams = coOnlyReturnCode;
  2249. if (!LastLineRead) ECParams |= coWaitForLastLine;
  2250. ReadCommandOutput(ECParams);
  2251. }
  2252. }
  2253. }
  2254. //---------------------------------------------------------------------------
  2255. void __fastcall TSCPFileSystem::Sink(
  2256. const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/,
  2257. const UnicodeString & /*TargetDir*/, UnicodeString & /*DestFileName*/, int /*Attrs*/,
  2258. const TCopyParamType * /*CopyParam*/, int /*Params*/, TFileOperationProgressType * /*OperationProgress*/,
  2259. unsigned int /*Flags*/, TDownloadSessionAction & /*Action*/)
  2260. {
  2261. DebugFail();
  2262. }
  2263. //---------------------------------------------------------------------------
  2264. void __fastcall TSCPFileSystem::SCPError(const UnicodeString Message, bool Fatal)
  2265. {
  2266. SCPSendError(Message, Fatal);
  2267. throw EScpFileSkipped(NULL, Message);
  2268. }
  2269. //---------------------------------------------------------------------------
  2270. void __fastcall TSCPFileSystem::SCPSendError(const UnicodeString Message, bool Fatal)
  2271. {
  2272. unsigned char ErrorLevel = (char)(Fatal ? 2 : 1);
  2273. FTerminal->LogEvent(FORMAT(L"Sending SCP error (%d) to remote side:",
  2274. ((int)ErrorLevel)));
  2275. FSecureShell->Send(&ErrorLevel, 1);
  2276. // We don't send exact error message, because some unspecified
  2277. // characters can terminate remote scp
  2278. FSecureShell->SendLine(L"scp: error");
  2279. }
  2280. //---------------------------------------------------------------------------
  2281. void __fastcall TSCPFileSystem::SCPSink(const UnicodeString TargetDir,
  2282. const UnicodeString FileName, const UnicodeString SourceDir,
  2283. const TCopyParamType * CopyParam, bool & Success,
  2284. TFileOperationProgressType * OperationProgress, int Params,
  2285. int Level)
  2286. {
  2287. struct
  2288. {
  2289. int SetTime;
  2290. TDateTime Modification;
  2291. TRights RemoteRights;
  2292. int Attrs;
  2293. bool Exists;
  2294. } FileData;
  2295. bool SkipConfirmed = false;
  2296. bool Initialized = (Level > 0);
  2297. FileData.SetTime = 0;
  2298. FSecureShell->SendNull();
  2299. while (!OperationProgress->Cancel)
  2300. {
  2301. // See (switch ... case 'T':)
  2302. if (FileData.SetTime) FileData.SetTime--;
  2303. // In case of error occurred before control record arrived.
  2304. // We can finally use full path here, as we get current path in FileName param
  2305. // (we used to set the file into OperationProgress->FileName, but it collided
  2306. // with progress outputting, particularly for scripting)
  2307. UnicodeString FullFileName = FileName;
  2308. try
  2309. {
  2310. // Receive control record
  2311. UnicodeString Line = FSecureShell->ReceiveLine();
  2312. if (Line.Length() == 0) FTerminal->FatalError(NULL, LoadStr(SCP_EMPTY_LINE));
  2313. if (IsLastLine(Line))
  2314. {
  2315. // Remote side finished copying, so remote SCP was closed
  2316. // and we don't need to terminate it manually, see CopyToLocal()
  2317. OperationProgress->SetCancel(csRemoteAbort);
  2318. /* TODO 1 : Show stderror to user? */
  2319. FSecureShell->ClearStdError();
  2320. try
  2321. {
  2322. // coIgnoreWarnings should allow batch transfer to continue when
  2323. // download of one the files fails (user denies overwriting
  2324. // of target local file, no read permissions...)
  2325. ReadCommandOutput(coExpectNoOutput | coRaiseExcept |
  2326. coOnlyReturnCode | coIgnoreWarnings);
  2327. if (!Initialized)
  2328. {
  2329. throw Exception(L"");
  2330. }
  2331. }
  2332. catch(Exception & E)
  2333. {
  2334. if (!Initialized && FTerminal->Active)
  2335. {
  2336. FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
  2337. }
  2338. else
  2339. {
  2340. throw;
  2341. }
  2342. }
  2343. return;
  2344. }
  2345. else
  2346. {
  2347. Initialized = true;
  2348. // First character distinguish type of control record
  2349. wchar_t Ctrl = Line[1];
  2350. Line.Delete(1, 1);
  2351. switch (Ctrl) {
  2352. case 1:
  2353. // Error (already logged by ReceiveLine())
  2354. throw EScpFileSkipped(NULL, FMTLOAD(REMOTE_ERROR, (Line)));
  2355. case 2:
  2356. // Fatal error, terminate copying
  2357. FTerminal->TerminalError(Line);
  2358. return; // Unreachable
  2359. case L'E': // Exit
  2360. FSecureShell->SendNull();
  2361. return;
  2362. case L'T':
  2363. unsigned long MTime, ATime;
  2364. if (swscanf(Line.c_str(), L"%ld %*d %ld %*d", &MTime, &ATime) == 2)
  2365. {
  2366. FileData.Modification = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  2367. FSecureShell->SendNull();
  2368. // File time is only valid until next pass
  2369. FileData.SetTime = 2;
  2370. continue;
  2371. }
  2372. else
  2373. {
  2374. SCPError(LoadStr(SCP_ILLEGAL_TIME_FORMAT), False);
  2375. }
  2376. case L'C':
  2377. case L'D':
  2378. break; // continue pass switch{}
  2379. default:
  2380. FTerminal->FatalError(NULL, FMTLOAD(SCP_INVALID_CONTROL_RECORD, (Ctrl, Line)));
  2381. }
  2382. TFileMasks::TParams MaskParams;
  2383. MaskParams.Modification = FileData.Modification;
  2384. // We reach this point only if control record was 'C' or 'D'
  2385. try
  2386. {
  2387. FileData.RemoteRights.Octal = CutToChar(Line, L' ', True);
  2388. // do not trim leading spaces of the filename
  2389. __int64 TSize = StrToInt64(CutToChar(Line, L' ', False).TrimRight());
  2390. MaskParams.Size = TSize;
  2391. // Security fix: ensure the file ends up where we asked for it.
  2392. // (accept only filename, not path)
  2393. UnicodeString OnlyFileName = UnixExtractFileName(Line);
  2394. if (Line != OnlyFileName)
  2395. {
  2396. FTerminal->LogEvent(FORMAT(L"Warning: Remote host set a compound pathname '%s'", (Line)));
  2397. }
  2398. if ((Level == 0) && (OnlyFileName != UnixExtractFileName(FileName)))
  2399. {
  2400. SCPError(LoadStr(UNREQUESTED_FILE), False);
  2401. }
  2402. FullFileName = SourceDir + OnlyFileName;
  2403. OperationProgress->SetFile(FullFileName);
  2404. OperationProgress->SetTransferSize(TSize);
  2405. }
  2406. catch (Exception &E)
  2407. {
  2408. {
  2409. TSuspendFileOperationProgress Suspend(OperationProgress);
  2410. FTerminal->Log->AddException(&E);
  2411. }
  2412. SCPError(LoadStr(SCP_ILLEGAL_FILE_DESCRIPTOR), false);
  2413. }
  2414. // last possibility to cancel transfer before it starts
  2415. if (OperationProgress->Cancel)
  2416. {
  2417. throw ESkipFile(NULL, MainInstructions(LoadStr(USER_TERMINATED)));
  2418. }
  2419. bool Dir = (Ctrl == L'D');
  2420. UnicodeString BaseFileName = FTerminal->GetBaseFileName(FullFileName);
  2421. if (!CopyParam->AllowTransfer(BaseFileName, osRemote, Dir, MaskParams, IsUnixHiddenFile(BaseFileName)))
  2422. {
  2423. FTerminal->LogEvent(FORMAT(L"File \"%s\" excluded from transfer",
  2424. (FullFileName)));
  2425. SkipConfirmed = true;
  2426. SCPError(L"", false);
  2427. }
  2428. if (CopyParam->SkipTransfer(FullFileName, Dir))
  2429. {
  2430. SkipConfirmed = true;
  2431. SCPError(L"", false);
  2432. OperationProgress->AddSkippedFileSize(MaskParams.Size);
  2433. }
  2434. FTerminal->LogFileDetails(FileName, FileData.Modification, MaskParams.Size);
  2435. UnicodeString DestFileNameOnly =
  2436. FTerminal->ChangeFileName(
  2437. CopyParam, OperationProgress->FileName, osRemote,
  2438. Level == 0);
  2439. UnicodeString DestFileName =
  2440. IncludeTrailingBackslash(TargetDir) + DestFileNameOnly;
  2441. FileData.Attrs = FileGetAttrFix(ApiPath(DestFileName));
  2442. // If getting attrs fails, we suppose, that file/folder doesn't exists
  2443. FileData.Exists = (FileData.Attrs != -1);
  2444. if (Dir)
  2445. {
  2446. if (FileData.Exists && !(FileData.Attrs & faDirectory))
  2447. {
  2448. SCPError(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFileName)), false);
  2449. }
  2450. if (!FileData.Exists)
  2451. {
  2452. FILE_OPERATION_LOOP_BEGIN
  2453. {
  2454. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFileName)));
  2455. }
  2456. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFileName)));
  2457. /* SCP: can we set the timestamp for directories ? */
  2458. }
  2459. UnicodeString FullFileName = SourceDir + OperationProgress->FileName;
  2460. SCPSink(DestFileName, FullFileName, UnixIncludeTrailingBackslash(FullFileName),
  2461. CopyParam, Success, OperationProgress, Params, Level + 1);
  2462. continue;
  2463. }
  2464. else if (Ctrl == L'C')
  2465. {
  2466. TDownloadSessionAction Action(FTerminal->ActionLog);
  2467. Action.FileName(FTerminal->AbsolutePath(FullFileName, true));
  2468. try
  2469. {
  2470. HANDLE File = NULL;
  2471. TStream * FileStream = NULL;
  2472. /* TODO 1 : Turn off read-only attr */
  2473. try
  2474. {
  2475. try
  2476. {
  2477. if (FileExists(ApiPath(DestFileName)))
  2478. {
  2479. __int64 MTime;
  2480. TOverwriteFileParams FileParams;
  2481. FileParams.SourceSize = OperationProgress->TransferSize;
  2482. FileParams.SourceTimestamp = FileData.Modification;
  2483. FTerminal->OpenLocalFile(DestFileName, GENERIC_READ,
  2484. NULL, NULL, NULL, &MTime, NULL,
  2485. &FileParams.DestSize);
  2486. FileParams.DestTimestamp = UnixToDateTime(MTime,
  2487. FTerminal->SessionData->DSTMode);
  2488. unsigned int Answer =
  2489. ConfirmOverwrite(OperationProgress->FileName, DestFileNameOnly, osLocal,
  2490. &FileParams, CopyParam, Params, OperationProgress);
  2491. switch (Answer)
  2492. {
  2493. case qaCancel:
  2494. OperationProgress->SetCancel(csCancel); // continue on next case
  2495. case qaNo:
  2496. SkipConfirmed = true;
  2497. EXCEPTION;
  2498. }
  2499. }
  2500. Action.Destination(DestFileName);
  2501. if (!FTerminal->CreateLocalFile(DestFileName, OperationProgress,
  2502. &File, FLAGSET(Params, cpNoConfirmation)))
  2503. {
  2504. SkipConfirmed = true;
  2505. EXCEPTION;
  2506. }
  2507. FileStream = new TSafeHandleStream((THandle)File);
  2508. }
  2509. catch (Exception &E)
  2510. {
  2511. // In this step we can still cancel transfer, so we do it
  2512. SCPError(E.Message, false);
  2513. throw;
  2514. }
  2515. // We succeeded, so we confirm transfer to remote side
  2516. FSecureShell->SendNull();
  2517. // From now we need to finish file transfer, if not it's fatal error
  2518. OperationProgress->SetTransferringFile(true);
  2519. // Suppose same data size to transfer as to write
  2520. // (not true with ASCII transfer)
  2521. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  2522. // Will we use ASCII of BINARY file transfer?
  2523. OperationProgress->SetAsciiTransfer(
  2524. CopyParam->UseAsciiTransfer(BaseFileName, osRemote, MaskParams));
  2525. FTerminal->LogEvent(
  2526. 0, UnicodeString((OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary")) +
  2527. L" transfer mode selected.");
  2528. try
  2529. {
  2530. // Buffer for one block of data
  2531. TFileBuffer BlockBuf;
  2532. bool ConvertToken = false;
  2533. do
  2534. {
  2535. BlockBuf.Size = OperationProgress->TransferBlockSize();
  2536. BlockBuf.Reset();
  2537. FSecureShell->Receive(reinterpret_cast<unsigned char *>(BlockBuf.Data), BlockBuf.Size);
  2538. OperationProgress->AddTransferred(BlockBuf.Size);
  2539. if (OperationProgress->AsciiTransfer)
  2540. {
  2541. unsigned int PrevBlockSize = BlockBuf.Size;
  2542. BlockBuf.Convert(FTerminal->SessionData->EOLType,
  2543. FTerminal->Configuration->LocalEOLType, 0, ConvertToken);
  2544. OperationProgress->SetLocalSize(
  2545. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  2546. }
  2547. // This is crucial, if it fails during file transfer, it's fatal error
  2548. FILE_OPERATION_LOOP_BEGIN
  2549. {
  2550. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  2551. }
  2552. FILE_OPERATION_LOOP_END_EX(FMTLOAD(WRITE_ERROR, (DestFileName)), folNone);
  2553. OperationProgress->AddLocallyUsed(BlockBuf.Size);
  2554. if (OperationProgress->Cancel == csCancelTransfer)
  2555. {
  2556. throw Exception(MainInstructions(LoadStr(USER_TERMINATED)));
  2557. }
  2558. }
  2559. while (!OperationProgress->IsLocallyDone() || !OperationProgress->IsTransferDoneChecked());
  2560. }
  2561. catch (Exception &E)
  2562. {
  2563. // Every exception during file transfer is fatal
  2564. FTerminal->FatalError(&E,
  2565. FMTLOAD(COPY_FATAL, (OperationProgress->FileName)));
  2566. }
  2567. OperationProgress->SetTransferringFile(false);
  2568. try
  2569. {
  2570. SCPResponse();
  2571. // If one of following exception occurs, we still need
  2572. // to send confirmation to other side
  2573. }
  2574. catch (EScp &E)
  2575. {
  2576. FSecureShell->SendNull();
  2577. throw;
  2578. }
  2579. catch (EScpFileSkipped &E)
  2580. {
  2581. FSecureShell->SendNull();
  2582. throw;
  2583. }
  2584. FSecureShell->SendNull();
  2585. if (FileData.SetTime && CopyParam->PreserveTime)
  2586. {
  2587. FTerminal->UpdateTargetTime(File, FileData.Modification, FTerminal->SessionData->DSTMode);
  2588. }
  2589. }
  2590. __finally
  2591. {
  2592. if (File) CloseHandle(File);
  2593. if (FileStream) delete FileStream;
  2594. }
  2595. }
  2596. catch(Exception & E)
  2597. {
  2598. if (SkipConfirmed)
  2599. {
  2600. Action.Cancel();
  2601. }
  2602. else
  2603. {
  2604. FTerminal->RollbackAction(Action, OperationProgress, &E);
  2605. }
  2606. throw;
  2607. }
  2608. if (FileData.Attrs == -1) FileData.Attrs = faArchive;
  2609. int NewAttrs = CopyParam->LocalFileAttrs(FileData.RemoteRights);
  2610. if ((NewAttrs & FileData.Attrs) != NewAttrs)
  2611. {
  2612. FILE_OPERATION_LOOP_BEGIN
  2613. {
  2614. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFileName), FileData.Attrs | NewAttrs) == 0);
  2615. }
  2616. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFileName)));
  2617. }
  2618. FTerminal->LogFileDone(OperationProgress, DestFileName, Action);
  2619. }
  2620. }
  2621. }
  2622. catch (EScpFileSkipped &E)
  2623. {
  2624. if (!SkipConfirmed)
  2625. {
  2626. TSuspendFileOperationProgress Suspend(OperationProgress);
  2627. TQueryParams Params(qpAllowContinueOnError);
  2628. if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FullFileName)),
  2629. &E, qaOK | qaAbort, &Params, qtError) == qaAbort)
  2630. {
  2631. OperationProgress->SetCancel(csCancel);
  2632. }
  2633. FTerminal->Log->AddException(&E);
  2634. }
  2635. // this was inside above condition, but then transfer was considered
  2636. // successful, even when for example user refused to overwrite file
  2637. Success = false;
  2638. }
  2639. catch (ESkipFile &E)
  2640. {
  2641. SCPSendError(E.Message, false);
  2642. Success = false;
  2643. if (!FTerminal->HandleException(&E)) throw;
  2644. }
  2645. }
  2646. }
  2647. //---------------------------------------------------------------------------
  2648. void __fastcall TSCPFileSystem::GetSupportedChecksumAlgs(TStrings * Algs)
  2649. {
  2650. FTerminal->GetShellChecksumAlgs(Algs);
  2651. }
  2652. //---------------------------------------------------------------------------
  2653. void __fastcall TSCPFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  2654. {
  2655. DebugFail();
  2656. }
  2657. //---------------------------------------------------------------------------
  2658. void __fastcall TSCPFileSystem::UnlockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  2659. {
  2660. DebugFail();
  2661. }
  2662. //---------------------------------------------------------------------------
  2663. void __fastcall TSCPFileSystem::UpdateFromMain(TCustomFileSystem * /*MainFileSystem*/)
  2664. {
  2665. // noop
  2666. }
  2667. //---------------------------------------------------------------------------
  2668. void __fastcall TSCPFileSystem::ClearCaches()
  2669. {
  2670. // noop
  2671. }