ScpFileSystem.cpp 90 KB

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