ScpFileSystem.cpp 91 KB

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