ScpFileSystem.cpp 99 KB

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