ScpFileSystem.cpp 90 KB

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