ScpFileSystem.cpp 86 KB

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