ScpFileSystem.cpp 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434
  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)
  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. return false;
  432. default:
  433. assert(false);
  434. return false;
  435. }
  436. }
  437. //---------------------------------------------------------------------------
  438. AnsiString __fastcall TSCPFileSystem::DelimitStr(AnsiString Str)
  439. {
  440. if (!Str.IsEmpty())
  441. {
  442. Str = ::DelimitStr(Str, "\\`$\"");
  443. if (Str[1] == '-') Str = "./"+Str;
  444. }
  445. return Str;
  446. }
  447. //---------------------------------------------------------------------------
  448. void __fastcall TSCPFileSystem::EnsureLocation()
  449. {
  450. if (!FCachedDirectoryChange.IsEmpty())
  451. {
  452. FTerminal->LogEvent(FORMAT("Locating to cached directory \"%s\".",
  453. (FCachedDirectoryChange)));
  454. AnsiString Directory = FCachedDirectoryChange;
  455. FCachedDirectoryChange = "";
  456. try
  457. {
  458. ChangeDirectory(Directory);
  459. }
  460. catch(...)
  461. {
  462. // when location to cached directory fails, pretend again
  463. // location in cached directory
  464. // here used to be check (CurrentDirectory != Directory), but it is
  465. // false always (currentdirectory is already set to cached directory),
  466. // making the condition below useless. check remove.
  467. if (FTerminal->Active)
  468. {
  469. FCachedDirectoryChange = Directory;
  470. }
  471. throw;
  472. }
  473. }
  474. }
  475. //---------------------------------------------------------------------------
  476. void __fastcall TSCPFileSystem::SendCommand(const AnsiString Cmd)
  477. {
  478. EnsureLocation();
  479. AnsiString Line;
  480. FSecureShell->ClearStdError();
  481. FReturnCode = 0;
  482. FOutput->Clear();
  483. // We suppose, that 'Cmd' already contains command that ensures,
  484. // that 'LastLine' will be printed
  485. FSecureShell->SendLine(Cmd);
  486. FProcessingCommand = true;
  487. }
  488. //---------------------------------------------------------------------------
  489. bool __fastcall TSCPFileSystem::IsTotalListingLine(const AnsiString Line)
  490. {
  491. // On some hosts there is not "total" but "totalt". What's the reason??
  492. // see mail from "Jan Wiklund (SysOp)" <[email protected]>
  493. return !Line.SubString(1, 5).AnsiCompareIC("total");
  494. }
  495. //---------------------------------------------------------------------------
  496. bool __fastcall TSCPFileSystem::RemoveLastLine(AnsiString & Line,
  497. int & ReturnCode, AnsiString LastLine)
  498. {
  499. bool IsLastLine = false;
  500. if (LastLine.IsEmpty()) LastLine = LAST_LINE;
  501. // #55: fixed so, even when last line of command output does not
  502. // contain CR/LF, we can recognize last line
  503. int Pos = Line.Pos(LastLine);
  504. if (Pos)
  505. {
  506. // 2003-07-14: There must be nothing after return code number to
  507. // consider string as last line. This fixes bug with 'set' command
  508. // in console window
  509. AnsiString ReturnCodeStr = Line.SubString(Pos + LastLine.Length() + 1,
  510. Line.Length() - Pos + LastLine.Length());
  511. if (TryStrToInt(ReturnCodeStr, ReturnCode))
  512. {
  513. IsLastLine = true;
  514. Line.SetLength(Pos - 1);
  515. }
  516. }
  517. return IsLastLine;
  518. }
  519. //---------------------------------------------------------------------------
  520. bool __fastcall TSCPFileSystem::IsLastLine(AnsiString & Line)
  521. {
  522. bool Result = false;
  523. try
  524. {
  525. Result = RemoveLastLine(Line, FReturnCode, FCommandSet->LastLine);
  526. }
  527. catch (Exception &E)
  528. {
  529. FTerminal->TerminalError(&E, LoadStr(CANT_DETECT_RETURN_CODE));
  530. }
  531. return Result;
  532. }
  533. //---------------------------------------------------------------------------
  534. void __fastcall TSCPFileSystem::SkipFirstLine()
  535. {
  536. AnsiString Line = FSecureShell->ReceiveLine();
  537. if (Line != FCommandSet->FirstLine)
  538. {
  539. FTerminal->TerminalError(NULL, FMTLOAD(FIRST_LINE_EXPECTED, (Line)));
  540. }
  541. }
  542. //---------------------------------------------------------------------------
  543. void __fastcall TSCPFileSystem::ReadCommandOutput(int Params, const AnsiString * Cmd)
  544. {
  545. try
  546. {
  547. if (Params & coWaitForLastLine)
  548. {
  549. AnsiString Line;
  550. bool IsLast;
  551. unsigned int Total = 0;
  552. // #55: fixed so, even when last line of command output does not
  553. // contain CR/LF, we can recognize last line
  554. do
  555. {
  556. Line = FSecureShell->ReceiveLine();
  557. IsLast = IsLastLine(Line);
  558. if (!IsLast || !Line.IsEmpty())
  559. {
  560. FOutput->Add(Line);
  561. if (FLAGSET(Params, coReadProgress))
  562. {
  563. Total++;
  564. if (Total % 10 == 0)
  565. {
  566. bool Cancel; //dummy
  567. FTerminal->DoReadDirectoryProgress(Total, Cancel);
  568. }
  569. }
  570. }
  571. }
  572. while (!IsLast);
  573. }
  574. if (Params & coRaiseExcept)
  575. {
  576. AnsiString Message = FSecureShell->GetStdError();
  577. if ((Params & coExpectNoOutput) && FOutput->Count)
  578. {
  579. if (!Message.IsEmpty()) Message += "\n";
  580. Message += FOutput->Text;
  581. }
  582. while (!Message.IsEmpty() && (Message.LastDelimiter("\n\r") == Message.Length()))
  583. Message.SetLength(Message.Length() - 1);
  584. bool WrongReturnCode =
  585. (ReturnCode > 1) || (ReturnCode == 1 && !(Params & coIgnoreWarnings));
  586. if (Params & coOnlyReturnCode && WrongReturnCode)
  587. {
  588. FTerminal->TerminalError(FMTLOAD(COMMAND_FAILED_CODEONLY, (ReturnCode)));
  589. }
  590. else
  591. if (!(Params & coOnlyReturnCode) &&
  592. ((!Message.IsEmpty() && ((FOutput->Count == 0) || !(Params & coIgnoreWarnings))) ||
  593. WrongReturnCode))
  594. {
  595. assert(Cmd != NULL);
  596. FTerminal->TerminalError(FMTLOAD(COMMAND_FAILED, (*Cmd, ReturnCode, Message)));
  597. }
  598. }
  599. }
  600. __finally
  601. {
  602. FProcessingCommand = false;
  603. }
  604. }
  605. //---------------------------------------------------------------------------
  606. void __fastcall TSCPFileSystem::ExecCommand(const AnsiString & Cmd, int Params,
  607. const AnsiString & CmdString)
  608. {
  609. if (Params < 0) Params = ecDefault;
  610. if (FTerminal->UseBusyCursor)
  611. {
  612. Busy(true);
  613. }
  614. try
  615. {
  616. SendCommand(Cmd);
  617. int COParams = coWaitForLastLine;
  618. if (Params & ecRaiseExcept) COParams |= coRaiseExcept;
  619. if (Params & ecIgnoreWarnings) COParams |= coIgnoreWarnings;
  620. if (Params & ecReadProgress) COParams |= coReadProgress;
  621. ReadCommandOutput(COParams, &CmdString);
  622. }
  623. __finally
  624. {
  625. if (FTerminal->UseBusyCursor)
  626. {
  627. Busy(false);
  628. }
  629. }
  630. }
  631. //---------------------------------------------------------------------------
  632. void __fastcall TSCPFileSystem::ExecCommand(TFSCommand Cmd, const TVarRec * args,
  633. int size, int Params)
  634. {
  635. if (Params < 0) Params = ecDefault;
  636. AnsiString FullCommand = FCommandSet->FullCommand(Cmd, args, size);
  637. AnsiString Command = FCommandSet->Command(Cmd, args, size);
  638. ExecCommand(FullCommand, Params, Command);
  639. if (Params & ecRaiseExcept)
  640. {
  641. Integer MinL = FCommandSet->MinLines[Cmd];
  642. Integer MaxL = FCommandSet->MaxLines[Cmd];
  643. if (((MinL >= 0) && (MinL > FOutput->Count)) ||
  644. ((MaxL >= 0) && (MaxL > FOutput->Count)))
  645. {
  646. FTerminal->TerminalError(FmtLoadStr(INVALID_OUTPUT_ERROR,
  647. ARRAYOFCONST((FullCommand, Output->Text))));
  648. }
  649. }
  650. }
  651. //---------------------------------------------------------------------------
  652. AnsiString __fastcall TSCPFileSystem::GetCurrentDirectory()
  653. {
  654. return FCurrentDirectory;
  655. }
  656. //---------------------------------------------------------------------------
  657. void __fastcall TSCPFileSystem::DoStartup()
  658. {
  659. // SkipStartupMessage and DetectReturnVar must succeed,
  660. // otherwise session is to be closed.
  661. FTerminal->ExceptionOnFail = true;
  662. SkipStartupMessage();
  663. if (FTerminal->SessionData->DetectReturnVar) DetectReturnVar();
  664. FTerminal->ExceptionOnFail = false;
  665. #define COND_OPER(OPER) if (FTerminal->SessionData->OPER) OPER()
  666. COND_OPER(ClearAliases);
  667. COND_OPER(UnsetNationalVars);
  668. #undef COND_OPER
  669. }
  670. //---------------------------------------------------------------------------
  671. void __fastcall TSCPFileSystem::SkipStartupMessage()
  672. {
  673. try
  674. {
  675. FTerminal->LogEvent("Skipping host startup message (if any).");
  676. ExecCommand(fsNull, NULL, 0, 0);
  677. }
  678. catch (Exception & E)
  679. {
  680. FTerminal->CommandError(&E, LoadStr(SKIP_STARTUP_MESSAGE_ERROR));
  681. }
  682. }
  683. //---------------------------------------------------------------------------
  684. void __fastcall TSCPFileSystem::LookupUsersGroups()
  685. {
  686. ExecCommand(fsLookupUsersGroups);
  687. FTerminal->FUsers->Clear();
  688. FTerminal->FGroups->Clear();
  689. if (FOutput->Count > 0)
  690. {
  691. FTerminal->FGroups->BeginUpdate();
  692. try
  693. {
  694. AnsiString Groups = FOutput->Strings[0];
  695. while (!Groups.IsEmpty())
  696. {
  697. AnsiString NewGroup = CutToChar(Groups, ' ', False);
  698. FTerminal->FGroups->Add(NewGroup);
  699. }
  700. }
  701. __finally
  702. {
  703. FTerminal->FGroups->EndUpdate();
  704. }
  705. }
  706. }
  707. //---------------------------------------------------------------------------
  708. void __fastcall TSCPFileSystem::DetectReturnVar()
  709. {
  710. // This suppose that something was already executed (probably SkipStartupMessage())
  711. // or return code variable is already set on start up.
  712. try
  713. {
  714. // #60 17.10.01: "status" and "?" switched
  715. AnsiString ReturnVars[2] = { "status", "?" };
  716. AnsiString NewReturnVar = "";
  717. FTerminal->LogEvent("Detecting variable containing return code of last command.");
  718. for (int Index = 0; Index < 2; Index++)
  719. {
  720. bool Success = true;
  721. try
  722. {
  723. FTerminal->LogEvent(FORMAT("Trying \"$%s\".", (ReturnVars[Index])));
  724. ExecCommand(fsVarValue, ARRAYOFCONST((ReturnVars[Index])));
  725. if ((Output->Count != 1) || (StrToIntDef(Output->Strings[0], 256) > 255)) Abort();
  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 = 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)
  1034. {
  1035. USEDPARAM(File);
  1036. USEDPARAM(Params);
  1037. assert(FLAGCLEAR(Params, dfNoRecursive) || (File && File->IsSymLink));
  1038. ExecCommand(fsDeleteFile, ARRAYOFCONST((DelimitStr(FileName))));
  1039. }
  1040. //---------------------------------------------------------------------------
  1041. void __fastcall TSCPFileSystem::RenameFile(const AnsiString FileName,
  1042. const AnsiString NewName)
  1043. {
  1044. ExecCommand(fsRenameFile, ARRAYOFCONST((DelimitStr(FileName), DelimitStr(NewName))));
  1045. }
  1046. //---------------------------------------------------------------------------
  1047. void __fastcall TSCPFileSystem::CopyFile(const AnsiString FileName,
  1048. const AnsiString NewName)
  1049. {
  1050. ExecCommand(fsCopyFile, ARRAYOFCONST((DelimitStr(FileName), DelimitStr(NewName))));
  1051. }
  1052. //---------------------------------------------------------------------------
  1053. void __fastcall TSCPFileSystem::CreateDirectory(const AnsiString DirName,
  1054. const TRemoteProperties * Properties)
  1055. {
  1056. USEDPARAM(Properties);
  1057. ExecCommand(fsCreateDirectory, ARRAYOFCONST((DelimitStr(DirName))));
  1058. if (Properties != NULL)
  1059. {
  1060. ChangeFileProperties(DirName, NULL, Properties);
  1061. }
  1062. }
  1063. //---------------------------------------------------------------------------
  1064. void __fastcall TSCPFileSystem::CreateLink(const AnsiString FileName,
  1065. const AnsiString PointTo, bool Symbolic)
  1066. {
  1067. ExecCommand(fsCreateLink,
  1068. ARRAYOFCONST((Symbolic ? "-s" : "", DelimitStr(PointTo), DelimitStr(FileName))));
  1069. }
  1070. //---------------------------------------------------------------------------
  1071. void __fastcall TSCPFileSystem::ChangeFileProperties(const AnsiString FileName,
  1072. const TRemoteFile * File, const TRemoteProperties * Properties)
  1073. {
  1074. assert(Properties);
  1075. bool IsDirectory = File && File->IsDirectory;
  1076. bool Recursive = Properties->Recursive && IsDirectory;
  1077. AnsiString RecursiveStr = Recursive ? "-R" : "";
  1078. AnsiString DelimitedName = DelimitStr(FileName);
  1079. // change group before permissions as chgrp change permissions
  1080. if (Properties->Valid.Contains(vpGroup))
  1081. {
  1082. ExecCommand(fsChangeGroup,
  1083. ARRAYOFCONST((RecursiveStr, Properties->Group, DelimitedName)));
  1084. }
  1085. if (Properties->Valid.Contains(vpOwner))
  1086. {
  1087. ExecCommand(fsChangeOwner,
  1088. ARRAYOFCONST((RecursiveStr, DelimitStr(Properties->Owner), DelimitedName)));
  1089. }
  1090. if (Properties->Valid.Contains(vpRights))
  1091. {
  1092. TRights Rights = Properties->Rights;
  1093. // if we don't set modes recursively, we may add X at once with other
  1094. // options. Otherwise we have to add X after recusive command
  1095. if (!Recursive && IsDirectory && Properties->AddXToDirectories)
  1096. Rights.AddExecute();
  1097. ExecCommand(fsChangeMode,
  1098. ARRAYOFCONST((RecursiveStr, Rights.SimplestStr, DelimitedName)));
  1099. // if file is directory and we do recursive mode settings with
  1100. // add-x-to-directories option on, add those X
  1101. if (Recursive && IsDirectory && Properties->AddXToDirectories)
  1102. {
  1103. Rights.AddExecute();
  1104. ExecCommand(fsChangeMode,
  1105. ARRAYOFCONST(("", Rights.SimplestStr, DelimitedName)));
  1106. }
  1107. }
  1108. assert(!Properties->Valid.Contains(vpLastAccess));
  1109. assert(!Properties->Valid.Contains(vpModification));
  1110. }
  1111. //---------------------------------------------------------------------------
  1112. bool __fastcall TSCPFileSystem::LoadFilesProperties(TStrings * /*FileList*/ )
  1113. {
  1114. assert(false);
  1115. return false;
  1116. }
  1117. //---------------------------------------------------------------------------
  1118. void __fastcall TSCPFileSystem::CalculateFilesChecksum(const AnsiString & /*Alg*/,
  1119. TStrings * /*FileList*/, TStrings * /*Checksums*/,
  1120. TCalculatedChecksumEvent /*OnCalculatedChecksum*/)
  1121. {
  1122. assert(false);
  1123. }
  1124. //---------------------------------------------------------------------------
  1125. void __fastcall TSCPFileSystem::CustomCommandOnFile(const AnsiString FileName,
  1126. const TRemoteFile * File, AnsiString Command, int Params,
  1127. TCaptureOutputEvent OutputEvent)
  1128. {
  1129. assert(File);
  1130. bool Dir = File->IsDirectory && !File->IsSymLink;
  1131. if (Dir && (Params & ccRecursive))
  1132. {
  1133. TCustomCommandParams AParams;
  1134. AParams.Command = Command;
  1135. AParams.Params = Params;
  1136. AParams.OutputEvent = OutputEvent;
  1137. FTerminal->ProcessDirectory(FileName, FTerminal->CustomCommandOnFile,
  1138. &AParams);
  1139. }
  1140. if (!Dir || (Params & ccApplyToDirectories))
  1141. {
  1142. TCustomCommandData Data(FTerminal);
  1143. AnsiString Cmd = TRemoteCustomCommand(
  1144. Data, FTerminal->CurrentDirectory, FileName, "").
  1145. Complete(Command, true);
  1146. AnyCommand(Cmd, OutputEvent);
  1147. }
  1148. }
  1149. //---------------------------------------------------------------------------
  1150. void __fastcall TSCPFileSystem::CaptureOutput(const AnsiString & AddedLine, bool StdError)
  1151. {
  1152. int ReturnCode;
  1153. AnsiString Line = AddedLine;
  1154. if (StdError ||
  1155. !RemoveLastLine(Line, ReturnCode) ||
  1156. !Line.IsEmpty())
  1157. {
  1158. assert(FOnCaptureOutput != NULL);
  1159. FOnCaptureOutput(Line, StdError);
  1160. }
  1161. }
  1162. //---------------------------------------------------------------------------
  1163. void __fastcall TSCPFileSystem::AnyCommand(const AnsiString Command,
  1164. TCaptureOutputEvent OutputEvent)
  1165. {
  1166. assert(FSecureShell->OnCaptureOutput == NULL);
  1167. if (OutputEvent != NULL)
  1168. {
  1169. FSecureShell->OnCaptureOutput = CaptureOutput;
  1170. FOnCaptureOutput = OutputEvent;
  1171. }
  1172. try
  1173. {
  1174. ExecCommand(fsAnyCommand, ARRAYOFCONST((Command)),
  1175. ecDefault | ecIgnoreWarnings);
  1176. }
  1177. __finally
  1178. {
  1179. FOnCaptureOutput = NULL;
  1180. FSecureShell->OnCaptureOutput = NULL;
  1181. }
  1182. }
  1183. //---------------------------------------------------------------------------
  1184. AnsiString __fastcall TSCPFileSystem::FileUrl(const AnsiString FileName)
  1185. {
  1186. return FTerminal->FileUrl("scp", FileName);
  1187. }
  1188. //---------------------------------------------------------------------------
  1189. TStrings * __fastcall TSCPFileSystem::GetFixedPaths()
  1190. {
  1191. return NULL;
  1192. }
  1193. //---------------------------------------------------------------------------
  1194. void __fastcall TSCPFileSystem::SpaceAvailable(const AnsiString Path,
  1195. TSpaceAvailable & /*ASpaceAvailable*/)
  1196. {
  1197. assert(false);
  1198. }
  1199. //---------------------------------------------------------------------------
  1200. // transfer protocol
  1201. //---------------------------------------------------------------------------
  1202. void __fastcall TSCPFileSystem::SCPResponse(bool * GotLastLine)
  1203. {
  1204. // Taken from scp.c response() and modified
  1205. char Resp;
  1206. FSecureShell->Receive(&Resp, 1);
  1207. switch (Resp)
  1208. {
  1209. case 0: /* ok */
  1210. FTerminal->LogEvent("SCP remote side confirmation (0)");
  1211. return;
  1212. default:
  1213. case 1: /* error */
  1214. case 2: /* fatal error */
  1215. // pscp adds 'Resp' to 'Msg', why?
  1216. AnsiString Msg = FSecureShell->ReceiveLine();
  1217. AnsiString Line = AnsiString(Resp) + Msg;
  1218. if (IsLastLine(Line))
  1219. {
  1220. if (GotLastLine)
  1221. {
  1222. *GotLastLine = true;
  1223. }
  1224. /* TODO 1 : Show stderror to user? */
  1225. FSecureShell->ClearStdError();
  1226. try
  1227. {
  1228. ReadCommandOutput(coExpectNoOutput | coRaiseExcept | coOnlyReturnCode);
  1229. }
  1230. catch(...)
  1231. {
  1232. // when ReadCommandOutput() fails than remote SCP is terminated already
  1233. *GotLastLine = true;
  1234. throw;
  1235. }
  1236. }
  1237. else
  1238. if (Resp == 1)
  1239. {
  1240. FTerminal->LogEvent("SCP remote side error (1):");
  1241. }
  1242. else
  1243. {
  1244. FTerminal->LogEvent("SCP remote side fatal error (2):");
  1245. }
  1246. if (Resp == 1)
  1247. {
  1248. THROW_FILE_SKIPPED(NULL, Msg);
  1249. }
  1250. else
  1251. {
  1252. THROW_SCP_ERROR(NULL, Msg);
  1253. }
  1254. }
  1255. }
  1256. //---------------------------------------------------------------------------
  1257. void __fastcall TSCPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1258. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  1259. int Params, TFileOperationProgressType * OperationProgress,
  1260. bool & DisconnectWhenComplete)
  1261. {
  1262. // scp.c: source(), toremote()
  1263. assert(FilesToCopy && OperationProgress);
  1264. AnsiString Options = "";
  1265. bool CheckExistence = UnixComparePaths(TargetDir, FTerminal->CurrentDirectory) &&
  1266. (FTerminal->FFiles != NULL) && FTerminal->FFiles->Loaded;
  1267. bool CopyBatchStarted = false;
  1268. bool Failed = true;
  1269. bool GotLastLine = false;
  1270. if (CopyParam->PreserveRights) Options = "-p";
  1271. if (FTerminal->SessionData->Scp1Compatibility) Options += " -1";
  1272. SendCommand(FCommandSet->FullCommand(fsCopyToRemote,
  1273. ARRAYOFCONST((Options, DelimitStr(UnixExcludeTrailingBackslash(TargetDir))))));
  1274. SkipFirstLine();
  1275. try
  1276. {
  1277. try
  1278. {
  1279. SCPResponse(&GotLastLine);
  1280. // This can happen only if SCP command is not executed and return code is 0
  1281. // It has never happened to me (return code is usually 127)
  1282. if (GotLastLine)
  1283. {
  1284. throw Exception("");
  1285. }
  1286. }
  1287. catch(Exception & E)
  1288. {
  1289. if (GotLastLine && FTerminal->Active)
  1290. {
  1291. FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
  1292. }
  1293. else
  1294. {
  1295. throw;
  1296. }
  1297. }
  1298. CopyBatchStarted = true;
  1299. for (int IFile = 0; (IFile < FilesToCopy->Count) &&
  1300. !OperationProgress->Cancel; IFile++)
  1301. {
  1302. AnsiString FileName = FilesToCopy->Strings[IFile];
  1303. bool CanProceed;
  1304. AnsiString FileNameOnly =
  1305. CopyParam->ChangeFileName(ExtractFileName(FileName), osLocal, true);
  1306. if (CheckExistence)
  1307. {
  1308. // previously there was assertion on FTerminal->FFiles->Loaded, but it
  1309. // fails for scripting, is 'ls' is not issued before
  1310. TRemoteFile * File = FTerminal->FFiles->FindFile(FileNameOnly);
  1311. if (File && OperationProgress->NoToAll)
  1312. {
  1313. CanProceed = false;
  1314. }
  1315. else if (File && !OperationProgress->YesToAll &&
  1316. FTerminal->Configuration->ConfirmOverwriting && !(Params & cpNoConfirmation))
  1317. {
  1318. int Answer;
  1319. if (File->IsDirectory)
  1320. {
  1321. TQueryParams Params(qpNeverAskAgainCheck);
  1322. SUSPEND_OPERATION
  1323. (
  1324. Answer = FTerminal->QueryUser(
  1325. FMTLOAD(DIRECTORY_OVERWRITE, (FileNameOnly)), NULL,
  1326. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll,
  1327. &Params);
  1328. );
  1329. switch (Answer)
  1330. {
  1331. case qaNeverAskAgain:
  1332. FTerminal->Configuration->ConfirmOverwriting = false;
  1333. Answer = qaYes;
  1334. break;
  1335. case qaYesToAll:
  1336. OperationProgress->YesToAll = true;
  1337. Answer = qaYes;
  1338. break;
  1339. case qaNoToAll:
  1340. OperationProgress->NoToAll = true;
  1341. Answer = qaNo;
  1342. break;
  1343. }
  1344. }
  1345. else
  1346. {
  1347. __int64 MTime;
  1348. TOverwriteFileParams FileParams;
  1349. FTerminal->OpenLocalFile(FileName, GENERIC_READ,
  1350. NULL, NULL, NULL, &MTime, NULL,
  1351. &FileParams.SourceSize);
  1352. FileParams.SourceTimestamp = UnixToDateTime(MTime,
  1353. FTerminal->SessionData->DSTMode);
  1354. FileParams.DestSize = File->Size;
  1355. FileParams.DestTimestamp = File->Modification;
  1356. TQueryButtonAlias Aliases[1];
  1357. Aliases[0].Button = qaAll;
  1358. Aliases[0].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  1359. TQueryParams Params(qpNeverAskAgainCheck);
  1360. Params.Aliases = Aliases;
  1361. Params.AliasesCount = LENOF(Aliases);
  1362. SUSPEND_OPERATION
  1363. (
  1364. Answer = FTerminal->ConfirmFileOverwrite(
  1365. FileNameOnly, &FileParams,
  1366. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll,
  1367. &Params, osRemote, OperationProgress);
  1368. );
  1369. }
  1370. switch (Answer) {
  1371. case qaYes:
  1372. CanProceed = true;
  1373. break;
  1374. case qaCancel:
  1375. if (!OperationProgress->Cancel) OperationProgress->Cancel = csCancel;
  1376. case qaNo:
  1377. CanProceed = false;
  1378. break;
  1379. default:
  1380. assert(false);
  1381. }
  1382. }
  1383. else CanProceed = true;
  1384. }
  1385. else CanProceed = true;
  1386. if (CanProceed)
  1387. {
  1388. if (FTerminal->SessionData->CacheDirectories)
  1389. {
  1390. FTerminal->DirectoryModified(TargetDir, false);
  1391. if (DirectoryExists(FileName))
  1392. {
  1393. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  1394. FileNameOnly, true);
  1395. }
  1396. }
  1397. try
  1398. {
  1399. SCPSource(FileName, CopyParam, Params, OperationProgress, 0);
  1400. OperationProgress->Finish(FileName, true, DisconnectWhenComplete);
  1401. }
  1402. catch (EScpFileSkipped &E)
  1403. {
  1404. TQueryParams Params(qpAllowContinueOnError);
  1405. SUSPEND_OPERATION (
  1406. if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FileName)), &E,
  1407. qaOK | qaAbort, &Params, qtError) == qaAbort)
  1408. {
  1409. OperationProgress->Cancel = csCancel;
  1410. }
  1411. OperationProgress->Finish(FileName, false, DisconnectWhenComplete);
  1412. if (!FTerminal->HandleException(&E)) throw;
  1413. );
  1414. }
  1415. catch (EScpSkipFile &E)
  1416. {
  1417. OperationProgress->Finish(FileName, false, DisconnectWhenComplete);
  1418. // If ESkipFile occurs, just log it and continue with next file
  1419. SUSPEND_OPERATION (
  1420. if (!FTerminal->HandleException(&E)) throw;
  1421. );
  1422. }
  1423. catch (...)
  1424. {
  1425. OperationProgress->Finish(FileName, false, DisconnectWhenComplete);
  1426. throw;
  1427. }
  1428. }
  1429. }
  1430. Failed = false;
  1431. }
  1432. __finally
  1433. {
  1434. // Tell remote side, that we're done.
  1435. if (FTerminal->Active)
  1436. {
  1437. try
  1438. {
  1439. if (!GotLastLine)
  1440. {
  1441. if (CopyBatchStarted)
  1442. {
  1443. // What about case, remote side sends fatal error ???
  1444. // (Not sure, if it causes remote side to terminate scp)
  1445. FSecureShell->SendLine("E");
  1446. SCPResponse();
  1447. };
  1448. /* TODO 1 : Show stderror to user? */
  1449. FSecureShell->ClearStdError();
  1450. ReadCommandOutput(coExpectNoOutput | coWaitForLastLine | coOnlyReturnCode |
  1451. (Failed ? 0 : coRaiseExcept));
  1452. }
  1453. }
  1454. catch (Exception &E)
  1455. {
  1456. // Only show error message (it should always succeed, but
  1457. // some pending error maybe in queque) }
  1458. FTerminal->Log->AddException(&E);
  1459. }
  1460. }
  1461. }
  1462. }
  1463. //---------------------------------------------------------------------------
  1464. void __fastcall TSCPFileSystem::SCPSource(const AnsiString FileName,
  1465. const TCopyParamType * CopyParam, int Params,
  1466. TFileOperationProgressType * OperationProgress, int Level)
  1467. {
  1468. AnsiString DestFileName = CopyParam->ChangeFileName(
  1469. ExtractFileName(FileName), osLocal, Level == 0);
  1470. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  1471. OperationProgress->SetFile(FileName);
  1472. HANDLE File;
  1473. int Attrs;
  1474. __int64 MTime, ATime;
  1475. __int64 Size;
  1476. FTerminal->OpenLocalFile(FileName, GENERIC_READ,
  1477. &Attrs, &File, NULL, &MTime, &ATime, &Size);
  1478. TStream * Stream = new TSafeHandleStream((THandle)File);
  1479. try
  1480. {
  1481. bool Dir = FLAGSET(Attrs, faDirectory);
  1482. TFileMasks::TParams MaskParams;
  1483. MaskParams.Size = Size;
  1484. if (FLAGCLEAR(Params, cpDelete) &&
  1485. !CopyParam->AllowTransfer(FileName, osLocal, Dir, MaskParams))
  1486. {
  1487. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer", (FileName)));
  1488. THROW_SKIP_FILE_NULL;
  1489. }
  1490. if (Dir)
  1491. {
  1492. SCPDirectorySource(FileName, CopyParam, Params, OperationProgress, Level);
  1493. }
  1494. else
  1495. {
  1496. assert(File);
  1497. // File is regular file (not directory)
  1498. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  1499. OperationProgress->SetLocalSize(Size);
  1500. // Suppose same data size to transfer as to read
  1501. // (not true with ASCII transfer)
  1502. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1503. OperationProgress->TransferingFile = false;
  1504. // Will we use ASCII of BINARY file tranfer?
  1505. OperationProgress->SetAsciiTransfer(
  1506. CopyParam->UseAsciiTransfer(FileName, osLocal, MaskParams));
  1507. FTerminal->LogEvent(
  1508. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  1509. " transfer mode selected.");
  1510. try
  1511. {
  1512. // During ASCII transfer we will load whole file to this buffer
  1513. // than convert EOL and send it at once, because before converting EOL
  1514. // we can't know its size
  1515. TFileBuffer AsciiBuf;
  1516. do
  1517. {
  1518. // Buffer for one block of data
  1519. TFileBuffer BlockBuf;
  1520. // This is crucial, if it fails during file transfer, it's fatal error
  1521. FILE_OPERATION_LOOP_EX (!OperationProgress->TransferingFile,
  1522. FMTLOAD(READ_ERROR, (FileName)),
  1523. BlockBuf.LoadStream(Stream, OperationProgress->LocalBlockSize(), true);
  1524. );
  1525. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  1526. // We do ASCII transfer: convert EOL of current block
  1527. // (we don't convert whole buffer, cause it would produce
  1528. // huge memory-transfers while inserting/deleting EOL characters)
  1529. // Than we add current block to file buffer
  1530. if (OperationProgress->AsciiTransfer)
  1531. {
  1532. BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
  1533. FTerminal->SessionData->EOLType, cpRemoveCtrlZ | cpRemoveBOM);
  1534. BlockBuf.Memory->Seek(0, soFromBeginning);
  1535. AsciiBuf.ReadStream(BlockBuf.Memory, BlockBuf.Size, true);
  1536. // We don't need it any more
  1537. BlockBuf.Memory->Clear();
  1538. // Calculate total size to sent (assume that ratio between
  1539. // size of source and size of EOL-transformed data would remain same)
  1540. // First check if file contains anything (div by zero!)
  1541. if (OperationProgress->LocalyUsed)
  1542. {
  1543. __int64 X = OperationProgress->LocalSize;
  1544. X *= AsciiBuf.Size;
  1545. X /= OperationProgress->LocalyUsed;
  1546. OperationProgress->ChangeTransferSize(X);
  1547. }
  1548. else
  1549. {
  1550. OperationProgress->ChangeTransferSize(0);
  1551. }
  1552. }
  1553. // We send file information on first pass during BINARY transfer
  1554. // and on last pass during ASCII transfer
  1555. // BINARY: We succeeded reading first buffer from file, hopefully
  1556. // we will be able to read whole, so we send file info to remote side
  1557. // This is done, because when reading fails we can't interrupt sending
  1558. // (don't know how to tell other side that it failed)
  1559. if (!OperationProgress->TransferingFile &&
  1560. (!OperationProgress->AsciiTransfer || OperationProgress->IsLocalyDone()))
  1561. {
  1562. AnsiString Buf;
  1563. if (CopyParam->PreserveTime)
  1564. {
  1565. // Send last file access and modification time
  1566. // TVarRec don't understand 'unsigned int' -> we use sprintf()
  1567. Buf.sprintf("T%lu 0 %lu 0", static_cast<unsigned long>(MTime),
  1568. static_cast<unsigned long>(ATime));
  1569. FSecureShell->SendLine(Buf);
  1570. SCPResponse();
  1571. }
  1572. // Send file modes (rights), filesize and file name
  1573. // TVarRec don't understand 'unsigned int' -> we use sprintf()
  1574. Buf.sprintf("C%s %Ld %s",
  1575. CopyParam->RemoteFileRights(Attrs).Octal.data(),
  1576. (OperationProgress->AsciiTransfer ? (__int64)AsciiBuf.Size :
  1577. OperationProgress->LocalSize),
  1578. DestFileName.data());
  1579. FSecureShell->SendLine(Buf);
  1580. SCPResponse();
  1581. // Indicate we started transfering file, we need to finish it
  1582. // If not, it's fatal error
  1583. OperationProgress->TransferingFile = true;
  1584. // If we're doing ASCII transfer, this is last pass
  1585. // so we send whole file
  1586. /* TODO : We can't send file above 32bit size in ASCII mode! */
  1587. if (OperationProgress->AsciiTransfer)
  1588. {
  1589. FTerminal->LogEvent(FORMAT("Sending ASCII data (%u bytes)",
  1590. (AsciiBuf.Size)));
  1591. // Should be equal, just in case it's rounded (see above)
  1592. OperationProgress->ChangeTransferSize(AsciiBuf.Size);
  1593. while (!OperationProgress->IsTransferDone())
  1594. {
  1595. unsigned long BlockSize = OperationProgress->TransferBlockSize();
  1596. FSecureShell->Send(
  1597. AsciiBuf.Data + (unsigned int)OperationProgress->TransferedSize,
  1598. BlockSize);
  1599. OperationProgress->AddTransfered(BlockSize);
  1600. if (OperationProgress->Cancel == csCancelTransfer)
  1601. {
  1602. throw Exception(USER_TERMINATED);
  1603. }
  1604. }
  1605. }
  1606. }
  1607. // At end of BINARY transfer pass, send current block
  1608. if (!OperationProgress->AsciiTransfer)
  1609. {
  1610. if (!OperationProgress->TransferedSize)
  1611. {
  1612. FTerminal->LogEvent(FORMAT("Sending BINARY data (first block, %u bytes)",
  1613. (BlockBuf.Size)));
  1614. }
  1615. else if (FTerminal->Configuration->LogProtocol >= 1)
  1616. {
  1617. FTerminal->LogEvent(FORMAT("Sending BINARY data (%u bytes)",
  1618. (BlockBuf.Size)));
  1619. }
  1620. FSecureShell->Send(BlockBuf.Data, BlockBuf.Size);
  1621. OperationProgress->AddTransfered(BlockBuf.Size);
  1622. }
  1623. if ((OperationProgress->Cancel == csCancelTransfer) ||
  1624. (OperationProgress->Cancel == csCancel && !OperationProgress->TransferingFile))
  1625. {
  1626. throw Exception(USER_TERMINATED);
  1627. }
  1628. }
  1629. while (!OperationProgress->IsLocalyDone() || !OperationProgress->IsTransferDone());
  1630. FSecureShell->SendNull();
  1631. try
  1632. {
  1633. SCPResponse();
  1634. // If one of two following exceptions occurs, is means, that remote
  1635. // side already know, that file transfer finished, even if it failed
  1636. // so we don't have to throw EFatal
  1637. }
  1638. catch (EScp &E)
  1639. {
  1640. // SCP protocol fatal error
  1641. OperationProgress->TransferingFile = false;
  1642. throw;
  1643. }
  1644. catch (EScpFileSkipped &E)
  1645. {
  1646. // SCP protocol non-fatal error
  1647. OperationProgress->TransferingFile = false;
  1648. throw;
  1649. }
  1650. // We succeded transfering file, from now we can handle exceptions
  1651. // normally -> no fatal error
  1652. OperationProgress->TransferingFile = false;
  1653. }
  1654. catch (Exception &E)
  1655. {
  1656. // Every exception during file transfer is fatal
  1657. if (OperationProgress->TransferingFile)
  1658. {
  1659. FTerminal->FatalError(&E, FMTLOAD(COPY_FATAL, (FileName)));
  1660. }
  1661. else
  1662. {
  1663. throw;
  1664. }
  1665. }
  1666. }
  1667. }
  1668. __finally
  1669. {
  1670. if (File != NULL)
  1671. {
  1672. CloseHandle(File);
  1673. }
  1674. delete Stream;
  1675. }
  1676. /* TODO : Delete also read-only files. */
  1677. /* TODO : Show error message on failure. */
  1678. if (FLAGSET(Params, cpDelete))
  1679. {
  1680. Sysutils::DeleteFile(FileName);
  1681. }
  1682. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1683. {
  1684. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (FileName)),
  1685. THROWOSIFFALSE(FileSetAttr(FileName, Attrs & ~faArchive) == 0);
  1686. )
  1687. }
  1688. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory finished.", (FileName)));
  1689. }
  1690. //---------------------------------------------------------------------------
  1691. void __fastcall TSCPFileSystem::SCPDirectorySource(const AnsiString DirectoryName,
  1692. const TCopyParamType * CopyParam, int Params,
  1693. TFileOperationProgressType * OperationProgress, int Level)
  1694. {
  1695. int Attrs;
  1696. FTerminal->LogEvent(FORMAT("Entering directory \"%s\".", (DirectoryName)));
  1697. OperationProgress->SetFile(DirectoryName);
  1698. AnsiString DestFileName = CopyParam->ChangeFileName(
  1699. ExtractFileName(DirectoryName), osLocal, Level == 0);
  1700. // Get directory attributes
  1701. FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (DirectoryName)),
  1702. Attrs = FileGetAttr(DirectoryName);
  1703. if (Attrs == -1) RaiseLastOSError();
  1704. )
  1705. AnsiString Buf;
  1706. /* TODO 1: maybe send filetime */
  1707. // Send directory modes (rights), filesize and file name
  1708. Buf = FORMAT("D%s 0 %s",
  1709. (CopyParam->RemoteFileRights(Attrs).Octal, DestFileName));
  1710. FSecureShell->SendLine(Buf);
  1711. SCPResponse();
  1712. try
  1713. {
  1714. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1715. TSearchRec SearchRec;
  1716. bool FindOK;
  1717. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1718. FindOK = (bool)(FindFirst(IncludeTrailingBackslash(DirectoryName) + "*.*",
  1719. FindAttrs, SearchRec) == 0);
  1720. );
  1721. while (FindOK && !OperationProgress->Cancel)
  1722. {
  1723. AnsiString FileName = IncludeTrailingBackslash(DirectoryName) + SearchRec.Name;
  1724. try
  1725. {
  1726. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  1727. {
  1728. SCPSource(FileName, CopyParam, Params, OperationProgress, Level + 1);
  1729. }
  1730. }
  1731. // Previously we catched EScpSkipFile, making error being displayed
  1732. // even when file was excluded by mask. Now the EScpSkipFile is special
  1733. // case without error message.
  1734. catch (EScpFileSkipped &E)
  1735. {
  1736. TQueryParams Params(qpAllowContinueOnError);
  1737. SUSPEND_OPERATION (
  1738. if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (FileName)), &E,
  1739. qaOK | qaAbort, &Params, qtError) == qaAbort)
  1740. {
  1741. OperationProgress->Cancel = csCancel;
  1742. }
  1743. if (!FTerminal->HandleException(&E)) throw;
  1744. );
  1745. }
  1746. catch (EScpSkipFile &E)
  1747. {
  1748. // If ESkipFile occurs, just log it and continue with next file
  1749. SUSPEND_OPERATION (
  1750. if (!FTerminal->HandleException(&E)) throw;
  1751. );
  1752. }
  1753. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1754. FindOK = (FindNext(SearchRec) == 0);
  1755. );
  1756. };
  1757. FindClose(SearchRec);
  1758. /* TODO : Delete also read-only directories. */
  1759. /* TODO : Show error message on failure. */
  1760. if (!OperationProgress->Cancel)
  1761. {
  1762. if (FLAGSET(Params, cpDelete))
  1763. {
  1764. RemoveDir(DirectoryName);
  1765. }
  1766. else if (CopyParam->ClearArchive && FLAGSET(Attrs, faArchive))
  1767. {
  1768. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DirectoryName)),
  1769. THROWOSIFFALSE(FileSetAttr(DirectoryName, Attrs & ~faArchive) == 0);
  1770. )
  1771. }
  1772. }
  1773. }
  1774. __finally
  1775. {
  1776. if (FTerminal->Active)
  1777. {
  1778. // Tell remote side, that we're done.
  1779. FTerminal->LogEvent(FORMAT("Leaving directory \"%s\".", (DirectoryName)));
  1780. FSecureShell->SendLine("E");
  1781. SCPResponse();
  1782. }
  1783. }
  1784. }
  1785. //---------------------------------------------------------------------------
  1786. void __fastcall TSCPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1787. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  1788. int Params, TFileOperationProgressType * OperationProgress,
  1789. bool & DisconnectWhenComplete)
  1790. {
  1791. bool CloseSCP = False;
  1792. AnsiString Options = "";
  1793. if (CopyParam->PreserveRights || CopyParam->PreserveTime) Options = "-p";
  1794. if (FTerminal->SessionData->Scp1Compatibility) Options += " -1";
  1795. FTerminal->LogEvent(FORMAT("Copying %d files/directories to local directory "
  1796. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  1797. FTerminal->LogEvent(CopyParam->LogStr);
  1798. try
  1799. {
  1800. for (int IFile = 0; (IFile < FilesToCopy->Count) &&
  1801. !OperationProgress->Cancel; IFile++)
  1802. {
  1803. AnsiString FileName = FilesToCopy->Strings[IFile];
  1804. TRemoteFile * File = (TRemoteFile *)FilesToCopy->Objects[IFile];
  1805. assert(File);
  1806. try
  1807. {
  1808. bool Success = true; // Have to be set to True (see ::SCPSink)
  1809. SendCommand(FCommandSet->FullCommand(fsCopyToLocal,
  1810. ARRAYOFCONST((Options, DelimitStr(FileName)))));
  1811. SkipFirstLine();
  1812. // Filename is used for error messaging and excluding files only
  1813. // Send in full path to allow path-based excluding
  1814. AnsiString FullFileName = UnixExcludeTrailingBackslash(File->FullFileName);
  1815. SCPSink(TargetDir, FullFileName, UnixExtractFilePath(FullFileName),
  1816. CopyParam, Success, OperationProgress, Params, 0);
  1817. // operation succeded (no exception), so it's ok that
  1818. // remote side closed SCP, but we continue with next file
  1819. if (OperationProgress->Cancel == csRemoteAbort)
  1820. {
  1821. OperationProgress->Cancel = csContinue;
  1822. }
  1823. // Move operation -> delete file/directory afterwards
  1824. // but only if copying succeded
  1825. if ((Params & cpDelete) && Success && !OperationProgress->Cancel)
  1826. {
  1827. try
  1828. {
  1829. FTerminal->ExceptionOnFail = true;
  1830. try
  1831. {
  1832. FILE_OPERATION_LOOP(FMTLOAD(DELETE_FILE_ERROR, (FileName)),
  1833. // pass full file name in FileName, in case we are not moving
  1834. // from current directory
  1835. FTerminal->DeleteFile(FileName, File)
  1836. );
  1837. }
  1838. __finally
  1839. {
  1840. FTerminal->ExceptionOnFail = false;
  1841. }
  1842. }
  1843. catch (EFatal &E)
  1844. {
  1845. throw;
  1846. }
  1847. catch (...)
  1848. {
  1849. // If user selects skip (or abort), nothing special actualy occures
  1850. // we just run DoFinished with Success = False, so file won't
  1851. // be deselected in panel (depends on assigned event handler)
  1852. // On csCancel we would later try to close remote SCP, but it
  1853. // is closed already
  1854. if (OperationProgress->Cancel == csCancel)
  1855. {
  1856. OperationProgress->Cancel = csRemoteAbort;
  1857. }
  1858. Success = false;
  1859. }
  1860. }
  1861. OperationProgress->Finish(FileName,
  1862. (!OperationProgress->Cancel && Success), DisconnectWhenComplete);
  1863. }
  1864. catch (...)
  1865. {
  1866. OperationProgress->Finish(FileName, false, DisconnectWhenComplete);
  1867. CloseSCP = (OperationProgress->Cancel != csRemoteAbort);
  1868. throw;
  1869. }
  1870. }
  1871. }
  1872. __finally
  1873. {
  1874. // In case that copying don't causes fatal error (ie. connection is
  1875. // still active) but weren't succesful (exception or user termination)
  1876. // we need to ensure, that SCP on remote side is closed
  1877. if (FTerminal->Active && (CloseSCP ||
  1878. (OperationProgress->Cancel == csCancel) ||
  1879. (OperationProgress->Cancel == csCancelTransfer)))
  1880. {
  1881. bool LastLineRead;
  1882. // If we get LastLine, it means that remote side 'scp' is already
  1883. // terminated, so we need not to terminate it. There is also
  1884. // possibility that remote side waits for confirmation, so it will hang.
  1885. // This should not happen (hope)
  1886. AnsiString Line = FSecureShell->ReceiveLine();
  1887. LastLineRead = IsLastLine(Line);
  1888. if (!LastLineRead)
  1889. {
  1890. SCPSendError((OperationProgress->Cancel ? "Terminated by user." : "Exception"), true);
  1891. }
  1892. // Just in case, remote side already sent some more data (it's probable)
  1893. // but we don't want to raise exception (user asked to terminate, it's not error)
  1894. int ECParams = coOnlyReturnCode;
  1895. if (!LastLineRead) ECParams |= coWaitForLastLine;
  1896. ReadCommandOutput(ECParams);
  1897. }
  1898. }
  1899. }
  1900. //---------------------------------------------------------------------------
  1901. void __fastcall TSCPFileSystem::SCPError(const AnsiString Message, bool Fatal)
  1902. {
  1903. SCPSendError(Message, Fatal);
  1904. THROW_FILE_SKIPPED(NULL, Message);
  1905. }
  1906. //---------------------------------------------------------------------------
  1907. void __fastcall TSCPFileSystem::SCPSendError(const AnsiString Message, bool Fatal)
  1908. {
  1909. char ErrorLevel = (char)(Fatal ? 2 : 1);
  1910. FTerminal->LogEvent(FORMAT("Sending SCP error (%d) to remote side:",
  1911. ((int)ErrorLevel)));
  1912. FSecureShell->Send(&ErrorLevel, 1);
  1913. // We don't send exact error message, because some unspecified
  1914. // characters can terminate remote scp
  1915. FSecureShell->SendLine("scp: error");
  1916. }
  1917. //---------------------------------------------------------------------------
  1918. void __fastcall TSCPFileSystem::SCPSink(const AnsiString TargetDir,
  1919. const AnsiString FileName, const AnsiString SourceDir,
  1920. const TCopyParamType * CopyParam, bool & Success,
  1921. TFileOperationProgressType * OperationProgress, int Params,
  1922. int Level)
  1923. {
  1924. struct
  1925. {
  1926. int SetTime;
  1927. FILETIME AcTime;
  1928. FILETIME WrTime;
  1929. TRights RemoteRights;
  1930. int Attrs;
  1931. bool Exists;
  1932. } FileData;
  1933. TDateTime SourceTimestamp;
  1934. bool SkipConfirmed = false;
  1935. bool Initialized = (Level > 0);
  1936. FileData.SetTime = 0;
  1937. FSecureShell->SendNull();
  1938. while (!OperationProgress->Cancel)
  1939. {
  1940. // See (switch ... case 'T':)
  1941. if (FileData.SetTime) FileData.SetTime--;
  1942. // In case of error occured before control record arrived.
  1943. // We can finally use full path here, as we get current path in FileName param
  1944. // (we used to set the file into OperationProgress->FileName, but it collided
  1945. // with progress outputing, particularly for scripting)
  1946. AnsiString ErrorFileName = FileName;
  1947. try
  1948. {
  1949. // Receive control record
  1950. AnsiString Line = FSecureShell->ReceiveLine();
  1951. if (Line.Length() == 0) FTerminal->FatalError(NULL, LoadStr(SCP_EMPTY_LINE));
  1952. if (IsLastLine(Line))
  1953. {
  1954. // Remote side finished copying, so remote SCP was closed
  1955. // and we don't need to terminate it manualy, see CopyToLocal()
  1956. OperationProgress->Cancel = csRemoteAbort;
  1957. /* TODO 1 : Show stderror to user? */
  1958. FSecureShell->ClearStdError();
  1959. try
  1960. {
  1961. // coIgnoreWarnings should allow batch transfer to continue when
  1962. // download of one the files failes (user denies overwritting
  1963. // of target local file, no read permissions...)
  1964. ReadCommandOutput(coExpectNoOutput | coRaiseExcept |
  1965. coOnlyReturnCode | coIgnoreWarnings);
  1966. if (!Initialized)
  1967. {
  1968. throw Exception("");
  1969. }
  1970. }
  1971. catch(Exception & E)
  1972. {
  1973. if (!Initialized && FTerminal->Active)
  1974. {
  1975. FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
  1976. }
  1977. else
  1978. {
  1979. throw;
  1980. }
  1981. }
  1982. return;
  1983. }
  1984. else
  1985. {
  1986. Initialized = true;
  1987. // First characted distinguish type of control record
  1988. char Ctrl = Line[1];
  1989. Line.Delete(1, 1);
  1990. switch (Ctrl) {
  1991. case 1:
  1992. // Error (already logged by ReceiveLine())
  1993. THROW_FILE_SKIPPED(NULL, FMTLOAD(REMOTE_ERROR, (Line)));
  1994. case 2:
  1995. // Fatal error, terminate copying
  1996. FTerminal->TerminalError(Line);
  1997. return; // Unreachable
  1998. case 'E': // Exit
  1999. FSecureShell->SendNull();
  2000. return;
  2001. case 'T':
  2002. unsigned long MTime, ATime;
  2003. if (sscanf(Line.c_str(), "%ld %*d %ld %*d", &MTime, &ATime) == 2)
  2004. {
  2005. FileData.AcTime = DateTimeToFileTime(UnixToDateTime(ATime,
  2006. FTerminal->SessionData->DSTMode), FTerminal->SessionData->DSTMode);
  2007. FileData.WrTime = DateTimeToFileTime(UnixToDateTime(MTime,
  2008. FTerminal->SessionData->DSTMode), FTerminal->SessionData->DSTMode);
  2009. SourceTimestamp = UnixToDateTime(MTime,
  2010. FTerminal->SessionData->DSTMode);
  2011. FSecureShell->SendNull();
  2012. // File time is only valid until next pass
  2013. FileData.SetTime = 2;
  2014. continue;
  2015. }
  2016. else
  2017. {
  2018. SCPError(LoadStr(SCP_ILLEGAL_TIME_FORMAT), False);
  2019. }
  2020. case 'C':
  2021. case 'D':
  2022. break; // continue pass switch{}
  2023. default:
  2024. FTerminal->FatalError(NULL, FMTLOAD(SCP_INVALID_CONTROL_RECORD, (Ctrl, Line)));
  2025. }
  2026. TFileMasks::TParams MaskParams;
  2027. // We reach this point only if control record was 'C' or 'D'
  2028. try
  2029. {
  2030. FileData.RemoteRights.Octal = CutToChar(Line, ' ', True);
  2031. // do not trim leading spaces of the filename
  2032. __int64 TSize = StrToInt64(CutToChar(Line, ' ', False).TrimRight());
  2033. MaskParams.Size = TSize;
  2034. // Security fix: ensure the file ends up where we asked for it.
  2035. // (accept only filename, not path)
  2036. AnsiString OnlyFileName = UnixExtractFileName(Line);
  2037. if (Line != OnlyFileName)
  2038. {
  2039. FTerminal->LogEvent(FORMAT("Warning: Remote host set a compound pathname '%s'", (Line)));
  2040. }
  2041. OperationProgress->SetFile(OnlyFileName);
  2042. ErrorFileName = SourceDir + OnlyFileName;
  2043. OperationProgress->SetTransferSize(TSize);
  2044. }
  2045. catch (Exception &E)
  2046. {
  2047. SUSPEND_OPERATION (
  2048. FTerminal->Log->AddException(&E);
  2049. );
  2050. SCPError(LoadStr(SCP_ILLEGAL_FILE_DESCRIPTOR), false);
  2051. }
  2052. // last possibility to cancel transfer before it starts
  2053. if (OperationProgress->Cancel)
  2054. {
  2055. THROW_SKIP_FILE(NULL, LoadStr(USER_TERMINATED));
  2056. }
  2057. // Security fix
  2058. if (IsDots(OperationProgress->FileName))
  2059. {
  2060. FTerminal->FatalError(NULL, LoadStr(ATTEMPT_TO_WRITE_TO_PARENT_DIR));
  2061. }
  2062. bool Dir = (Ctrl == 'D');
  2063. AnsiString SourceFullName = SourceDir + OperationProgress->FileName;
  2064. if (FLAGCLEAR(Params, cpDelete) &&
  2065. !CopyParam->AllowTransfer(SourceFullName, osRemote, Dir, MaskParams))
  2066. {
  2067. FTerminal->LogEvent(FORMAT("File \"%s\" excluded from transfer",
  2068. (ErrorFileName)));
  2069. SkipConfirmed = true;
  2070. SCPError("", false);
  2071. }
  2072. AnsiString DestFileName =
  2073. IncludeTrailingBackslash(TargetDir) +
  2074. CopyParam->ChangeFileName(OperationProgress->FileName, osRemote,
  2075. Level == 0);
  2076. FileData.Attrs = FileGetAttr(DestFileName);
  2077. // If getting attrs failes, we suppose, that file/folder doesn't exists
  2078. FileData.Exists = (FileData.Attrs != -1);
  2079. if (Dir)
  2080. {
  2081. if (FileData.Exists && !(FileData.Attrs & faDirectory))
  2082. {
  2083. SCPError(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFileName)), false);
  2084. }
  2085. if (!FileData.Exists)
  2086. {
  2087. FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFileName)),
  2088. if (!ForceDirectories(DestFileName)) RaiseLastOSError();
  2089. );
  2090. /* SCP: can we set the timestamp for directories ? */
  2091. }
  2092. AnsiString FullFileName = SourceDir + OperationProgress->FileName;
  2093. SCPSink(DestFileName, FullFileName, UnixIncludeTrailingBackslash(FullFileName),
  2094. CopyParam, Success, OperationProgress, Params, Level + 1);
  2095. continue;
  2096. }
  2097. else
  2098. if (Ctrl == 'C')
  2099. {
  2100. HANDLE File = NULL;
  2101. TStream * FileStream = NULL;
  2102. /* TODO 1 : Turn off read-only attr */
  2103. try
  2104. {
  2105. try
  2106. {
  2107. if (FileExists(DestFileName))
  2108. {
  2109. int Answer;
  2110. if (OperationProgress->NoToAll)
  2111. {
  2112. Answer = qaNo;
  2113. }
  2114. // if overwrite confirmation is required or
  2115. // only newer files should be transfered, get both file timestamps
  2116. else if (FLAGSET(Params, cpNewerOnly) ||
  2117. (!OperationProgress->YesToAll &&
  2118. FTerminal->Configuration->ConfirmOverwriting &&
  2119. FLAGCLEAR(Params, cpNoConfirmation)))
  2120. {
  2121. __int64 MTime;
  2122. TOverwriteFileParams FileParams;
  2123. FileParams.SourceSize = OperationProgress->TransferSize;
  2124. FileParams.SourceTimestamp = SourceTimestamp;
  2125. FTerminal->OpenLocalFile(DestFileName, GENERIC_READ,
  2126. NULL, NULL, NULL, &MTime, NULL,
  2127. &FileParams.DestSize);
  2128. FileParams.DestTimestamp = UnixToDateTime(MTime,
  2129. FTerminal->SessionData->DSTMode);
  2130. TQueryButtonAlias Aliases[1];
  2131. Aliases[0].Button = qaAll;
  2132. Aliases[0].Alias = LoadStr(YES_TO_NEWER_BUTTON);
  2133. TQueryParams Params(qpNeverAskAgainCheck);
  2134. Params.Aliases = Aliases;
  2135. Params.AliasesCount = LENOF(Aliases);
  2136. SUSPEND_OPERATION (
  2137. Answer = FTerminal->ConfirmFileOverwrite(
  2138. OperationProgress->FileName, &FileParams,
  2139. qaYes | qaNo | qaCancel | qaYesToAll | qaNoToAll | qaAll,
  2140. &Params, osLocal, OperationProgress);
  2141. );
  2142. }
  2143. switch (Answer)
  2144. {
  2145. case qaCancel: OperationProgress->Cancel = csCancel; // continue on next case
  2146. case qaNo: SkipConfirmed = true; EXCEPTION;
  2147. }
  2148. }
  2149. if (!FTerminal->CreateLocalFile(DestFileName, OperationProgress,
  2150. &File, FLAGSET(Params, cpNoConfirmation)))
  2151. {
  2152. SkipConfirmed = true;
  2153. EXCEPTION;
  2154. }
  2155. FileStream = new TSafeHandleStream((THandle)File);
  2156. }
  2157. catch (Exception &E)
  2158. {
  2159. // In this step we can still cancel transfer, so we do it
  2160. SCPError(E.Message, false);
  2161. throw;
  2162. }
  2163. // We succeded, so we confirm transfer to remote side
  2164. FSecureShell->SendNull();
  2165. // From now we need to finish file transfer, if not it's fatal error
  2166. OperationProgress->TransferingFile = true;
  2167. // Suppose same data size to transfer as to write
  2168. // (not true with ASCII transfer)
  2169. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  2170. // Will we use ASCII of BINARY file tranfer?
  2171. OperationProgress->SetAsciiTransfer(
  2172. CopyParam->UseAsciiTransfer(SourceFullName, osRemote, MaskParams));
  2173. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  2174. " transfer mode selected.");
  2175. try
  2176. {
  2177. // Buffer for one block of data
  2178. TFileBuffer BlockBuf;
  2179. do
  2180. {
  2181. BlockBuf.Size = OperationProgress->TransferBlockSize();
  2182. BlockBuf.Position = 0;
  2183. FSecureShell->Receive(BlockBuf.Data, BlockBuf.Size);
  2184. OperationProgress->AddTransfered(BlockBuf.Size);
  2185. if (OperationProgress->AsciiTransfer)
  2186. {
  2187. unsigned int PrevBlockSize = BlockBuf.Size;
  2188. BlockBuf.Convert(FTerminal->SessionData->EOLType,
  2189. FTerminal->Configuration->LocalEOLType, 0);
  2190. OperationProgress->SetLocalSize(
  2191. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  2192. }
  2193. // This is crucial, if it fails during file transfer, it's fatal error
  2194. FILE_OPERATION_LOOP_EX (false, FMTLOAD(WRITE_ERROR, (DestFileName)),
  2195. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  2196. );
  2197. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  2198. if (OperationProgress->Cancel == csCancelTransfer)
  2199. {
  2200. throw Exception(USER_TERMINATED);
  2201. }
  2202. }
  2203. while (!OperationProgress->IsLocalyDone() || !
  2204. OperationProgress->IsTransferDone());
  2205. }
  2206. catch (Exception &E)
  2207. {
  2208. // Every exception during file transfer is fatal
  2209. FTerminal->FatalError(&E,
  2210. FMTLOAD(COPY_FATAL, (OperationProgress->FileName)));
  2211. }
  2212. OperationProgress->TransferingFile = false;
  2213. try
  2214. {
  2215. SCPResponse();
  2216. // If one of following exception occurs, we still need
  2217. // to send confirmation to other side
  2218. }
  2219. catch (EScp &E)
  2220. {
  2221. FSecureShell->SendNull();
  2222. throw;
  2223. }
  2224. catch (EScpFileSkipped &E)
  2225. {
  2226. FSecureShell->SendNull();
  2227. throw;
  2228. }
  2229. FSecureShell->SendNull();
  2230. if (FileData.SetTime && CopyParam->PreserveTime)
  2231. {
  2232. SetFileTime(File, NULL, &FileData.AcTime, &FileData.WrTime);
  2233. }
  2234. }
  2235. __finally
  2236. {
  2237. if (File) CloseHandle(File);
  2238. if (FileStream) delete FileStream;
  2239. }
  2240. if (FileData.Attrs == -1) FileData.Attrs = faArchive;
  2241. int NewAttrs = CopyParam->LocalFileAttrs(FileData.RemoteRights);
  2242. if ((NewAttrs & FileData.Attrs) != NewAttrs)
  2243. {
  2244. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFileName)),
  2245. THROWOSIFFALSE(FileSetAttr(DestFileName, FileData.Attrs | NewAttrs) == 0);
  2246. );
  2247. }
  2248. }
  2249. }
  2250. }
  2251. catch (EScpFileSkipped &E)
  2252. {
  2253. if (!SkipConfirmed)
  2254. {
  2255. SUSPEND_OPERATION (
  2256. TQueryParams Params(qpAllowContinueOnError);
  2257. if (FTerminal->QueryUserException(FMTLOAD(COPY_ERROR, (ErrorFileName)),
  2258. &E, qaOK | qaAbort, &Params, qtError) == qaAbort)
  2259. {
  2260. OperationProgress->Cancel = csCancel;
  2261. }
  2262. FTerminal->FLog->AddException(&E);
  2263. );
  2264. }
  2265. // this was inside above condition, but then transfer was considered
  2266. // succesfull, even when for example user refused to overwrite file
  2267. Success = false;
  2268. }
  2269. catch (EScpSkipFile &E)
  2270. {
  2271. SCPSendError(E.Message, false);
  2272. Success = false;
  2273. if (!FTerminal->HandleException(&E)) throw;
  2274. }
  2275. }
  2276. }