ScpFileSystem.cpp 90 KB

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