ScpFileSystem.cpp 91 KB

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