ScpFileSystem.cpp 84 KB

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