ScpFileSystem.cpp 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857
  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 TSCPFileSystem::InvalidOutputError(const UnicodeString & Command)
  639. {
  640. FTerminal->TerminalError(FMTLOAD(INVALID_OUTPUT_ERROR, (Command, Output->Text)));
  641. }
  642. //---------------------------------------------------------------------------
  643. void __fastcall TSCPFileSystem::ExecCommand(TFSCommand Cmd, const TVarRec * args,
  644. int size, int Params)
  645. {
  646. if (Params < 0) Params = ecDefault;
  647. UnicodeString FullCommand = FCommandSet->FullCommand(Cmd, args, size);
  648. UnicodeString Command = FCommandSet->Command(Cmd, args, size);
  649. TOperationVisualizer Visualizer(FTerminal->UseBusyCursor);
  650. SendCommand(Command);
  651. int COParams =
  652. coWaitForLastLine |
  653. FLAGMASK(FLAGSET(Params, ecRaiseExcept), coRaiseExcept) |
  654. FLAGMASK(FLAGSET(Params, ecIgnoreWarnings), coIgnoreWarnings) |
  655. FLAGMASK(FLAGSET(Params, ecReadProgress), coReadProgress) |
  656. FLAGMASK(FLAGSET(Params, ecIgnoreStdErr), coIgnoreStdErr);
  657. ReadCommandOutput(COParams, &FullCommand);
  658. if (Params & ecRaiseExcept)
  659. {
  660. Integer MinL = FCommandSet->MinLines[Cmd];
  661. Integer MaxL = FCommandSet->MaxLines[Cmd];
  662. if (((MinL >= 0) && (MinL > FOutput->Count)) ||
  663. ((MaxL >= 0) && (MaxL > FOutput->Count)))
  664. {
  665. InvalidOutputError(FullCommand);
  666. }
  667. }
  668. }
  669. //---------------------------------------------------------------------------
  670. UnicodeString __fastcall TSCPFileSystem::GetCurrentDirectory()
  671. {
  672. return FCurrentDirectory;
  673. }
  674. //---------------------------------------------------------------------------
  675. void __fastcall TSCPFileSystem::DoStartup()
  676. {
  677. // Capabilities of SCP protocol are fixed
  678. FTerminal->SaveCapabilities(FFileSystemInfo);
  679. // SkipStartupMessage and DetectReturnVar must succeed,
  680. // otherwise session is to be closed.
  681. try
  682. {
  683. FTerminal->ExceptionOnFail = true;
  684. SkipStartupMessage();
  685. if (FTerminal->SessionData->DetectReturnVar) DetectReturnVar();
  686. FTerminal->ExceptionOnFail = false;
  687. }
  688. catch (Exception & E)
  689. {
  690. FTerminal->FatalError(&E, L"");
  691. }
  692. // Needs to be done before UnsetNationalVars()
  693. DetectUtf();
  694. #define COND_OPER(OPER) if (FTerminal->SessionData->OPER) OPER()
  695. COND_OPER(ClearAliases);
  696. COND_OPER(UnsetNationalVars);
  697. #undef COND_OPER
  698. }
  699. //---------------------------------------------------------------------------
  700. void __fastcall TSCPFileSystem::DetectUtf()
  701. {
  702. switch (FTerminal->SessionData->NotUtf)
  703. {
  704. case asOn:
  705. FSecureShell->UtfStrings = false; // noop
  706. break;
  707. case asOff:
  708. FSecureShell->UtfStrings = true;
  709. break;
  710. default:
  711. DebugFail();
  712. case asAuto:
  713. FSecureShell->UtfStrings = false; // noop
  714. try
  715. {
  716. ExecCommand(fsLang, NULL, 0, false);
  717. if ((FOutput->Count >= 1) &&
  718. ContainsText(FOutput->Strings[0], L"UTF-8"))
  719. {
  720. FSecureShell->UtfStrings = true;
  721. }
  722. }
  723. catch (Exception & E)
  724. {
  725. // ignore non-fatal errors
  726. if (!FTerminal->Active)
  727. {
  728. throw;
  729. }
  730. }
  731. break;
  732. }
  733. if (FSecureShell->UtfStrings)
  734. {
  735. FTerminal->LogEvent(L"We will use UTF-8");
  736. }
  737. else
  738. {
  739. FTerminal->LogEvent(L"We will not use UTF-8");
  740. }
  741. }
  742. //---------------------------------------------------------------------------
  743. void __fastcall TSCPFileSystem::SkipStartupMessage()
  744. {
  745. try
  746. {
  747. FTerminal->LogEvent(L"Skipping host startup message (if any).");
  748. ExecCommand(fsNull, NULL, 0, 0);
  749. }
  750. catch (Exception & E)
  751. {
  752. FTerminal->CommandError(&E, LoadStr(SKIP_STARTUP_MESSAGE_ERROR), 0, HELP_SKIP_STARTUP_MESSAGE_ERROR);
  753. }
  754. }
  755. //---------------------------------------------------------------------------
  756. void __fastcall TSCPFileSystem::LookupUsersGroups()
  757. {
  758. ExecCommand(fsLookupUsersGroups);
  759. FTerminal->FUsers.Clear();
  760. FTerminal->FGroups.Clear();
  761. if (FOutput->Count > 0)
  762. {
  763. UnicodeString Groups = FOutput->Strings[0];
  764. while (!Groups.IsEmpty())
  765. {
  766. UnicodeString NewGroup = CutToChar(Groups, L' ', false);
  767. FTerminal->FGroups.Add(TRemoteToken(NewGroup));
  768. FTerminal->FMembership.Add(TRemoteToken(NewGroup));
  769. }
  770. }
  771. }
  772. //---------------------------------------------------------------------------
  773. void __fastcall TSCPFileSystem::DetectReturnVar()
  774. {
  775. // This suppose that something was already executed (probably SkipStartupMessage())
  776. // or return code variable is already set on start up.
  777. try
  778. {
  779. // #60 17.10.01: "status" and "?" switched
  780. UnicodeString ReturnVars[2] = { L"status", L"?" };
  781. UnicodeString NewReturnVar = L"";
  782. FTerminal->LogEvent(L"Detecting variable containing return code of last command.");
  783. for (int Index = 0; Index < 2; Index++)
  784. {
  785. bool Success = true;
  786. try
  787. {
  788. FTerminal->LogEvent(FORMAT(L"Trying \"$%s\".", (ReturnVars[Index])));
  789. ExecCommand(fsVarValue, ARRAYOFCONST((ReturnVars[Index])));
  790. if ((Output->Count != 1) || (StrToIntDef(Output->Strings[0], 256) > 255))
  791. {
  792. FTerminal->LogEvent(L"The response is not numerical exit code");
  793. Abort();
  794. }
  795. }
  796. catch (EFatal &E)
  797. {
  798. // if fatal error occurs, we need to exit ...
  799. throw;
  800. }
  801. catch (Exception &E)
  802. {
  803. // ...otherwise, we will try next variable (if any)
  804. Success = false;
  805. }
  806. if (Success)
  807. {
  808. NewReturnVar = ReturnVars[Index];
  809. break;
  810. }
  811. }
  812. if (NewReturnVar.IsEmpty())
  813. {
  814. EXCEPTION;
  815. }
  816. else
  817. {
  818. FCommandSet->ReturnVar = NewReturnVar;
  819. FTerminal->LogEvent(FORMAT(L"Return code variable \"%s\" selected.",
  820. (FCommandSet->ReturnVar)));
  821. }
  822. }
  823. catch (Exception &E)
  824. {
  825. FTerminal->CommandError(&E, LoadStr(DETECT_RETURNVAR_ERROR));
  826. }
  827. }
  828. //---------------------------------------------------------------------------
  829. void __fastcall TSCPFileSystem::ClearAlias(UnicodeString Alias)
  830. {
  831. if (!Alias.IsEmpty())
  832. {
  833. // this command usually fails, because there will never be
  834. // aliases on all commands -> see last False parameter
  835. ExecCommand(fsUnalias, ARRAYOFCONST((Alias)), false);
  836. }
  837. }
  838. //---------------------------------------------------------------------------
  839. void __fastcall TSCPFileSystem::ClearAliases()
  840. {
  841. try
  842. {
  843. FTerminal->LogEvent(L"Clearing all aliases.");
  844. ClearAlias(TCommandSet::ExtractCommand(FTerminal->SessionData->ListingCommand));
  845. TStrings * CommandList = FCommandSet->CreateCommandList();
  846. try
  847. {
  848. for (int Index = 0; Index < CommandList->Count; Index++)
  849. {
  850. ClearAlias(CommandList->Strings[Index]);
  851. }
  852. }
  853. __finally
  854. {
  855. delete CommandList;
  856. }
  857. }
  858. catch (Exception &E)
  859. {
  860. FTerminal->CommandError(&E, LoadStr(UNALIAS_ALL_ERROR));
  861. }
  862. }
  863. //---------------------------------------------------------------------------
  864. void __fastcall TSCPFileSystem::UnsetNationalVars()
  865. {
  866. try
  867. {
  868. FTerminal->LogEvent(L"Clearing national user variables.");
  869. for (size_t Index = 0; Index < LENOF(NationalVars); Index++)
  870. {
  871. ExecCommand(fsUnset, ARRAYOFCONST((NationalVars[Index])), false);
  872. }
  873. }
  874. catch (Exception &E)
  875. {
  876. FTerminal->CommandError(&E, LoadStr(UNSET_NATIONAL_ERROR));
  877. }
  878. }
  879. //---------------------------------------------------------------------------
  880. void __fastcall TSCPFileSystem::ReadCurrentDirectory()
  881. {
  882. if (FCachedDirectoryChange.IsEmpty())
  883. {
  884. ExecCommand(fsCurrentDirectory);
  885. FCurrentDirectory = UnixExcludeTrailingBackslash(FOutput->Strings[0]);
  886. }
  887. else
  888. {
  889. FCurrentDirectory = FCachedDirectoryChange;
  890. }
  891. }
  892. //---------------------------------------------------------------------------
  893. void __fastcall TSCPFileSystem::HomeDirectory()
  894. {
  895. ExecCommand(fsHomeDirectory);
  896. }
  897. //---------------------------------------------------------------------------
  898. void __fastcall TSCPFileSystem::AnnounceFileListOperation()
  899. {
  900. // noop
  901. }
  902. //---------------------------------------------------------------------------
  903. void __fastcall TSCPFileSystem::ChangeDirectory(const UnicodeString Directory)
  904. {
  905. UnicodeString ToDir;
  906. // This effectivelly disallows entering subdirectories starting with ~ and containing space
  907. if (!Directory.IsEmpty() &&
  908. ((Directory[1] != L'~') || (Directory.SubString(1, 2) == L"~ ")))
  909. {
  910. ToDir = ShellQuoteStr(Directory);
  911. }
  912. else
  913. {
  914. ToDir = DelimitStr(Directory);
  915. }
  916. ExecCommand(fsChangeDirectory, ARRAYOFCONST((ToDir)));
  917. FCachedDirectoryChange = L"";
  918. }
  919. //---------------------------------------------------------------------------
  920. void __fastcall TSCPFileSystem::CachedChangeDirectory(const UnicodeString Directory)
  921. {
  922. FCachedDirectoryChange = UnixExcludeTrailingBackslash(Directory);
  923. }
  924. //---------------------------------------------------------------------------
  925. void __fastcall TSCPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  926. {
  927. DebugAssert(FileList);
  928. // emptying file list moved before command execution
  929. FileList->Reset();
  930. bool Again;
  931. do
  932. {
  933. Again = false;
  934. try
  935. {
  936. int Params = ecDefault | ecReadProgress |
  937. FLAGMASK(FTerminal->SessionData->IgnoreLsWarnings, ecIgnoreWarnings);
  938. const wchar_t * Options =
  939. ((FLsFullTime == asAuto) || (FLsFullTime == asOn)) ? FullTimeOption : L"";
  940. bool ListCurrentDirectory = (FileList->Directory == FTerminal->CurrentDirectory);
  941. if (ListCurrentDirectory)
  942. {
  943. FTerminal->LogEvent(L"Listing current directory.");
  944. ExecCommand(fsListCurrentDirectory,
  945. ARRAYOFCONST((FTerminal->SessionData->ListingCommand, Options)), Params);
  946. }
  947. else
  948. {
  949. FTerminal->LogEvent(FORMAT(L"Listing directory \"%s\".",
  950. (FileList->Directory)));
  951. ExecCommand(fsListDirectory,
  952. ARRAYOFCONST((FTerminal->SessionData->ListingCommand, Options,
  953. DelimitStr(FileList->Directory))),
  954. Params);
  955. }
  956. // If output is not empty, we have successfully got file listing,
  957. // otherwise there was an error, in case it was "permission denied"
  958. // we try to get at least parent directory (see "else" statement below)
  959. if (FOutput->Count > 0)
  960. {
  961. // Copy LS command output, because eventual symlink analysis would
  962. // modify FTerminal->Output
  963. TStringList * OutputCopy = new TStringList();
  964. try
  965. {
  966. OutputCopy->Assign(FOutput);
  967. // delete leading "total xxx" line
  968. // On some hosts there is not "total" but "totalt". What's the reason??
  969. // see mail from "Jan Wiklund (SysOp)" <[email protected]>
  970. if (IsTotalListingLine(OutputCopy->Strings[0]))
  971. {
  972. OutputCopy->Delete(0);
  973. }
  974. for (int Index = 0; Index < OutputCopy->Count; Index++)
  975. {
  976. UnicodeString OutputLine = OutputCopy->Strings[Index];
  977. if (!OutputLine.IsEmpty())
  978. {
  979. std::unique_ptr<TRemoteFile> File(CreateRemoteFile(OutputCopy->Strings[Index]));
  980. if (FTerminal->IsValidFile(File.get()))
  981. {
  982. FileList->AddFile(File.release());
  983. }
  984. }
  985. }
  986. }
  987. __finally
  988. {
  989. delete OutputCopy;
  990. }
  991. }
  992. else
  993. {
  994. bool Empty;
  995. if (ListCurrentDirectory)
  996. {
  997. // Empty file list -> probably "permission denied", we
  998. // at least get link to parent directory ("..")
  999. TRemoteFile * File = FTerminal->ReadFile(UnixCombinePaths(FTerminal->FFiles->Directory, PARENTDIRECTORY));
  1000. Empty = (File == NULL);
  1001. if (!Empty)
  1002. {
  1003. DebugAssert(File->IsParentDirectory);
  1004. FileList->AddFile(File);
  1005. }
  1006. }
  1007. else
  1008. {
  1009. Empty = true;
  1010. }
  1011. if (Empty)
  1012. {
  1013. throw ExtException(
  1014. NULL, FMTLOAD(EMPTY_DIRECTORY, (FileList->Directory)),
  1015. HELP_EMPTY_DIRECTORY);
  1016. }
  1017. }
  1018. if (FLsFullTime == asAuto)
  1019. {
  1020. FTerminal->LogEvent(
  1021. FORMAT(L"Directory listing with %s succeed, next time all errors during "
  1022. "directory listing will be displayed immediately.",
  1023. (FullTimeOption)));
  1024. FLsFullTime = asOn;
  1025. }
  1026. }
  1027. catch(Exception & E)
  1028. {
  1029. if (FTerminal->Active)
  1030. {
  1031. if (FLsFullTime == asAuto)
  1032. {
  1033. FTerminal->Log->AddException(&E);
  1034. FLsFullTime = asOff;
  1035. Again = true;
  1036. FTerminal->LogEvent(
  1037. FORMAT(L"Directory listing with %s failed, try again regular listing.",
  1038. (FullTimeOption)));
  1039. }
  1040. else
  1041. {
  1042. throw;
  1043. }
  1044. }
  1045. else
  1046. {
  1047. throw;
  1048. }
  1049. }
  1050. }
  1051. while (Again);
  1052. }
  1053. //---------------------------------------------------------------------------
  1054. void __fastcall TSCPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  1055. TRemoteFile *& File)
  1056. {
  1057. CustomReadFile(SymlinkFile->LinkTo, File, SymlinkFile);
  1058. }
  1059. //---------------------------------------------------------------------------
  1060. void __fastcall TSCPFileSystem::ReadFile(const UnicodeString FileName,
  1061. TRemoteFile *& File)
  1062. {
  1063. CustomReadFile(FileName, File, NULL);
  1064. }
  1065. //---------------------------------------------------------------------------
  1066. TRemoteFile * __fastcall TSCPFileSystem::CreateRemoteFile(
  1067. const UnicodeString & ListingStr, TRemoteFile * LinkedByFile)
  1068. {
  1069. TRemoteFile * File = new TRemoteFile(LinkedByFile);
  1070. try
  1071. {
  1072. File->Terminal = FTerminal;
  1073. File->ListingStr = ListingStr;
  1074. File->ShiftTimeInSeconds(TimeToSeconds(FTerminal->SessionData->TimeDifference));
  1075. File->Complete();
  1076. }
  1077. catch(...)
  1078. {
  1079. delete File;
  1080. throw;
  1081. }
  1082. return File;
  1083. }
  1084. //---------------------------------------------------------------------------
  1085. void __fastcall TSCPFileSystem::CustomReadFile(const UnicodeString FileName,
  1086. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  1087. {
  1088. File = NULL;
  1089. int Params = ecDefault |
  1090. FLAGMASK(FTerminal->SessionData->IgnoreLsWarnings, ecIgnoreWarnings);
  1091. // the auto-detection of --full-time support is not implemented for fsListFile,
  1092. // so we use it only if we already know that it is supported (asOn).
  1093. const wchar_t * Options = (FLsFullTime == asOn) ? FullTimeOption : L"";
  1094. ExecCommand(fsListFile,
  1095. ARRAYOFCONST((FTerminal->SessionData->ListingCommand, Options, DelimitStr(FileName))),
  1096. Params);
  1097. if (FOutput->Count)
  1098. {
  1099. int LineIndex = 0;
  1100. if (IsTotalListingLine(FOutput->Strings[LineIndex]) && FOutput->Count > 1)
  1101. {
  1102. LineIndex++;
  1103. }
  1104. File = CreateRemoteFile(FOutput->Strings[LineIndex], ALinkedByFile);
  1105. }
  1106. }
  1107. //---------------------------------------------------------------------------
  1108. void __fastcall TSCPFileSystem::DeleteFile(const UnicodeString FileName,
  1109. const TRemoteFile * File, int Params, TRmSessionAction & Action)
  1110. {
  1111. DebugUsedParam(File);
  1112. DebugUsedParam(Params);
  1113. Action.Recursive();
  1114. DebugAssert(FLAGCLEAR(Params, dfNoRecursive) || (File && File->IsSymLink));
  1115. ExecCommand(fsDeleteFile, ARRAYOFCONST((DelimitStr(FileName))));
  1116. }
  1117. //---------------------------------------------------------------------------
  1118. void __fastcall TSCPFileSystem::RenameFile(
  1119. const UnicodeString & FileName, const TRemoteFile *, const UnicodeString & NewName, bool DebugUsedArg(Overwrite))
  1120. {
  1121. ExecCommand(fsRenameFile, ARRAYOFCONST((DelimitStr(FileName), DelimitStr(NewName))));
  1122. }
  1123. //---------------------------------------------------------------------------
  1124. void __fastcall TSCPFileSystem::CopyFile(
  1125. const UnicodeString & FileName, const TRemoteFile *, const UnicodeString & NewName, bool DebugUsedArg(Overwrite))
  1126. {
  1127. UnicodeString DelimitedFileName = DelimitStr(FileName);
  1128. UnicodeString DelimitedNewName = DelimitStr(NewName);
  1129. const UnicodeString AdditionalSwitches = L"-T";
  1130. try
  1131. {
  1132. ExecCommand(fsCopyFile, ARRAYOFCONST((AdditionalSwitches, DelimitedFileName, DelimitedNewName)));
  1133. }
  1134. catch (Exception & E)
  1135. {
  1136. if (FTerminal->Active)
  1137. {
  1138. // The -T is GNU switch and may not be available on all platforms.
  1139. // https://lists.gnu.org/archive/html/bug-coreutils/2004-07/msg00000.html
  1140. FTerminal->LogEvent(FORMAT(L"Attempt with %s failed, trying without", (AdditionalSwitches)));
  1141. ExecCommand(fsCopyFile, ARRAYOFCONST((L"", DelimitedFileName, DelimitedNewName)));
  1142. }
  1143. else
  1144. {
  1145. throw;
  1146. }
  1147. }
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. void __fastcall TSCPFileSystem::CreateDirectory(const UnicodeString & DirName, bool /*Encrypt*/)
  1151. {
  1152. ExecCommand(fsCreateDirectory, ARRAYOFCONST((DelimitStr(DirName))));
  1153. }
  1154. //---------------------------------------------------------------------------
  1155. void __fastcall TSCPFileSystem::CreateLink(const UnicodeString FileName,
  1156. const UnicodeString PointTo, bool Symbolic)
  1157. {
  1158. ExecCommand(fsCreateLink,
  1159. ARRAYOFCONST((Symbolic ? L"-s" : L"", DelimitStr(PointTo), DelimitStr(FileName))));
  1160. }
  1161. //---------------------------------------------------------------------------
  1162. void __fastcall TSCPFileSystem::ChangeFileToken(const UnicodeString & DelimitedName,
  1163. const TRemoteToken & Token, TFSCommand Cmd, const UnicodeString & RecursiveStr)
  1164. {
  1165. UnicodeString Str;
  1166. if (Token.IDValid)
  1167. {
  1168. Str = IntToStr(int(Token.ID));
  1169. }
  1170. else if (Token.NameValid)
  1171. {
  1172. Str = Token.Name;
  1173. }
  1174. if (!Str.IsEmpty())
  1175. {
  1176. ExecCommand(Cmd, ARRAYOFCONST((RecursiveStr, Str, DelimitedName)));
  1177. }
  1178. }
  1179. //---------------------------------------------------------------------------
  1180. void __fastcall TSCPFileSystem::ChangeFileProperties(const UnicodeString FileName,
  1181. const TRemoteFile * File, const TRemoteProperties * Properties,
  1182. TChmodSessionAction & Action)
  1183. {
  1184. DebugAssert(Properties);
  1185. int Directory = ((File == NULL) ? -1 : (File->IsDirectory ? 1 : 0));
  1186. bool IsDirectory = (Directory > 0);
  1187. bool Recursive = Properties->Recursive && IsDirectory;
  1188. UnicodeString RecursiveStr = Recursive ? L"-R" : L"";
  1189. UnicodeString DelimitedName = DelimitStr(FileName);
  1190. // change group before permissions as chgrp change permissions
  1191. if (Properties->Valid.Contains(vpGroup))
  1192. {
  1193. ChangeFileToken(DelimitedName, Properties->Group, fsChangeGroup, RecursiveStr);
  1194. }
  1195. if (Properties->Valid.Contains(vpOwner))
  1196. {
  1197. ChangeFileToken(DelimitedName, Properties->Owner, fsChangeOwner, RecursiveStr);
  1198. }
  1199. if (Properties->Valid.Contains(vpRights))
  1200. {
  1201. TRights Rights = Properties->Rights;
  1202. // if we don't set modes recursively, we may add X at once with other
  1203. // options. Otherwise we have to add X after recursive command
  1204. if (!Recursive && IsDirectory && Properties->AddXToDirectories)
  1205. Rights.AddExecute();
  1206. Action.Rights(Rights);
  1207. if (Recursive)
  1208. {
  1209. Action.Recursive();
  1210. }
  1211. if ((Rights.NumberSet | Rights.NumberUnset) != TRights::rfNo)
  1212. {
  1213. ExecCommand(fsChangeMode,
  1214. ARRAYOFCONST((RecursiveStr, Rights.GetChmodStr(Directory), DelimitedName)));
  1215. }
  1216. // if file is directory and we do recursive mode settings with
  1217. // add-x-to-directories option on, add those X
  1218. if (Recursive && IsDirectory && Properties->AddXToDirectories)
  1219. {
  1220. Rights.AddExecute();
  1221. ExecCommand(fsChangeMode,
  1222. ARRAYOFCONST((L"", Rights.GetChmodStr(Directory), DelimitedName)));
  1223. }
  1224. }
  1225. else
  1226. {
  1227. Action.Cancel();
  1228. }
  1229. DebugAssert(!Properties->Valid.Contains(vpLastAccess));
  1230. DebugAssert(!Properties->Valid.Contains(vpModification));
  1231. }
  1232. //---------------------------------------------------------------------------
  1233. bool __fastcall TSCPFileSystem::LoadFilesProperties(TStrings * /*FileList*/ )
  1234. {
  1235. DebugFail();
  1236. return false;
  1237. }
  1238. //---------------------------------------------------------------------------
  1239. UnicodeString TSCPFileSystem::CalculateFilesChecksumInitialize(const UnicodeString & Alg)
  1240. {
  1241. std::unique_ptr<TStrings> Algs(new TStringList());
  1242. GetSupportedChecksumAlgs(Algs.get());
  1243. return FindIdent(Alg, Algs.get());
  1244. }
  1245. //---------------------------------------------------------------------------
  1246. UnicodeString TSCPFileSystem::ParseFileChecksum(
  1247. const UnicodeString & Line, const UnicodeString & FileName, const UnicodeString & Command)
  1248. {
  1249. int P = Line.Pos(L" ");
  1250. if ((P < 0) ||
  1251. (P == Line.Length()) ||
  1252. ((Line[P + 1] != L' ') && (Line[P + 1] != L'*')) ||
  1253. (Line.SubString(P + 2, Line.Length() - P - 1) != FileName))
  1254. {
  1255. InvalidOutputError(Command);
  1256. }
  1257. return Line.SubString(1, P - 1);
  1258. }
  1259. //---------------------------------------------------------------------------
  1260. void TSCPFileSystem::ProcessFileChecksum(
  1261. TCalculatedChecksumEvent OnCalculatedChecksum, TChecksumSessionAction & Action, TFileOperationProgressType * OperationProgress,
  1262. bool FirstLevel, const UnicodeString & FileName, const UnicodeString & Alg, const UnicodeString & Checksum)
  1263. {
  1264. bool Success = !Checksum.IsEmpty();
  1265. if (Success)
  1266. {
  1267. if (OnCalculatedChecksum != NULL)
  1268. {
  1269. OnCalculatedChecksum(UnixExtractFileName(FileName), Alg, Checksum);
  1270. }
  1271. Action.Checksum(Alg, Checksum);
  1272. }
  1273. if (FirstLevel)
  1274. {
  1275. TOnceDoneOperation OnceDoneOperation; // not used
  1276. OperationProgress->Finish(FileName, Success, OnceDoneOperation);
  1277. }
  1278. }
  1279. //---------------------------------------------------------------------------
  1280. void __fastcall TSCPFileSystem::CalculateFilesChecksum(
  1281. const UnicodeString & Alg, TStrings * FileList, TCalculatedChecksumEvent OnCalculatedChecksum,
  1282. TFileOperationProgressType * OperationProgress, bool FirstLevel)
  1283. {
  1284. FTerminal->CalculateSubFoldersChecksum(Alg, FileList, OnCalculatedChecksum, OperationProgress, FirstLevel);
  1285. TStrings * AlgDefs = FTerminal->GetShellChecksumAlgDefs();
  1286. int AlgIndex = AlgDefs->IndexOfName(Alg);
  1287. UnicodeString AlgCommand = (AlgIndex >= 0) ? AlgDefs->ValueFromIndex[AlgIndex] : Alg;
  1288. int Index = 0;
  1289. while ((Index < FileList->Count) && !OperationProgress->Cancel)
  1290. {
  1291. std::unique_ptr<TStrings> BatchFileList(new TStringList());
  1292. UnicodeString FileListCommandLine;
  1293. __int64 BatchSize = 0;
  1294. while (Index < FileList->Count)
  1295. {
  1296. TRemoteFile * File = DebugNotNull(dynamic_cast<TRemoteFile *>(FileList->Objects[Index]));
  1297. if (!File->IsDirectory)
  1298. {
  1299. UnicodeString FileName = FileList->Strings[Index];
  1300. UnicodeString FileListCommandLineBak = FileListCommandLine;
  1301. AddToShellFileListCommandLine(FileListCommandLine, FileName);
  1302. BatchSize += File->Size;
  1303. if (!FileListCommandLineBak.IsEmpty() &&
  1304. ((FileListCommandLine.Length() > 2048) ||
  1305. (BatchSize > 1024*1024*1024)))
  1306. {
  1307. FileListCommandLine = FileListCommandLineBak;
  1308. break;
  1309. }
  1310. else
  1311. {
  1312. BatchFileList->AddObject(FileName, File);
  1313. }
  1314. }
  1315. Index++;
  1316. }
  1317. if (!FileListCommandLine.IsEmpty())
  1318. {
  1319. bool IndividualCommands = false;
  1320. std::unique_ptr<TStrings> BatchChecksums(new TStringList());
  1321. try
  1322. {
  1323. UnicodeString BatchCommand = FORMAT(L"%s %s", (AlgCommand, FileListCommandLine));
  1324. AnyCommand(BatchCommand, NULL);
  1325. if (Output->Count != BatchFileList->Count)
  1326. {
  1327. InvalidOutputError(BatchCommand);
  1328. }
  1329. // First do everything that can throw.
  1330. // Only once everything is checked, distribute the results.
  1331. for (int BatchIndex = 0; BatchIndex < BatchFileList->Count; BatchIndex++)
  1332. {
  1333. UnicodeString FileName = BatchFileList->Strings[BatchIndex];
  1334. UnicodeString Line = Output->Strings[BatchIndex];
  1335. UnicodeString Checksum = ParseFileChecksum(Line, FileName, BatchCommand);
  1336. BatchChecksums->Add(Checksum);
  1337. }
  1338. }
  1339. catch (Exception & E)
  1340. {
  1341. if (!FTerminal->Active)
  1342. {
  1343. throw;
  1344. }
  1345. else
  1346. {
  1347. IndividualCommands = true;
  1348. }
  1349. }
  1350. if (!IndividualCommands)
  1351. {
  1352. // None of this should throw
  1353. for (int BatchIndex = 0; BatchIndex < BatchFileList->Count; BatchIndex++)
  1354. {
  1355. UnicodeString FileName = BatchFileList->Strings[BatchIndex];
  1356. TRemoteFile * File = DebugNotNull(dynamic_cast<TRemoteFile *>(BatchFileList->Objects[BatchIndex]));
  1357. TChecksumSessionAction Action(FTerminal->ActionLog);
  1358. Action.FileName(File->FullFileName);
  1359. OperationProgress->SetFile(FileName);
  1360. UnicodeString Checksum = BatchChecksums->Strings[BatchIndex];
  1361. ProcessFileChecksum(OnCalculatedChecksum, Action, OperationProgress, FirstLevel, FileName, Alg, Checksum);
  1362. }
  1363. }
  1364. else
  1365. {
  1366. FTerminal->LogEvent(
  1367. L"Batch checksum calculation failed, falling back to calculating checksum individually for each file...");
  1368. for (int BatchIndex = 0; BatchIndex < BatchFileList->Count; BatchIndex++)
  1369. {
  1370. TRemoteFile * File = DebugNotNull(dynamic_cast<TRemoteFile *>(BatchFileList->Objects[BatchIndex]));
  1371. TChecksumSessionAction Action(FTerminal->ActionLog);
  1372. try
  1373. {
  1374. UnicodeString FileName = BatchFileList->Strings[BatchIndex];
  1375. OperationProgress->SetFile(FileName);
  1376. Action.FileName(File->FullFileName);
  1377. UnicodeString Checksum;
  1378. try
  1379. {
  1380. UnicodeString Command = FORMAT(L"%s %s", (AlgCommand, ShellQuoteStr(FileName)));
  1381. AnyCommand(Command, NULL);
  1382. if (Output->Count != 1)
  1383. {
  1384. InvalidOutputError(Command);
  1385. }
  1386. UnicodeString Line = Output->Strings[0];
  1387. Checksum = ParseFileChecksum(Line, FileName, Command);
  1388. }
  1389. __finally
  1390. {
  1391. ProcessFileChecksum(OnCalculatedChecksum, Action, OperationProgress, FirstLevel, FileName, Alg, Checksum);
  1392. }
  1393. }
  1394. catch (Exception & E)
  1395. {
  1396. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1397. UnicodeString Error = FMTLOAD(CHECKSUM_ERROR, (File->FullFileName));
  1398. FTerminal->CommandError(&E, Error);
  1399. // Abort loop.
  1400. // TODO: retries? resume?
  1401. BatchIndex = BatchFileList->Count;
  1402. Index = FileList->Count;
  1403. }
  1404. }
  1405. }
  1406. }
  1407. }
  1408. }
  1409. //---------------------------------------------------------------------------
  1410. void __fastcall TSCPFileSystem::CustomCommandOnFile(const UnicodeString FileName,
  1411. const TRemoteFile * File, UnicodeString Command, int Params,
  1412. TCaptureOutputEvent OutputEvent)
  1413. {
  1414. DebugAssert(File);
  1415. bool Dir = File->IsDirectory && FTerminal->CanRecurseToDirectory(File);
  1416. if (Dir && (Params & ccRecursive))
  1417. {
  1418. TCustomCommandParams AParams;
  1419. AParams.Command = Command;
  1420. AParams.Params = Params;
  1421. AParams.OutputEvent = OutputEvent;
  1422. FTerminal->ProcessDirectory(FileName, FTerminal->CustomCommandOnFile,
  1423. &AParams);
  1424. }
  1425. if (!Dir || (Params & ccApplyToDirectories))
  1426. {
  1427. TCustomCommandData Data(FTerminal);
  1428. UnicodeString Cmd = TRemoteCustomCommand(
  1429. Data, FTerminal->CurrentDirectory, FileName, L"").
  1430. Complete(Command, true);
  1431. if (!FTerminal->DoOnCustomCommand(Cmd))
  1432. {
  1433. AnyCommand(Cmd, OutputEvent);
  1434. }
  1435. }
  1436. }
  1437. //---------------------------------------------------------------------------
  1438. void __fastcall TSCPFileSystem::CaptureOutput(const UnicodeString & AddedLine, TCaptureOutputType OutputType)
  1439. {
  1440. int ReturnCode;
  1441. UnicodeString Line = AddedLine;
  1442. // TSecureShell never uses cotExitCode
  1443. DebugAssert((OutputType == cotOutput) || (OutputType == cotError));
  1444. if ((OutputType == cotError) || DebugAlwaysFalse(OutputType == cotExitCode) ||
  1445. !RemoveLastLine(Line, ReturnCode) ||
  1446. !Line.IsEmpty())
  1447. {
  1448. DebugAssert(FOnCaptureOutput != NULL);
  1449. FOnCaptureOutput(Line, OutputType);
  1450. }
  1451. }
  1452. //---------------------------------------------------------------------------
  1453. void __fastcall TSCPFileSystem::AnyCommand(const UnicodeString Command,
  1454. TCaptureOutputEvent OutputEvent)
  1455. {
  1456. DebugAssert(FSecureShell->OnCaptureOutput == NULL);
  1457. if (OutputEvent != NULL)
  1458. {
  1459. FSecureShell->OnCaptureOutput = CaptureOutput;
  1460. FOnCaptureOutput = OutputEvent;
  1461. }
  1462. try
  1463. {
  1464. int Params =
  1465. ecDefault |
  1466. (FTerminal->SessionData->ExitCode1IsError ? ecIgnoreStdErr : ecIgnoreWarnings);
  1467. ExecCommand(fsAnyCommand, ARRAYOFCONST((Command)), Params);
  1468. }
  1469. __finally
  1470. {
  1471. FOnCaptureOutput = NULL;
  1472. FSecureShell->OnCaptureOutput = NULL;
  1473. }
  1474. }
  1475. //---------------------------------------------------------------------------
  1476. TStrings * __fastcall TSCPFileSystem::GetFixedPaths()
  1477. {
  1478. return NULL;
  1479. }
  1480. //---------------------------------------------------------------------------
  1481. void __fastcall TSCPFileSystem::SpaceAvailable(const UnicodeString Path,
  1482. TSpaceAvailable & /*ASpaceAvailable*/)
  1483. {
  1484. DebugFail();
  1485. }
  1486. //---------------------------------------------------------------------------
  1487. // transfer protocol
  1488. //---------------------------------------------------------------------------
  1489. unsigned int __fastcall TSCPFileSystem::ConfirmOverwrite(
  1490. const UnicodeString & SourceFullFileName, const UnicodeString & TargetFileName, TOperationSide Side,
  1491. const TOverwriteFileParams * FileParams, const TCopyParamType * CopyParam,
  1492. int Params, TFileOperationProgressType * OperationProgress)
  1493. {
  1494. TSuspendFileOperationProgress Suspend(OperationProgress);
  1495. TQueryButtonAlias Aliases[3];
  1496. Aliases[0] = TQueryButtonAlias::CreateAllAsYesToNewerGrouppedWithYes();
  1497. Aliases[1] = TQueryButtonAlias::CreateYesToAllGrouppedWithYes();
  1498. Aliases[2] = TQueryButtonAlias::CreateNoToAllGrouppedWithNo();
  1499. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1500. QueryParams.Aliases = Aliases;
  1501. QueryParams.AliasesCount = LENOF(Aliases);
  1502. unsigned int Answer =
  1503. FTerminal->ConfirmFileOverwrite(
  1504. SourceFullFileName, TargetFileName, FileParams,
  1505. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll,
  1506. &QueryParams, Side, CopyParam, Params, OperationProgress);
  1507. return Answer;
  1508. }
  1509. //---------------------------------------------------------------------------
  1510. void __fastcall TSCPFileSystem::SCPResponse(bool * GotLastLine)
  1511. {
  1512. // Taken from scp.c response() and modified
  1513. unsigned char Resp;
  1514. FSecureShell->Receive(&Resp, 1);
  1515. switch (Resp)
  1516. {
  1517. case 0: /* ok */
  1518. FTerminal->LogEvent(L"SCP remote side confirmation (0)");
  1519. return;
  1520. default:
  1521. case 1: /* error */
  1522. case 2: /* fatal error */
  1523. // pscp adds 'Resp' to 'Msg', why?
  1524. UnicodeString Msg = FSecureShell->ReceiveLine();
  1525. UnicodeString Line = UnicodeString(static_cast<char>(Resp)) + Msg;
  1526. if (IsLastLine(Line))
  1527. {
  1528. if (GotLastLine != NULL)
  1529. {
  1530. *GotLastLine = true;
  1531. }
  1532. /* TODO 1 : Show stderror to user? */
  1533. FSecureShell->ClearStdError();
  1534. try
  1535. {
  1536. ReadCommandOutput(coExpectNoOutput | coRaiseExcept | coOnlyReturnCode);
  1537. }
  1538. catch(...)
  1539. {
  1540. // when ReadCommandOutput() fails than remote SCP is terminated already
  1541. if (GotLastLine != NULL)
  1542. {
  1543. *GotLastLine = true;
  1544. }
  1545. throw;
  1546. }
  1547. }
  1548. else if (Resp == 1)
  1549. {
  1550. // While the OpenSSH scp client distinguishes the 1 for error and 2 for fatal errors,
  1551. // the OpenSSH scp server always sends 1 even for fatal errors. Using the error message to tell
  1552. // which errors are fatal and which are not.
  1553. // This error list is valid for OpenSSH 5.3p1 and 7.2p2
  1554. if (SameText(Msg, L"scp: ambiguous target") ||
  1555. StartsText(L"scp: error: unexpected filename: ", Msg) ||
  1556. StartsText(L"scp: protocol error: ", Msg))
  1557. {
  1558. FTerminal->LogEvent(L"SCP remote side error (1), fatal error detected from error message");
  1559. Resp = 2;
  1560. FScpFatalError = true;
  1561. }
  1562. else
  1563. {
  1564. FTerminal->LogEvent(L"SCP remote side error (1)");
  1565. }
  1566. }
  1567. else
  1568. {
  1569. FTerminal->LogEvent(L"SCP remote side fatal error (2)");
  1570. FScpFatalError = true;
  1571. }
  1572. if (Resp == 1)
  1573. {
  1574. throw EScpFileSkipped(NULL, Msg);
  1575. }
  1576. else
  1577. {
  1578. throw EScp(NULL, Msg);
  1579. }
  1580. }
  1581. }
  1582. //---------------------------------------------------------------------------
  1583. void __fastcall TSCPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1584. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  1585. int Params, TFileOperationProgressType * OperationProgress,
  1586. TOnceDoneOperation & OnceDoneOperation)
  1587. {
  1588. // scp.c: source(), toremote()
  1589. DebugAssert(FilesToCopy && OperationProgress);
  1590. Params &= ~(cpAppend | cpResume);
  1591. UnicodeString Options = L"";
  1592. bool CheckExistence = UnixSamePath(TargetDir, FTerminal->CurrentDirectory) &&
  1593. (FTerminal->FFiles != NULL) && FTerminal->FFiles->Loaded;
  1594. bool CopyBatchStarted = false;
  1595. bool Failed = true;
  1596. bool GotLastLine = false;
  1597. UnicodeString TargetDirFull = UnixIncludeTrailingBackslash(TargetDir);
  1598. if (CopyParam->PreserveRights) Options = L"-p";
  1599. if (FTerminal->SessionData->Scp1Compatibility) Options += L" -1";
  1600. FScpFatalError = false;
  1601. SendCommand(FCommandSet->FullCommand(fsCopyToRemote,
  1602. ARRAYOFCONST((Options, DelimitStr(UnixExcludeTrailingBackslash(TargetDir))))));
  1603. SkipFirstLine();
  1604. try
  1605. {
  1606. try
  1607. {
  1608. SCPResponse(&GotLastLine);
  1609. // This can happen only if SCP command is not executed and return code is 0
  1610. // It has never happened to me (return code is usually 127)
  1611. if (GotLastLine)
  1612. {
  1613. throw Exception(L"");
  1614. }
  1615. }
  1616. catch(Exception & E)
  1617. {
  1618. if (GotLastLine && FTerminal->Active)
  1619. {
  1620. FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
  1621. }
  1622. else
  1623. {
  1624. throw;
  1625. }
  1626. }
  1627. CopyBatchStarted = true;
  1628. for (int IFile = 0; (IFile < FilesToCopy->Count) &&
  1629. !OperationProgress->Cancel; IFile++)
  1630. {
  1631. UnicodeString FileName = FilesToCopy->Strings[IFile];
  1632. bool CanProceed;
  1633. UnicodeString FileNameOnly =
  1634. FTerminal->ChangeFileName(
  1635. CopyParam, ExtractFileName(FileName), osLocal, true);
  1636. if (CheckExistence)
  1637. {
  1638. // previously there was assertion on FTerminal->FFiles->Loaded, but it
  1639. // fails for scripting, if 'ls' is not issued before.
  1640. // formally we should call CheckRemoteFile here but as checking is for
  1641. // free here (almost) ...
  1642. TRemoteFile * File = FTerminal->FFiles->FindFile(FileNameOnly);
  1643. if (File != NULL)
  1644. {
  1645. unsigned int Answer;
  1646. if (File->IsDirectory)
  1647. {
  1648. UnicodeString Message = MainInstructions(FMTLOAD(DIRECTORY_OVERWRITE, (FileNameOnly)));
  1649. TQueryParams QueryParams(qpNeverAskAgainCheck);
  1650. TSuspendFileOperationProgress Suspend(OperationProgress);
  1651. Answer = FTerminal->ConfirmFileOverwrite(
  1652. FileName, FileNameOnly, NULL,
  1653. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll,
  1654. &QueryParams, osRemote, CopyParam, Params, OperationProgress, Message);
  1655. }
  1656. else
  1657. {
  1658. __int64 MTime;
  1659. TOverwriteFileParams FileParams;
  1660. FTerminal->OpenLocalFile(FileName, GENERIC_READ,
  1661. NULL, NULL, NULL, &MTime, NULL,
  1662. &FileParams.SourceSize);
  1663. FileParams.SourceTimestamp = UnixToDateTime(MTime,
  1664. FTerminal->SessionData->DSTMode);
  1665. FileParams.DestSize = File->Size;
  1666. FileParams.DestTimestamp = File->Modification;
  1667. Answer = ConfirmOverwrite(FileName, FileNameOnly, osRemote,
  1668. &FileParams, CopyParam, Params, OperationProgress);
  1669. }
  1670. switch (Answer)
  1671. {
  1672. case qaYes:
  1673. CanProceed = true;
  1674. break;
  1675. case qaCancel:
  1676. OperationProgress->SetCancelAtLeast(csCancel);
  1677. case qaNo:
  1678. CanProceed = false;
  1679. break;
  1680. default:
  1681. DebugFail();
  1682. break;
  1683. }
  1684. }
  1685. else
  1686. {
  1687. CanProceed = true;
  1688. }
  1689. }
  1690. else
  1691. {
  1692. CanProceed = true;
  1693. }
  1694. if (CanProceed)
  1695. {
  1696. if (FTerminal->SessionData->CacheDirectories)
  1697. {
  1698. FTerminal->DirectoryModified(TargetDir, false);
  1699. if (DirectoryExists(ApiPath(FileName)))
  1700. {
  1701. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  1702. FileNameOnly, true);
  1703. }
  1704. }
  1705. void * Item = static_cast<void *>(FilesToCopy->Objects[IFile]);
  1706. try
  1707. {
  1708. SCPSource(FileName, TargetDirFull,
  1709. CopyParam, Params, OperationProgress, 0);
  1710. FTerminal->OperationFinish(OperationProgress, Item, FileName, true, OnceDoneOperation);
  1711. }
  1712. catch (EScpFileSkipped &E)
  1713. {
  1714. TQueryParams Params(qpAllowContinueOnError);
  1715. TSuspendFileOperationProgress Suspend(OperationProgress);
  1716. if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FileName)), &E,
  1717. qaOK | qaAbort, &Params, qtError) == qaAbort)
  1718. {
  1719. OperationProgress->SetCancel(csCancel);
  1720. }
  1721. FTerminal->OperationFinish(OperationProgress, Item, FileName, false, OnceDoneOperation);
  1722. if (!FTerminal->HandleException(&E))
  1723. {
  1724. throw;
  1725. }
  1726. }
  1727. catch (ESkipFile &E)
  1728. {
  1729. FTerminal->OperationFinish(OperationProgress, Item, FileName, false, OnceDoneOperation);
  1730. {
  1731. TSuspendFileOperationProgress Suspend(OperationProgress);
  1732. // If ESkipFile occurs, just log it and continue with next file
  1733. if (!FTerminal->HandleException(&E))
  1734. {
  1735. throw;
  1736. }
  1737. }
  1738. }
  1739. catch (...)
  1740. {
  1741. FTerminal->OperationFinish(OperationProgress, Item, FileName, false, OnceDoneOperation);
  1742. throw;
  1743. }
  1744. }
  1745. }
  1746. Failed = false;
  1747. }
  1748. __finally
  1749. {
  1750. // Tell remote side, that we're done.
  1751. if (FTerminal->Active)
  1752. {
  1753. try
  1754. {
  1755. if (!GotLastLine)
  1756. {
  1757. if (CopyBatchStarted && !FScpFatalError)
  1758. {
  1759. // What about case, remote side sends fatal error ???
  1760. // (Not sure, if it causes remote side to terminate scp)
  1761. FSecureShell->SendLine(L"E");
  1762. SCPResponse();
  1763. }
  1764. /* TODO 1 : Show stderror to user? */
  1765. FSecureShell->ClearStdError();
  1766. ReadCommandOutput(coExpectNoOutput | coWaitForLastLine | coOnlyReturnCode |
  1767. (Failed ? 0 : coRaiseExcept));
  1768. }
  1769. }
  1770. catch (Exception &E)
  1771. {
  1772. // Only log error message (it should always succeed, but
  1773. // some pending error maybe in queue) }
  1774. FTerminal->Log->AddException(&E);
  1775. }
  1776. }
  1777. }
  1778. }
  1779. //---------------------------------------------------------------------------
  1780. void __fastcall TSCPFileSystem::Source(
  1781. TLocalFileHandle & /*Handle*/, const UnicodeString & /*TargetDir*/, UnicodeString & /*DestFileName*/,
  1782. const TCopyParamType * /*CopyParam*/, int /*Params*/,
  1783. TFileOperationProgressType * /*OperationProgress*/, unsigned int /*Flags*/,
  1784. TUploadSessionAction & /*Action*/, bool & /*ChildError*/)
  1785. {
  1786. DebugFail();
  1787. }
  1788. //---------------------------------------------------------------------------
  1789. void __fastcall TSCPFileSystem::SCPSource(const UnicodeString FileName,
  1790. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  1791. TFileOperationProgressType * OperationProgress, int Level)
  1792. {
  1793. UnicodeString DestFileName =
  1794. FTerminal->ChangeFileName(
  1795. CopyParam, ExtractFileName(FileName), osLocal, Level == 0);
  1796. FTerminal->LogEvent(FORMAT(L"File: \"%s\"", (FileName)));
  1797. OperationProgress->SetFile(FileName, false);
  1798. if (!FTerminal->AllowLocalFileTransfer(FileName, NULL, CopyParam, OperationProgress))
  1799. {
  1800. throw ESkipFile();
  1801. }
  1802. TLocalFileHandle Handle;
  1803. FTerminal->OpenLocalFile(FileName, GENERIC_READ, Handle);
  1804. OperationProgress->SetFileInProgress();
  1805. if (Handle.Directory)
  1806. {
  1807. SCPDirectorySource(FileName, TargetDir, CopyParam, Params, OperationProgress, Level);
  1808. }
  1809. else
  1810. {
  1811. UnicodeString AbsoluteFileName = FTerminal->AbsolutePath(TargetDir + DestFileName, false);
  1812. DebugAssert(Handle.Handle);
  1813. std::unique_ptr<TStream> Stream(new TSafeHandleStream((THandle)Handle.Handle));
  1814. // File is regular file (not directory)
  1815. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory started.", (FileName)));
  1816. OperationProgress->SetLocalSize(Handle.Size);
  1817. // Suppose same data size to transfer as to read
  1818. // (not true with ASCII transfer)
  1819. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1820. OperationProgress->SetTransferringFile(false);
  1821. if (Handle.Size > 512*1024*1024)
  1822. {
  1823. OperationProgress->SetAsciiTransfer(false);
  1824. 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))));
  1825. }
  1826. else
  1827. {
  1828. FTerminal->SelectSourceTransferMode(Handle, CopyParam);
  1829. }
  1830. TUploadSessionAction Action(FTerminal->ActionLog);
  1831. Action.FileName(ExpandUNCFileName(FileName));
  1832. Action.Destination(AbsoluteFileName);
  1833. TRights Rights = CopyParam->RemoteFileRights(Handle.Attrs);
  1834. try
  1835. {
  1836. // During ASCII transfer we will load whole file to this buffer
  1837. // than convert EOL and send it at once, because before converting EOL
  1838. // we can't know its size
  1839. TFileBuffer AsciiBuf;
  1840. bool ConvertToken = false;
  1841. do
  1842. {
  1843. // Buffer for one block of data
  1844. TFileBuffer BlockBuf;
  1845. // This is crucial, if it fails during file transfer, it's fatal error
  1846. FILE_OPERATION_LOOP_BEGIN
  1847. {
  1848. BlockBuf.LoadStream(Stream.get(), OperationProgress->LocalBlockSize(), true);
  1849. }
  1850. FILE_OPERATION_LOOP_END_EX(
  1851. FMTLOAD(READ_ERROR, (FileName)),
  1852. FLAGMASK(!OperationProgress->TransferringFile, folAllowSkip));
  1853. OperationProgress->AddLocallyUsed(BlockBuf.Size);
  1854. // We do ASCII transfer: convert EOL of current block
  1855. // (we don't convert whole buffer, cause it would produce
  1856. // huge memory-transfers while inserting/deleting EOL characters)
  1857. // Than we add current block to file buffer
  1858. if (OperationProgress->AsciiTransfer)
  1859. {
  1860. int ConvertParams =
  1861. FLAGMASK(CopyParam->RemoveCtrlZ, cpRemoveCtrlZ) |
  1862. FLAGMASK(CopyParam->RemoveBOM, cpRemoveBOM);
  1863. BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
  1864. FTerminal->SessionData->EOLType,
  1865. ConvertParams, ConvertToken);
  1866. BlockBuf.Memory->Seek(0, soFromBeginning);
  1867. AsciiBuf.ReadStream(BlockBuf.Memory, BlockBuf.Size, true);
  1868. // We don't need it any more
  1869. BlockBuf.Memory->Clear();
  1870. // Calculate total size to sent (assume that ratio between
  1871. // size of source and size of EOL-transformed data would remain same)
  1872. // First check if file contains anything (div by zero!)
  1873. if (OperationProgress->LocallyUsed)
  1874. {
  1875. __int64 X = OperationProgress->LocalSize;
  1876. X *= AsciiBuf.Size;
  1877. X /= OperationProgress->LocallyUsed;
  1878. OperationProgress->ChangeTransferSize(X);
  1879. }
  1880. else
  1881. {
  1882. OperationProgress->ChangeTransferSize(0);
  1883. }
  1884. }
  1885. // We send file information on first pass during BINARY transfer
  1886. // and on last pass during ASCII transfer
  1887. // BINARY: We succeeded reading first buffer from file, hopefully
  1888. // we will be able to read whole, so we send file info to remote side
  1889. // This is done, because when reading fails we can't interrupt sending
  1890. // (don't know how to tell other side that it failed)
  1891. if (!OperationProgress->TransferringFile &&
  1892. (!OperationProgress->AsciiTransfer || OperationProgress->IsLocallyDone()))
  1893. {
  1894. UnicodeString Buf;
  1895. if (CopyParam->PreserveTime)
  1896. {
  1897. // Send last file access and modification time
  1898. // TVarRec don't understand 'unsigned int' -> we use sprintf()
  1899. Buf.sprintf(L"T%lu 0 %lu 0", static_cast<unsigned long>(Handle.MTime),
  1900. static_cast<unsigned long>(Handle.ATime));
  1901. FSecureShell->SendLine(Buf);
  1902. SCPResponse();
  1903. }
  1904. // Send file modes (rights), filesize and file name
  1905. // TVarRec don't understand 'unsigned int' -> we use sprintf()
  1906. Buf.sprintf(L"C%s %Ld %s",
  1907. Rights.Octal.data(),
  1908. (OperationProgress->AsciiTransfer ? (__int64)AsciiBuf.Size :
  1909. OperationProgress->LocalSize),
  1910. DestFileName.data());
  1911. FSecureShell->SendLine(Buf);
  1912. SCPResponse();
  1913. // Indicate we started transferring file, we need to finish it
  1914. // If not, it's fatal error
  1915. OperationProgress->SetTransferringFile(true);
  1916. // If we're doing ASCII transfer, this is last pass
  1917. // so we send whole file
  1918. /* TODO : We can't send file above 32bit size in ASCII mode! */
  1919. if (OperationProgress->AsciiTransfer)
  1920. {
  1921. FTerminal->LogEvent(FORMAT(L"Sending ASCII data (%u bytes)",
  1922. (AsciiBuf.Size)));
  1923. // Should be equal, just in case it's rounded (see above)
  1924. OperationProgress->ChangeTransferSize(AsciiBuf.Size);
  1925. while (!OperationProgress->IsTransferDoneChecked())
  1926. {
  1927. unsigned long BlockSize = OperationProgress->TransferBlockSize();
  1928. FSecureShell->Send(
  1929. reinterpret_cast<unsigned char *>(AsciiBuf.Data + (unsigned int)OperationProgress->TransferredSize),
  1930. BlockSize);
  1931. OperationProgress->AddTransferred(BlockSize);
  1932. if (OperationProgress->Cancel == csCancelTransfer)
  1933. {
  1934. throw Exception(MainInstructions(LoadStr(USER_TERMINATED)));
  1935. }
  1936. }
  1937. }
  1938. }
  1939. // At end of BINARY transfer pass, send current block
  1940. if (!OperationProgress->AsciiTransfer)
  1941. {
  1942. if (!OperationProgress->TransferredSize)
  1943. {
  1944. FTerminal->LogEvent(FORMAT(L"Sending BINARY data (first block, %u bytes)",
  1945. (BlockBuf.Size)));
  1946. }
  1947. else if (FTerminal->Configuration->ActualLogProtocol >= 1)
  1948. {
  1949. FTerminal->LogEvent(FORMAT(L"Sending BINARY data (%u bytes)",
  1950. (BlockBuf.Size)));
  1951. }
  1952. FSecureShell->Send(reinterpret_cast<const unsigned char *>(BlockBuf.Data), BlockBuf.Size);
  1953. OperationProgress->AddTransferred(BlockBuf.Size);
  1954. }
  1955. if ((OperationProgress->Cancel == csCancelTransfer) ||
  1956. (OperationProgress->Cancel == csCancel && !OperationProgress->TransferringFile))
  1957. {
  1958. throw Exception(MainInstructions(LoadStr(USER_TERMINATED)));
  1959. }
  1960. }
  1961. while (!OperationProgress->IsLocallyDone() || !OperationProgress->IsTransferDoneChecked());
  1962. FSecureShell->SendNull();
  1963. try
  1964. {
  1965. SCPResponse();
  1966. // If one of two following exceptions occurs, it means, that remote
  1967. // side already know, that file transfer finished, even if it failed
  1968. // so we don't have to throw EFatal
  1969. }
  1970. catch (EScp &E)
  1971. {
  1972. // SCP protocol fatal error
  1973. OperationProgress->SetTransferringFile(false);
  1974. throw;
  1975. }
  1976. catch (EScpFileSkipped &E)
  1977. {
  1978. // SCP protocol non-fatal error
  1979. OperationProgress->SetTransferringFile(false);
  1980. throw;
  1981. }
  1982. // We succeeded transferring file, from now we can handle exceptions
  1983. // normally -> no fatal error
  1984. OperationProgress->SetTransferringFile(false);
  1985. }
  1986. catch (Exception &E)
  1987. {
  1988. // EScpFileSkipped is derived from ESkipFile,
  1989. // but is does not indicate file skipped by user here
  1990. if (dynamic_cast<EScpFileSkipped *>(&E) != NULL)
  1991. {
  1992. Action.Rollback(&E);
  1993. }
  1994. else
  1995. {
  1996. FTerminal->RollbackAction(Action, OperationProgress, &E);
  1997. }
  1998. // Every exception during file transfer is fatal
  1999. if (OperationProgress->TransferringFile)
  2000. {
  2001. FTerminal->FatalError(&E, FMTLOAD(COPY_FATAL, (FileName)));
  2002. }
  2003. else
  2004. {
  2005. throw;
  2006. }
  2007. }
  2008. // With SCP we are not able to distinguish reason for failure
  2009. // (upload itself, touch or chmod).
  2010. // So we always report error with upload action and
  2011. // log touch and chmod actions only if upload succeeds.
  2012. if (CopyParam->PreserveTime)
  2013. {
  2014. TTouchSessionAction(FTerminal->ActionLog, AbsoluteFileName, Handle.Modification);
  2015. }
  2016. if (CopyParam->PreserveRights)
  2017. {
  2018. TChmodSessionAction(FTerminal->ActionLog, AbsoluteFileName,
  2019. Rights);
  2020. }
  2021. FTerminal->LogFileDone(OperationProgress, AbsoluteFileName, Action);
  2022. // Stream is disposed here
  2023. }
  2024. Handle.Release();
  2025. FTerminal->UpdateSource(Handle, CopyParam, Params);
  2026. FTerminal->LogEvent(FORMAT(L"Copying \"%s\" to remote directory finished.", (FileName)));
  2027. }
  2028. //---------------------------------------------------------------------------
  2029. void __fastcall TSCPFileSystem::SCPDirectorySource(const UnicodeString DirectoryName,
  2030. const UnicodeString TargetDir, const TCopyParamType * CopyParam, int Params,
  2031. TFileOperationProgressType * OperationProgress, int Level)
  2032. {
  2033. int Attrs;
  2034. FTerminal->LogEvent(FORMAT(L"Entering directory \"%s\".", (DirectoryName)));
  2035. OperationProgress->SetFile(DirectoryName);
  2036. UnicodeString DestFileName =
  2037. FTerminal->ChangeFileName(
  2038. CopyParam, ExtractFileName(DirectoryName), osLocal, Level == 0);
  2039. // Get directory attributes
  2040. FILE_OPERATION_LOOP_BEGIN
  2041. {
  2042. Attrs = FileGetAttrFix(ApiPath(DirectoryName));
  2043. if (Attrs < 0) RaiseLastOSError();
  2044. }
  2045. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_GET_ATTRS, (DirectoryName)));
  2046. UnicodeString TargetDirFull = UnixIncludeTrailingBackslash(TargetDir + DestFileName);
  2047. UnicodeString Buf;
  2048. /* TODO 1: maybe send filetime */
  2049. // Send directory modes (rights), filesize and file name
  2050. Buf = FORMAT(L"D%s 0 %s",
  2051. (CopyParam->RemoteFileRights(Attrs).Octal, DestFileName));
  2052. FSecureShell->SendLine(Buf);
  2053. SCPResponse();
  2054. try
  2055. {
  2056. TSearchRecOwned SearchRec;
  2057. bool FindOK = FTerminal->LocalFindFirstLoop(IncludeTrailingBackslash(DirectoryName) + L"*.*", SearchRec);
  2058. while (FindOK && !OperationProgress->Cancel)
  2059. {
  2060. UnicodeString FileName = SearchRec.GetFilePath();
  2061. try
  2062. {
  2063. if (SearchRec.IsRealFile())
  2064. {
  2065. SCPSource(FileName, TargetDirFull, CopyParam, Params, OperationProgress, Level + 1);
  2066. }
  2067. }
  2068. // Previously we caught ESkipFile, making error being displayed
  2069. // even when file was excluded by mask. Now the ESkipFile is special
  2070. // case without error message.
  2071. catch (EScpFileSkipped &E)
  2072. {
  2073. TQueryParams Params(qpAllowContinueOnError);
  2074. TSuspendFileOperationProgress Suspend(OperationProgress);
  2075. if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FileName)), &E,
  2076. qaOK | qaAbort, &Params, qtError) == qaAbort)
  2077. {
  2078. OperationProgress->SetCancel(csCancel);
  2079. }
  2080. if (!FTerminal->HandleException(&E))
  2081. {
  2082. throw;
  2083. }
  2084. }
  2085. catch (ESkipFile &E)
  2086. {
  2087. // If ESkipFile occurs, just log it and continue with next file
  2088. TSuspendFileOperationProgress Suspend(OperationProgress);
  2089. if (!FTerminal->HandleException(&E))
  2090. {
  2091. throw;
  2092. }
  2093. }
  2094. FindOK = FTerminal->LocalFindNextLoop(SearchRec);
  2095. }
  2096. SearchRec.Close();
  2097. /* TODO : Delete also read-only directories. */
  2098. /* TODO : Show error message on failure. */
  2099. if (!OperationProgress->Cancel)
  2100. {
  2101. if (FLAGSET(Params, cpDelete))
  2102. {
  2103. RemoveDir(ApiPath(DirectoryName));
  2104. }
  2105. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  2106. {
  2107. FILE_OPERATION_LOOP_BEGIN
  2108. {
  2109. THROWOSIFFALSE(FileSetAttr(ApiPath(DirectoryName), Attrs & ~faArchive) == 0);
  2110. }
  2111. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DirectoryName)));
  2112. }
  2113. }
  2114. }
  2115. __finally
  2116. {
  2117. if (FTerminal->Active)
  2118. {
  2119. // Tell remote side, that we're done.
  2120. FTerminal->LogEvent(FORMAT(L"Leaving directory \"%s\".", (DirectoryName)));
  2121. FSecureShell->SendLine(L"E");
  2122. SCPResponse();
  2123. }
  2124. }
  2125. }
  2126. //---------------------------------------------------------------------------
  2127. void __fastcall TSCPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  2128. const UnicodeString TargetDir, const TCopyParamType * CopyParam,
  2129. int Params, TFileOperationProgressType * OperationProgress,
  2130. TOnceDoneOperation & OnceDoneOperation)
  2131. {
  2132. bool CloseSCP = False;
  2133. Params &= ~(cpAppend | cpResume);
  2134. UnicodeString Options = L"";
  2135. if (CopyParam->PreserveRights || CopyParam->PreserveTime) Options = L"-p";
  2136. if (FTerminal->SessionData->Scp1Compatibility) Options += L" -1";
  2137. FTerminal->LogEvent(FORMAT(L"Copying %d files/directories to local directory "
  2138. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  2139. FTerminal->LogEvent(0, CopyParam->LogStr);
  2140. try
  2141. {
  2142. for (int IFile = 0; (IFile < FilesToCopy->Count) &&
  2143. !OperationProgress->Cancel; IFile++)
  2144. {
  2145. UnicodeString FileName = FilesToCopy->Strings[IFile];
  2146. TRemoteFile * File = (TRemoteFile *)FilesToCopy->Objects[IFile];
  2147. DebugAssert(File);
  2148. try
  2149. {
  2150. bool Success = true; // Have to be set to True (see ::SCPSink)
  2151. SendCommand(FCommandSet->FullCommand(fsCopyToLocal,
  2152. ARRAYOFCONST((Options, DelimitStr(FileName)))));
  2153. SkipFirstLine();
  2154. // Filename is used for error messaging and excluding files only
  2155. // Send in full path to allow path-based excluding
  2156. UnicodeString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  2157. SCPSink(TargetDir, FullFileName, UnixExtractFilePath(FullFileName),
  2158. CopyParam, Success, OperationProgress, Params, 0);
  2159. // operation succeeded (no exception), so it's ok that
  2160. // remote side closed SCP, but we continue with next file
  2161. if (OperationProgress->Cancel == csRemoteAbort)
  2162. {
  2163. OperationProgress->SetCancel(csContinue);
  2164. }
  2165. // Move operation -> delete file/directory afterwards
  2166. // but only if copying succeeded
  2167. if ((Params & cpDelete) && Success && !OperationProgress->Cancel)
  2168. {
  2169. try
  2170. {
  2171. FTerminal->ExceptionOnFail = true;
  2172. try
  2173. {
  2174. FILE_OPERATION_LOOP_BEGIN
  2175. {
  2176. // pass full file name in FileName, in case we are not moving
  2177. // from current directory
  2178. FTerminal->DeleteFile(FileName, File);
  2179. }
  2180. FILE_OPERATION_LOOP_END(FMTLOAD(DELETE_FILE_ERROR, (FileName)));
  2181. }
  2182. __finally
  2183. {
  2184. FTerminal->ExceptionOnFail = false;
  2185. }
  2186. }
  2187. catch (EFatal &E)
  2188. {
  2189. throw;
  2190. }
  2191. catch (...)
  2192. {
  2193. // If user selects skip (or abort), nothing special actually occurs
  2194. // we just run DoFinished with Success = False, so file won't
  2195. // be deselected in panel (depends on assigned event handler)
  2196. // On csCancel we would later try to close remote SCP, but it
  2197. // is closed already
  2198. if (OperationProgress->Cancel == csCancel)
  2199. {
  2200. OperationProgress->SetCancel(csRemoteAbort);
  2201. }
  2202. Success = false;
  2203. }
  2204. }
  2205. FTerminal->OperationFinish(
  2206. OperationProgress, File, FileName, (!OperationProgress->Cancel && Success), OnceDoneOperation);
  2207. }
  2208. catch (...)
  2209. {
  2210. FTerminal->OperationFinish(OperationProgress, File, FileName, false, OnceDoneOperation);
  2211. CloseSCP = (OperationProgress->Cancel != csRemoteAbort);
  2212. throw;
  2213. }
  2214. }
  2215. }
  2216. __finally
  2217. {
  2218. // In case that copying doesn't cause fatal error (ie. connection is
  2219. // still active) but wasn't successful (exception or user termination)
  2220. // we need to ensure, that SCP on remote side is closed
  2221. if (FTerminal->Active && (CloseSCP ||
  2222. (OperationProgress->Cancel == csCancel) ||
  2223. (OperationProgress->Cancel == csCancelTransfer)))
  2224. {
  2225. bool LastLineRead;
  2226. // If we get LastLine, it means that remote side 'scp' is already
  2227. // terminated, so we need not to terminate it. There is also
  2228. // possibility that remote side waits for confirmation, so it will hang.
  2229. // This should not happen (hope)
  2230. UnicodeString Line = FSecureShell->ReceiveLine();
  2231. LastLineRead = IsLastLine(Line);
  2232. if (!LastLineRead)
  2233. {
  2234. SCPSendError((OperationProgress->Cancel ? L"Terminated by user." : L"Exception"), true);
  2235. }
  2236. // Just in case, remote side already sent some more data (it's probable)
  2237. // but we don't want to raise exception (user asked to terminate, it's not error)
  2238. int ECParams = coOnlyReturnCode;
  2239. if (!LastLineRead) ECParams |= coWaitForLastLine;
  2240. ReadCommandOutput(ECParams);
  2241. }
  2242. }
  2243. }
  2244. //---------------------------------------------------------------------------
  2245. void __fastcall TSCPFileSystem::Sink(
  2246. const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/,
  2247. const UnicodeString & /*TargetDir*/, UnicodeString & /*DestFileName*/, int /*Attrs*/,
  2248. const TCopyParamType * /*CopyParam*/, int /*Params*/, TFileOperationProgressType * /*OperationProgress*/,
  2249. unsigned int /*Flags*/, TDownloadSessionAction & /*Action*/)
  2250. {
  2251. DebugFail();
  2252. }
  2253. //---------------------------------------------------------------------------
  2254. void __fastcall TSCPFileSystem::SCPError(const UnicodeString Message, bool Fatal)
  2255. {
  2256. SCPSendError(Message, Fatal);
  2257. throw EScpFileSkipped(NULL, Message);
  2258. }
  2259. //---------------------------------------------------------------------------
  2260. void __fastcall TSCPFileSystem::SCPSendError(const UnicodeString Message, bool Fatal)
  2261. {
  2262. unsigned char ErrorLevel = (char)(Fatal ? 2 : 1);
  2263. FTerminal->LogEvent(FORMAT(L"Sending SCP error (%d) to remote side:",
  2264. ((int)ErrorLevel)));
  2265. FSecureShell->Send(&ErrorLevel, 1);
  2266. // We don't send exact error message, because some unspecified
  2267. // characters can terminate remote scp
  2268. FSecureShell->SendLine(L"scp: error");
  2269. }
  2270. //---------------------------------------------------------------------------
  2271. void __fastcall TSCPFileSystem::SCPSink(const UnicodeString TargetDir,
  2272. const UnicodeString FileName, const UnicodeString SourceDir,
  2273. const TCopyParamType * CopyParam, bool & Success,
  2274. TFileOperationProgressType * OperationProgress, int Params,
  2275. int Level)
  2276. {
  2277. struct
  2278. {
  2279. int SetTime;
  2280. TDateTime Modification;
  2281. TRights RemoteRights;
  2282. int Attrs;
  2283. bool Exists;
  2284. } FileData;
  2285. bool SkipConfirmed = false;
  2286. bool Initialized = (Level > 0);
  2287. FileData.SetTime = 0;
  2288. FSecureShell->SendNull();
  2289. while (!OperationProgress->Cancel)
  2290. {
  2291. // See (switch ... case 'T':)
  2292. if (FileData.SetTime) FileData.SetTime--;
  2293. // In case of error occurred before control record arrived.
  2294. // We can finally use full path here, as we get current path in FileName param
  2295. // (we used to set the file into OperationProgress->FileName, but it collided
  2296. // with progress outputting, particularly for scripting)
  2297. UnicodeString FullFileName = FileName;
  2298. try
  2299. {
  2300. // Receive control record
  2301. UnicodeString Line = FSecureShell->ReceiveLine();
  2302. if (Line.Length() == 0) FTerminal->FatalError(NULL, LoadStr(SCP_EMPTY_LINE));
  2303. if (IsLastLine(Line))
  2304. {
  2305. // Remote side finished copying, so remote SCP was closed
  2306. // and we don't need to terminate it manually, see CopyToLocal()
  2307. OperationProgress->SetCancel(csRemoteAbort);
  2308. /* TODO 1 : Show stderror to user? */
  2309. FSecureShell->ClearStdError();
  2310. try
  2311. {
  2312. // coIgnoreWarnings should allow batch transfer to continue when
  2313. // download of one the files fails (user denies overwriting
  2314. // of target local file, no read permissions...)
  2315. ReadCommandOutput(coExpectNoOutput | coRaiseExcept |
  2316. coOnlyReturnCode | coIgnoreWarnings);
  2317. if (!Initialized)
  2318. {
  2319. throw Exception(L"");
  2320. }
  2321. }
  2322. catch(Exception & E)
  2323. {
  2324. if (!Initialized && FTerminal->Active)
  2325. {
  2326. FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
  2327. }
  2328. else
  2329. {
  2330. throw;
  2331. }
  2332. }
  2333. return;
  2334. }
  2335. else
  2336. {
  2337. Initialized = true;
  2338. // First character distinguish type of control record
  2339. wchar_t Ctrl = Line[1];
  2340. Line.Delete(1, 1);
  2341. switch (Ctrl) {
  2342. case 1:
  2343. // Error (already logged by ReceiveLine())
  2344. throw EScpFileSkipped(NULL, FMTLOAD(REMOTE_ERROR, (Line)));
  2345. case 2:
  2346. // Fatal error, terminate copying
  2347. FTerminal->TerminalError(Line);
  2348. return; // Unreachable
  2349. case L'E': // Exit
  2350. FSecureShell->SendNull();
  2351. return;
  2352. case L'T':
  2353. unsigned long MTime, ATime;
  2354. if (swscanf(Line.c_str(), L"%ld %*d %ld %*d", &MTime, &ATime) == 2)
  2355. {
  2356. FileData.Modification = UnixToDateTime(MTime, FTerminal->SessionData->DSTMode);
  2357. FSecureShell->SendNull();
  2358. // File time is only valid until next pass
  2359. FileData.SetTime = 2;
  2360. continue;
  2361. }
  2362. else
  2363. {
  2364. SCPError(LoadStr(SCP_ILLEGAL_TIME_FORMAT), False);
  2365. }
  2366. case L'C':
  2367. case L'D':
  2368. break; // continue pass switch{}
  2369. default:
  2370. FTerminal->FatalError(NULL, FMTLOAD(SCP_INVALID_CONTROL_RECORD, (Ctrl, Line)));
  2371. }
  2372. TFileMasks::TParams MaskParams;
  2373. MaskParams.Modification = FileData.Modification;
  2374. // We reach this point only if control record was 'C' or 'D'
  2375. try
  2376. {
  2377. FileData.RemoteRights.Octal = CutToChar(Line, L' ', True);
  2378. // do not trim leading spaces of the filename
  2379. __int64 TSize = StrToInt64(CutToChar(Line, L' ', False).TrimRight());
  2380. MaskParams.Size = TSize;
  2381. // Security fix: ensure the file ends up where we asked for it.
  2382. // (accept only filename, not path)
  2383. UnicodeString OnlyFileName = UnixExtractFileName(Line);
  2384. if (Line != OnlyFileName)
  2385. {
  2386. FTerminal->LogEvent(FORMAT(L"Warning: Remote host set a compound pathname '%s'", (Line)));
  2387. }
  2388. if ((Level == 0) && (OnlyFileName != UnixExtractFileName(FileName)))
  2389. {
  2390. SCPError(LoadStr(UNREQUESTED_FILE), False);
  2391. }
  2392. FullFileName = SourceDir + OnlyFileName;
  2393. OperationProgress->SetFile(FullFileName);
  2394. OperationProgress->SetTransferSize(TSize);
  2395. }
  2396. catch (Exception &E)
  2397. {
  2398. {
  2399. TSuspendFileOperationProgress Suspend(OperationProgress);
  2400. FTerminal->Log->AddException(&E);
  2401. }
  2402. SCPError(LoadStr(SCP_ILLEGAL_FILE_DESCRIPTOR), false);
  2403. }
  2404. // last possibility to cancel transfer before it starts
  2405. if (OperationProgress->Cancel)
  2406. {
  2407. throw ESkipFile(NULL, MainInstructions(LoadStr(USER_TERMINATED)));
  2408. }
  2409. bool Dir = (Ctrl == L'D');
  2410. UnicodeString BaseFileName = FTerminal->GetBaseFileName(FullFileName);
  2411. if (!CopyParam->AllowTransfer(BaseFileName, osRemote, Dir, MaskParams, IsUnixHiddenFile(BaseFileName)))
  2412. {
  2413. FTerminal->LogEvent(FORMAT(L"File \"%s\" excluded from transfer",
  2414. (FullFileName)));
  2415. SkipConfirmed = true;
  2416. SCPError(L"", false);
  2417. }
  2418. if (CopyParam->SkipTransfer(FullFileName, Dir))
  2419. {
  2420. SkipConfirmed = true;
  2421. SCPError(L"", false);
  2422. OperationProgress->AddSkippedFileSize(MaskParams.Size);
  2423. }
  2424. FTerminal->LogFileDetails(FileName, FileData.Modification, MaskParams.Size);
  2425. UnicodeString DestFileNameOnly =
  2426. FTerminal->ChangeFileName(
  2427. CopyParam, OperationProgress->FileName, osRemote,
  2428. Level == 0);
  2429. UnicodeString DestFileName =
  2430. IncludeTrailingBackslash(TargetDir) + DestFileNameOnly;
  2431. FileData.Attrs = FileGetAttrFix(ApiPath(DestFileName));
  2432. // If getting attrs fails, we suppose, that file/folder doesn't exists
  2433. FileData.Exists = (FileData.Attrs != -1);
  2434. if (Dir)
  2435. {
  2436. if (FileData.Exists && !(FileData.Attrs & faDirectory))
  2437. {
  2438. SCPError(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFileName)), false);
  2439. }
  2440. if (!FileData.Exists)
  2441. {
  2442. FILE_OPERATION_LOOP_BEGIN
  2443. {
  2444. THROWOSIFFALSE(ForceDirectories(ApiPath(DestFileName)));
  2445. }
  2446. FILE_OPERATION_LOOP_END(FMTLOAD(CREATE_DIR_ERROR, (DestFileName)));
  2447. /* SCP: can we set the timestamp for directories ? */
  2448. }
  2449. UnicodeString FullFileName = SourceDir + OperationProgress->FileName;
  2450. SCPSink(DestFileName, FullFileName, UnixIncludeTrailingBackslash(FullFileName),
  2451. CopyParam, Success, OperationProgress, Params, Level + 1);
  2452. continue;
  2453. }
  2454. else if (Ctrl == L'C')
  2455. {
  2456. TDownloadSessionAction Action(FTerminal->ActionLog);
  2457. Action.FileName(FTerminal->AbsolutePath(FullFileName, true));
  2458. try
  2459. {
  2460. HANDLE File = NULL;
  2461. TStream * FileStream = NULL;
  2462. /* TODO 1 : Turn off read-only attr */
  2463. try
  2464. {
  2465. try
  2466. {
  2467. if (FileExists(ApiPath(DestFileName)))
  2468. {
  2469. __int64 MTime;
  2470. TOverwriteFileParams FileParams;
  2471. FileParams.SourceSize = OperationProgress->TransferSize;
  2472. FileParams.SourceTimestamp = FileData.Modification;
  2473. FTerminal->OpenLocalFile(DestFileName, GENERIC_READ,
  2474. NULL, NULL, NULL, &MTime, NULL,
  2475. &FileParams.DestSize);
  2476. FileParams.DestTimestamp = UnixToDateTime(MTime,
  2477. FTerminal->SessionData->DSTMode);
  2478. unsigned int Answer =
  2479. ConfirmOverwrite(OperationProgress->FileName, DestFileNameOnly, osLocal,
  2480. &FileParams, CopyParam, Params, OperationProgress);
  2481. switch (Answer)
  2482. {
  2483. case qaCancel:
  2484. OperationProgress->SetCancel(csCancel); // continue on next case
  2485. case qaNo:
  2486. SkipConfirmed = true;
  2487. EXCEPTION;
  2488. }
  2489. }
  2490. Action.Destination(DestFileName);
  2491. if (!FTerminal->CreateLocalFile(DestFileName, OperationProgress,
  2492. &File, FLAGSET(Params, cpNoConfirmation)))
  2493. {
  2494. SkipConfirmed = true;
  2495. EXCEPTION;
  2496. }
  2497. FileStream = new TSafeHandleStream((THandle)File);
  2498. }
  2499. catch (Exception &E)
  2500. {
  2501. // In this step we can still cancel transfer, so we do it
  2502. SCPError(E.Message, false);
  2503. throw;
  2504. }
  2505. // We succeeded, so we confirm transfer to remote side
  2506. FSecureShell->SendNull();
  2507. // From now we need to finish file transfer, if not it's fatal error
  2508. OperationProgress->SetTransferringFile(true);
  2509. // Suppose same data size to transfer as to write
  2510. // (not true with ASCII transfer)
  2511. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  2512. // Will we use ASCII of BINARY file transfer?
  2513. OperationProgress->SetAsciiTransfer(
  2514. CopyParam->UseAsciiTransfer(BaseFileName, osRemote, MaskParams));
  2515. FTerminal->LogEvent(
  2516. 0, UnicodeString((OperationProgress->AsciiTransfer ? L"Ascii" : L"Binary")) +
  2517. L" transfer mode selected.");
  2518. try
  2519. {
  2520. // Buffer for one block of data
  2521. TFileBuffer BlockBuf;
  2522. bool ConvertToken = false;
  2523. do
  2524. {
  2525. BlockBuf.Size = OperationProgress->TransferBlockSize();
  2526. BlockBuf.Reset();
  2527. FSecureShell->Receive(reinterpret_cast<unsigned char *>(BlockBuf.Data), BlockBuf.Size);
  2528. OperationProgress->AddTransferred(BlockBuf.Size);
  2529. if (OperationProgress->AsciiTransfer)
  2530. {
  2531. unsigned int PrevBlockSize = BlockBuf.Size;
  2532. BlockBuf.Convert(FTerminal->SessionData->EOLType,
  2533. FTerminal->Configuration->LocalEOLType, 0, ConvertToken);
  2534. OperationProgress->SetLocalSize(
  2535. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  2536. }
  2537. // This is crucial, if it fails during file transfer, it's fatal error
  2538. FILE_OPERATION_LOOP_BEGIN
  2539. {
  2540. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  2541. }
  2542. FILE_OPERATION_LOOP_END_EX(FMTLOAD(WRITE_ERROR, (DestFileName)), folNone);
  2543. OperationProgress->AddLocallyUsed(BlockBuf.Size);
  2544. if (OperationProgress->Cancel == csCancelTransfer)
  2545. {
  2546. throw Exception(MainInstructions(LoadStr(USER_TERMINATED)));
  2547. }
  2548. }
  2549. while (!OperationProgress->IsLocallyDone() || !OperationProgress->IsTransferDoneChecked());
  2550. }
  2551. catch (Exception &E)
  2552. {
  2553. // Every exception during file transfer is fatal
  2554. FTerminal->FatalError(&E,
  2555. FMTLOAD(COPY_FATAL, (OperationProgress->FileName)));
  2556. }
  2557. OperationProgress->SetTransferringFile(false);
  2558. try
  2559. {
  2560. SCPResponse();
  2561. // If one of following exception occurs, we still need
  2562. // to send confirmation to other side
  2563. }
  2564. catch (EScp &E)
  2565. {
  2566. FSecureShell->SendNull();
  2567. throw;
  2568. }
  2569. catch (EScpFileSkipped &E)
  2570. {
  2571. FSecureShell->SendNull();
  2572. throw;
  2573. }
  2574. FSecureShell->SendNull();
  2575. if (FileData.SetTime && CopyParam->PreserveTime)
  2576. {
  2577. FTerminal->UpdateTargetTime(File, FileData.Modification, FTerminal->SessionData->DSTMode);
  2578. }
  2579. }
  2580. __finally
  2581. {
  2582. if (File) CloseHandle(File);
  2583. if (FileStream) delete FileStream;
  2584. }
  2585. }
  2586. catch(Exception & E)
  2587. {
  2588. if (SkipConfirmed)
  2589. {
  2590. Action.Cancel();
  2591. }
  2592. else
  2593. {
  2594. FTerminal->RollbackAction(Action, OperationProgress, &E);
  2595. }
  2596. throw;
  2597. }
  2598. if (FileData.Attrs == -1) FileData.Attrs = faArchive;
  2599. int NewAttrs = CopyParam->LocalFileAttrs(FileData.RemoteRights);
  2600. if ((NewAttrs & FileData.Attrs) != NewAttrs)
  2601. {
  2602. FILE_OPERATION_LOOP_BEGIN
  2603. {
  2604. THROWOSIFFALSE(FileSetAttr(ApiPath(DestFileName), FileData.Attrs | NewAttrs) == 0);
  2605. }
  2606. FILE_OPERATION_LOOP_END(FMTLOAD(CANT_SET_ATTRS, (DestFileName)));
  2607. }
  2608. FTerminal->LogFileDone(OperationProgress, DestFileName, Action);
  2609. }
  2610. }
  2611. }
  2612. catch (EScpFileSkipped &E)
  2613. {
  2614. if (!SkipConfirmed)
  2615. {
  2616. TSuspendFileOperationProgress Suspend(OperationProgress);
  2617. TQueryParams Params(qpAllowContinueOnError);
  2618. if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FullFileName)),
  2619. &E, qaOK | qaAbort, &Params, qtError) == qaAbort)
  2620. {
  2621. OperationProgress->SetCancel(csCancel);
  2622. }
  2623. FTerminal->Log->AddException(&E);
  2624. }
  2625. // this was inside above condition, but then transfer was considered
  2626. // successful, even when for example user refused to overwrite file
  2627. Success = false;
  2628. }
  2629. catch (ESkipFile &E)
  2630. {
  2631. SCPSendError(E.Message, false);
  2632. Success = false;
  2633. if (!FTerminal->HandleException(&E)) throw;
  2634. }
  2635. }
  2636. }
  2637. //---------------------------------------------------------------------------
  2638. void __fastcall TSCPFileSystem::GetSupportedChecksumAlgs(TStrings * Algs)
  2639. {
  2640. FTerminal->GetShellChecksumAlgs(Algs);
  2641. }
  2642. //---------------------------------------------------------------------------
  2643. void __fastcall TSCPFileSystem::LockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  2644. {
  2645. DebugFail();
  2646. }
  2647. //---------------------------------------------------------------------------
  2648. void __fastcall TSCPFileSystem::UnlockFile(const UnicodeString & /*FileName*/, const TRemoteFile * /*File*/)
  2649. {
  2650. DebugFail();
  2651. }
  2652. //---------------------------------------------------------------------------
  2653. void __fastcall TSCPFileSystem::UpdateFromMain(TCustomFileSystem * /*MainFileSystem*/)
  2654. {
  2655. // noop
  2656. }
  2657. //---------------------------------------------------------------------------
  2658. void __fastcall TSCPFileSystem::ClearCaches()
  2659. {
  2660. // noop
  2661. }