ScpFileSystem.cpp 86 KB

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