ScpFileSystem.cpp 86 KB

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