ScpFileSystem.cpp 89 KB

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