ScpFileSystem.cpp 99 KB

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