ScpFileSystem.cpp 91 KB

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