ScpFileSystem.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  1. //---------------------------------------------------------------------------
  2. #include <vcl.h>
  3. #pragma hdrstop
  4. #include "ScpFileSystem.h"
  5. #include "Common.h"
  6. #include "Interface.h"
  7. #include "Terminal.h"
  8. #include "TextsCore.h"
  9. #include <stdio.h>
  10. //---------------------------------------------------------------------------
  11. #pragma package(smart_init)
  12. //---------------------------------------------------------------------------
  13. const coRaiseExcept = 1;
  14. const coExpectNoOutput = 2;
  15. const coWaitForLastLine = 4;
  16. const coOnlyReturnCode = 8;
  17. const coIgnoreWarnings = 16;
  18. const ecRaiseExcept = 1;
  19. const ecIgnoreWarnings = 2;
  20. //---------------------------------------------------------------------------
  21. #define THROW_FILE_SKIPPED(EXCEPTION, MESSAGE) \
  22. throw EScpFileSkipped(EXCEPTION, MESSAGE)
  23. #define THROW_SCP_ERROR(EXCEPTION, MESSAGE) \
  24. throw EScp(EXCEPTION, MESSAGE)
  25. //===========================================================================
  26. #define MaxShellCommand fsAnyCommand
  27. #define ShellCommandCount MaxShellCommand + 1
  28. #define MaxCommandLen 40
  29. struct TCommandType
  30. {
  31. int MinLines;
  32. int MaxLines;
  33. bool ModifiesFiles;
  34. bool ChangesDirectory;
  35. bool InteractiveCommand;
  36. char Command[MaxCommandLen];
  37. };
  38. // Only one character! See TSCPFileSystem::ReadCommandOutput()
  39. #define LastLineSeparator ":"
  40. #define LAST_LINE "WinSCP: this is end-of-file"
  41. #define FIRST_LINE "WinSCP: this is begin-of-file"
  42. extern const TCommandType DefaultCommandSet[];
  43. #define NationalVarCount 10
  44. extern const char NationalVars[NationalVarCount][15];
  45. #define CHECK_CMD assert((Cmd >=0) && (Cmd <= MaxShellCommand))
  46. class TSessionData;
  47. //---------------------------------------------------------------------------
  48. class TCommandSet
  49. {
  50. private:
  51. TCommandType CommandSet[ShellCommandCount];
  52. TSessionData * FSessionData;
  53. AnsiString FReturnVar;
  54. int __fastcall GetMaxLines(TFSCommand Cmd);
  55. int __fastcall GetMinLines(TFSCommand Cmd);
  56. bool __fastcall GetModifiesFiles(TFSCommand Cmd);
  57. bool __fastcall GetChangesDirectory(TFSCommand Cmd);
  58. bool __fastcall GetOneLineCommand(TFSCommand Cmd);
  59. void __fastcall SetCommands(TFSCommand Cmd, AnsiString value);
  60. AnsiString __fastcall GetCommands(TFSCommand Cmd);
  61. AnsiString __fastcall GetFirstLine();
  62. bool __fastcall GetInteractiveCommand(TFSCommand Cmd);
  63. AnsiString __fastcall GetLastLine();
  64. AnsiString __fastcall GetReturnVar();
  65. public:
  66. __fastcall TCommandSet(TSessionData *aSessionData);
  67. void __fastcall Default();
  68. void __fastcall CopyFrom(TCommandSet * Source);
  69. AnsiString __fastcall Command(TFSCommand Cmd, const TVarRec * args, int size);
  70. TStrings * __fastcall CreateCommandList();
  71. AnsiString __fastcall FullCommand(TFSCommand Cmd, const TVarRec * args, int size);
  72. __property int MaxLines[TFSCommand Cmd] = { read=GetMaxLines};
  73. __property int MinLines[TFSCommand Cmd] = { read=GetMinLines };
  74. __property bool ModifiesFiles[TFSCommand Cmd] = { read=GetModifiesFiles };
  75. __property bool ChangesDirectory[TFSCommand Cmd] = { read=GetChangesDirectory };
  76. __property bool OneLineCommand[TFSCommand Cmd] = { read=GetOneLineCommand };
  77. __property AnsiString Commands[TFSCommand Cmd] = { read=GetCommands, write=SetCommands };
  78. __property AnsiString FirstLine = { read = GetFirstLine };
  79. __property bool InteractiveCommand[TFSCommand Cmd] = { read = GetInteractiveCommand };
  80. __property AnsiString LastLine = { read=GetLastLine };
  81. __property TSessionData * SessionData = { read=FSessionData, write=FSessionData };
  82. __property AnsiString ReturnVar = { read=GetReturnVar, write=FReturnVar };
  83. };
  84. //===========================================================================
  85. const char NationalVars[NationalVarCount][15] =
  86. {"LANG", "LANGUAGE", "LC_CTYPE", "LC_COLLATE", "LC_MONETARY", "LC_NUMERIC",
  87. "LC_TIME", "LC_MESSAGES", "LC_ALL", "HUMAN_BLOCKS" };
  88. //---------------------------------------------------------------------------
  89. #define F false
  90. #define T true
  91. // TODO: remove "mf" and "cd", it is implemented in TTerminal already
  92. const TCommandType DefaultCommandSet[ShellCommandCount] = {
  93. // min max mf cd ia command
  94. /*Null*/ { -1, -1, F, F, F, "" },
  95. /*VarValue*/ { -1, -1, F, F, F, "echo \"$%s\"" /* variable */ },
  96. /*LastLine*/ { -1, -1, F, F, F, "echo \"%s" LastLineSeparator "%s\"" /* last line, return var */ },
  97. /*FirstLine*/ { -1, -1, F, F, F, "echo \"%s\"" /* first line */ },
  98. /*CurrentDirectory*/ { 1, 1, F, F, F, "pwd" },
  99. /*ChangeDirectory*/ { 0, 0, F, T, F, "cd \"%s\"" /* directory */ },
  100. // list directory can be empty on permission denied, this is handled in ReadDirectory
  101. /*ListDirectory*/ { -1, -1, F, F, F, "ls -la \"%s\"" /* directory */ },
  102. /*ListCurrentDirectory*/{ -1, -1, F, F, F, "ls -la" },
  103. /*ListFile*/ { 1, 1, F, F, F, "ls -lad \"%s\"" /* file/directory */ },
  104. /*LookupUserGroups*/ { 1, 1, F, F, F, "groups" },
  105. /*CopyToRemote*/ { -1, -1, T, F, T, "scp -r %s -d -t \"%s\"" /* options, directory */ },
  106. /*CopyToLocal*/ { -1, -1, F, F, T, "scp -r %s -d -f \"%s\"" /* options, file */ },
  107. /*DeleteFile*/ { 0, 0, T, F, F, "rm -f -r \"%s\"" /* file/directory */},
  108. /*RenameFile*/ { 0, 0, T, F, F, "mv -f \"%s\" \"%s\"" /* file/directory, new name*/},
  109. /*CreateDirectory*/ { 0, 0, T, F, F, "mkdir \"%s\"" /* new directory */},
  110. /*ChangeMode*/ { 0, 0, T, F, F, "chmod %s %s \"%s\"" /* options, mode, filename */},
  111. /*ChangeGroup*/ { 0, 0, T, F, F, "chgrp %s \"%s\" \"%s\"" /* options, group, filename */},
  112. /*ChangeOwner*/ { 0, 0, T, F, F, "chown %s \"%s\" \"%s\"" /* options, owner, filename */},
  113. /*HomeDirectory*/ { 0, 0, F, T, F, "cd" },
  114. /*Unset*/ { 0, 0, F, F, F, "unset \"%s\"" /* variable */ },
  115. /*Unalias*/ { 0, 0, F, F, F, "unalias \"%s\"" /* alias */ },
  116. /*AliasGroupList*/ { 0, 0, F, F, F, "alias ls=\"ls -g\"" },
  117. /*CreateLink*/ { 0, 0, T, F, F, "ln %s \"%s\" \"%s\"" /*symbolic (-s), filename, point to*/},
  118. /*AnyCommand*/ { 0, -1, T, T, F, "%s" }
  119. };
  120. #undef F
  121. #undef T
  122. //---------------------------------------------------------------------------
  123. __fastcall TCommandSet::TCommandSet(TSessionData *aSessionData):
  124. FSessionData(aSessionData), FReturnVar("")
  125. {
  126. assert(FSessionData);
  127. Default();
  128. }
  129. //---------------------------------------------------------------------------
  130. void __fastcall TCommandSet::CopyFrom(TCommandSet * Source)
  131. {
  132. memcpy(&CommandSet, Source->CommandSet, sizeof(CommandSet));
  133. }
  134. //---------------------------------------------------------------------------
  135. void __fastcall TCommandSet::Default()
  136. {
  137. assert(sizeof(CommandSet) == sizeof(DefaultCommandSet));
  138. memcpy(&CommandSet, &DefaultCommandSet, sizeof(CommandSet));
  139. }
  140. //---------------------------------------------------------------------------
  141. int __fastcall TCommandSet::GetMaxLines(TFSCommand Cmd)
  142. {
  143. CHECK_CMD;
  144. return CommandSet[Cmd].MaxLines;
  145. }
  146. //---------------------------------------------------------------------------
  147. int __fastcall TCommandSet::GetMinLines(TFSCommand Cmd)
  148. {
  149. CHECK_CMD;
  150. return CommandSet[Cmd].MinLines;
  151. }
  152. //---------------------------------------------------------------------------
  153. bool __fastcall TCommandSet::GetModifiesFiles(TFSCommand Cmd)
  154. {
  155. CHECK_CMD;
  156. return CommandSet[Cmd].ModifiesFiles;
  157. }
  158. //---------------------------------------------------------------------------
  159. bool __fastcall TCommandSet::GetChangesDirectory(TFSCommand Cmd)
  160. {
  161. CHECK_CMD;
  162. return CommandSet[Cmd].ChangesDirectory;
  163. }
  164. //---------------------------------------------------------------------------
  165. bool __fastcall TCommandSet::GetInteractiveCommand(TFSCommand Cmd)
  166. {
  167. CHECK_CMD;
  168. return CommandSet[Cmd].InteractiveCommand;
  169. }
  170. //---------------------------------------------------------------------------
  171. bool __fastcall TCommandSet::GetOneLineCommand(TFSCommand /*Cmd*/)
  172. {
  173. //CHECK_CMD;
  174. // #56: we send "echo last line" from all commands on same line
  175. // just as it was in 1.0
  176. return True; //CommandSet[Cmd].OneLineCommand;
  177. }
  178. //---------------------------------------------------------------------------
  179. void __fastcall TCommandSet::SetCommands(TFSCommand Cmd, AnsiString value)
  180. {
  181. CHECK_CMD;
  182. strcpy(CommandSet[Cmd].Command, value.SubString(1, MaxCommandLen).c_str());
  183. }
  184. //---------------------------------------------------------------------------
  185. AnsiString __fastcall TCommandSet::GetCommands(TFSCommand Cmd)
  186. {
  187. CHECK_CMD;
  188. return CommandSet[Cmd].Command;
  189. }
  190. //---------------------------------------------------------------------------
  191. AnsiString __fastcall TCommandSet::Command(TFSCommand Cmd, const TVarRec * args, int size)
  192. {
  193. if (args) return Format(Commands[Cmd], args, size);
  194. else return Commands[Cmd];
  195. }
  196. //---------------------------------------------------------------------------
  197. AnsiString __fastcall TCommandSet::FullCommand(TFSCommand Cmd, const TVarRec * args, int size)
  198. {
  199. AnsiString Separator;
  200. if (OneLineCommand[Cmd]) Separator = " ; ";
  201. else Separator = "\n";
  202. AnsiString Line = Command(Cmd, args, size);
  203. AnsiString LastLineCmd =
  204. Command(fsLastLine, ARRAYOFCONST((LastLine, ReturnVar)));
  205. AnsiString FirstLineCmd;
  206. if (InteractiveCommand[Cmd])
  207. FirstLineCmd = Command(fsFirstLine, ARRAYOFCONST((FirstLine))) + Separator;
  208. AnsiString Result;
  209. if (!Line.IsEmpty())
  210. Result = FORMAT("%s%s%s%s", (FirstLineCmd, Line, Separator, LastLineCmd));
  211. else
  212. Result = FORMAT("%s%s", (FirstLineCmd, LastLineCmd));
  213. return Result;
  214. }
  215. //---------------------------------------------------------------------------
  216. AnsiString __fastcall TCommandSet::GetFirstLine()
  217. {
  218. return FIRST_LINE;
  219. }
  220. //---------------------------------------------------------------------------
  221. AnsiString __fastcall TCommandSet::GetLastLine()
  222. {
  223. return LAST_LINE;
  224. }
  225. //---------------------------------------------------------------------------
  226. AnsiString __fastcall TCommandSet::GetReturnVar()
  227. {
  228. assert(SessionData);
  229. if (!FReturnVar.IsEmpty()) return AnsiString('$') + FReturnVar;
  230. else
  231. if (SessionData->DetectReturnVar) return '0';
  232. else return AnsiString('$') + SessionData->ReturnVar;
  233. }
  234. //---------------------------------------------------------------------------
  235. TStrings * __fastcall TCommandSet::CreateCommandList()
  236. {
  237. TStrings * CommandList = new TStringList();
  238. for (Integer Index = 0; Index < ShellCommandCount; Index++)
  239. {
  240. AnsiString Cmd = Commands[(TFSCommand)Index];
  241. if (!Cmd.IsEmpty())
  242. {
  243. Integer P = Cmd.Pos(" ");
  244. if (P) Cmd.SetLength(P-1);
  245. if (CommandList->IndexOf(Cmd) < 0)
  246. CommandList->Add(Cmd);
  247. }
  248. }
  249. return CommandList;
  250. }
  251. //===========================================================================
  252. __fastcall TSCPFileSystem::TSCPFileSystem(TTerminal * ATerminal):
  253. TCustomFileSystem(ATerminal)
  254. {
  255. FCommandSet = new TCommandSet(FTerminal->SessionData);
  256. FOutput = new TStringList();
  257. }
  258. //---------------------------------------------------------------------------
  259. __fastcall TSCPFileSystem::~TSCPFileSystem()
  260. {
  261. delete FCommandSet;
  262. delete FOutput;
  263. }
  264. //---------------------------------------------------------------------------
  265. AnsiString __fastcall TSCPFileSystem::GetProtocolName() const
  266. {
  267. return "SCP";
  268. }
  269. //---------------------------------------------------------------------------
  270. bool __fastcall TSCPFileSystem::IsCapable(int Capability) const
  271. {
  272. assert(FTerminal);
  273. switch (Capability) {
  274. case fcUserGroupListing:
  275. case fcModeChanging:
  276. case fcGroupChanging:
  277. case fcOwnerChanging:
  278. case fcAnyCommand:
  279. case fcHardLink:
  280. case fcSymbolicLink:
  281. case fcResolveSymlink:
  282. return true;
  283. case fcTextMode:
  284. return FTerminal->SessionData->EOLType != FTerminal->Configuration->LocalEOLType;
  285. default:
  286. assert(false);
  287. return false;
  288. }
  289. }
  290. //---------------------------------------------------------------------------
  291. AnsiString __fastcall TSCPFileSystem::DelimitStr(AnsiString Str)
  292. {
  293. if (!Str.IsEmpty())
  294. {
  295. #define DELIMITCHAR(C) { \
  296. Integer P, X = 0; \
  297. while ((P = Str.SubString(X+1, Str.Length() - X).Pos(C)) != 0) { \
  298. Str.Insert("\\", X+P); \
  299. X += P+1; } \
  300. }
  301. DELIMITCHAR('\\');
  302. DELIMITCHAR('`');
  303. DELIMITCHAR('$');
  304. DELIMITCHAR('"');
  305. // #62 19.10.2001: delimiting ! doesn't work on BASH
  306. //DELIMITCHAR('!');
  307. #undef DELIMITCHAR
  308. if (Str[1] == '-') Str = "./"+Str;
  309. }
  310. return Str;
  311. }
  312. //---------------------------------------------------------------------------
  313. void __fastcall TSCPFileSystem::SendCommand(const AnsiString Cmd)
  314. {
  315. AnsiString Line;
  316. FTerminal->ClearStdError();
  317. FReturnCode = 0;
  318. FOutput->Clear();
  319. // We suppose, that 'Cmd' already contains command that ensures,
  320. // that 'LastLine' will be printed
  321. FTerminal->SendLine(Cmd);
  322. }
  323. //---------------------------------------------------------------------------
  324. bool __fastcall TSCPFileSystem::IsTotalListingLine(const AnsiString Line)
  325. {
  326. // On some hosts there is not "total" but "totalt". What's the reason??
  327. // see mail from "Jan Wiklund (SysOp)" <[email protected]>
  328. return !Line.SubString(1, 5).AnsiCompareIC("total");
  329. }
  330. //---------------------------------------------------------------------------
  331. bool __fastcall TSCPFileSystem::RemoveLastLine(AnsiString & Line,
  332. int & ReturnCode, AnsiString LastLine)
  333. {
  334. bool IsLastLine = false;
  335. if (LastLine.IsEmpty()) LastLine = LAST_LINE;
  336. // #55: fixed so, even when last line of command output does not
  337. // contain CR/LF, we can recognize last line
  338. int Pos = Line.Pos(LastLine);
  339. if (Pos)
  340. {
  341. // 2003-07-14: There must be nothing after return code number to
  342. // consider string as last line. This fixes bug with 'set' command
  343. // in console window
  344. AnsiString ReturnCodeStr = Line.SubString(Pos + LastLine.Length() + 1,
  345. Line.Length() - Pos + LastLine.Length());
  346. if (TryStrToInt(ReturnCodeStr, ReturnCode))
  347. {
  348. IsLastLine = true;
  349. Line.SetLength(Pos - 1);
  350. }
  351. }
  352. return IsLastLine;
  353. }
  354. //---------------------------------------------------------------------------
  355. bool __fastcall TSCPFileSystem::IsLastLine(AnsiString & Line)
  356. {
  357. bool Result = false;
  358. try
  359. {
  360. Result = RemoveLastLine(Line, FReturnCode, FCommandSet->LastLine);
  361. }
  362. catch (Exception &E)
  363. {
  364. FTerminal->TerminalError(&E, LoadStr(CANT_DETECT_RETURN_CODE));
  365. }
  366. return Result;
  367. }
  368. //---------------------------------------------------------------------------
  369. void __fastcall TSCPFileSystem::SkipFirstLine()
  370. {
  371. AnsiString Line = FTerminal->ReceiveLine();
  372. if (Line != FCommandSet->FirstLine)
  373. {
  374. FTerminal->TerminalError(NULL, FMTLOAD(FIRST_LINE_EXPECTED, (Line)));
  375. }
  376. }
  377. //---------------------------------------------------------------------------
  378. void __fastcall TSCPFileSystem::ReadCommandOutput(int Params)
  379. {
  380. if (Params & coWaitForLastLine)
  381. {
  382. AnsiString Line;
  383. bool IsLast;
  384. // #55: fixed so, even when last line of command output does not
  385. // contain CR/LF, we can recognize last line
  386. do
  387. {
  388. Line = FTerminal->ReceiveLine();
  389. IsLast = IsLastLine(Line);
  390. if (!IsLast || !Line.IsEmpty()) FOutput->Add(Line);
  391. }
  392. while (!IsLast);
  393. }
  394. if (Params & coRaiseExcept)
  395. {
  396. AnsiString Message = FTerminal->StdError;
  397. if ((Params & coExpectNoOutput) && FOutput->Count)
  398. {
  399. if (!Message.IsEmpty()) Message += "\n";
  400. Message += FOutput->Text;
  401. }
  402. while (!Message.IsEmpty() && (Message.LastDelimiter("\n\r") == Message.Length()))
  403. Message.SetLength(Message.Length() - 1);
  404. bool WrongReturnCode =
  405. (ReturnCode > 1) || (ReturnCode == 1 && !(Params & coIgnoreWarnings));
  406. if (Params & coOnlyReturnCode && WrongReturnCode)
  407. {
  408. FTerminal->TerminalError(FMTLOAD(COMMAND_FAILED_CODEONLY, (ReturnCode)));
  409. }
  410. else
  411. if (!(Params & coOnlyReturnCode) &&
  412. ((!Message.IsEmpty() && !(Params & coIgnoreWarnings)) ||
  413. WrongReturnCode))
  414. {
  415. FTerminal->TerminalError(FMTLOAD(COMMAND_FAILED, ("%s", ReturnCode, Message)));
  416. }
  417. }
  418. }
  419. //---------------------------------------------------------------------------
  420. void __fastcall TSCPFileSystem::ExecCommand(const AnsiString Cmd, int Params)
  421. {
  422. if (Params < 0) Params = ecRaiseExcept;
  423. if (FTerminal->UseBusyCursor)
  424. {
  425. Busy(true);
  426. }
  427. try
  428. {
  429. SendCommand(Cmd);
  430. try
  431. {
  432. int COParams = coWaitForLastLine;
  433. if (Params & ecRaiseExcept) COParams |= coRaiseExcept;
  434. if (Params & ecIgnoreWarnings) COParams |= coIgnoreWarnings;
  435. ReadCommandOutput(COParams);
  436. }
  437. catch (ETerminal &E)
  438. {
  439. AnsiString OnlyCmd = Cmd;
  440. Integer P = OnlyCmd.Pos('\n');
  441. if (!P) P = OnlyCmd.Pos(";");
  442. if (P) OnlyCmd.Delete(P, Cmd.Length() - P + 1);
  443. FTerminal->TerminalError(FORMAT(E.Message, (OnlyCmd.Trim())));
  444. }
  445. }
  446. __finally
  447. {
  448. if (FTerminal->UseBusyCursor)
  449. {
  450. Busy(false);
  451. }
  452. }
  453. }
  454. //---------------------------------------------------------------------------
  455. void __fastcall TSCPFileSystem::ExecCommand(TFSCommand Cmd, const TVarRec * args,
  456. int size, int Params)
  457. {
  458. if (Params < 0) Params = ecRaiseExcept;
  459. AnsiString FullCommand = FCommandSet->FullCommand(Cmd, args, size);
  460. if (FTerminal->SessionData->IgnoreLsWarnings &&
  461. (Cmd == fsListDirectory || Cmd == fsListCurrentDirectory ||
  462. Cmd == fsListFile))
  463. {
  464. Params |= ecIgnoreWarnings;
  465. }
  466. ExecCommand(FullCommand, Params);
  467. if (Params & ecRaiseExcept)
  468. {
  469. Integer MinL = FCommandSet->MinLines[Cmd];
  470. Integer MaxL = FCommandSet->MaxLines[Cmd];
  471. if (((MinL >= 0) && (MinL > FOutput->Count)) ||
  472. ((MaxL >= 0) && (MaxL > FOutput->Count)))
  473. {
  474. FTerminal->TerminalError(FmtLoadStr(INVALID_OUTPUT_ERROR,
  475. ARRAYOFCONST((FullCommand, Output->Text))));
  476. }
  477. }
  478. }
  479. //---------------------------------------------------------------------------
  480. void __fastcall TSCPFileSystem::SetCurrentDirectory(AnsiString value)
  481. {
  482. assert(false);
  483. }
  484. //---------------------------------------------------------------------------
  485. AnsiString __fastcall TSCPFileSystem::GetCurrentDirectory()
  486. {
  487. return FCurrentDirectory;
  488. }
  489. //---------------------------------------------------------------------------
  490. void __fastcall TSCPFileSystem::DoStartup()
  491. {
  492. // SkipStartupMessage and DetectReturnVar must succeed,
  493. // otherwise session is to be closed.
  494. FTerminal->ExceptionOnFail = true;
  495. SkipStartupMessage();
  496. if (FTerminal->SessionData->DetectReturnVar) DetectReturnVar();
  497. FTerminal->ExceptionOnFail = false;
  498. #define COND_OPER(OPER) if (FTerminal->SessionData->OPER) OPER()
  499. COND_OPER(ClearAliases);
  500. COND_OPER(UnsetNationalVars);
  501. COND_OPER(AliasGroupList);
  502. #undef COND_OPER
  503. }
  504. //---------------------------------------------------------------------------
  505. void __fastcall TSCPFileSystem::SkipStartupMessage()
  506. {
  507. try
  508. {
  509. FTerminal->LogEvent("Skipping host startup message (if any).");
  510. ExecCommand(fsNull, NULL, 0, 0);
  511. }
  512. catch (Exception & E)
  513. {
  514. FTerminal->CommandError(&E, LoadStr(SKIP_STARTUP_MESSAGE_ERROR));
  515. }
  516. }
  517. //---------------------------------------------------------------------------
  518. void __fastcall TSCPFileSystem::LookupUserGroups()
  519. {
  520. ExecCommand(fsLookupUserGroups);
  521. FTerminal->FUserGroups->Clear();
  522. FTerminal->FUserGroups->BeginUpdate();
  523. try
  524. {
  525. AnsiString Groups = FOutput->Strings[0];
  526. while (!Groups.IsEmpty())
  527. {
  528. AnsiString NewGroup = CutToChar(Groups, ' ', False);
  529. FTerminal->FUserGroups->Add(NewGroup);
  530. }
  531. }
  532. __finally
  533. {
  534. FTerminal->FUserGroups->EndUpdate();
  535. }
  536. }
  537. //---------------------------------------------------------------------------
  538. void __fastcall TSCPFileSystem::DetectReturnVar()
  539. {
  540. // This suppose that something was already executed (probably SkipStartupMessage())
  541. // or return code variable is already set on start up.
  542. try
  543. {
  544. // #60 17.10.01: "status" and "?" switched
  545. AnsiString ReturnVars[2] = { "status", "?" };
  546. AnsiString NewReturnVar = "";
  547. FTerminal->LogEvent("Detecting variable containing return code of last command.");
  548. for (int Index = 0; Index < 2; Index++)
  549. {
  550. bool Success = true;
  551. try
  552. {
  553. FTerminal->LogEvent(FORMAT("Trying \"$%s\".", (ReturnVars[Index])));
  554. ExecCommand(fsVarValue, ARRAYOFCONST((ReturnVars[Index])));
  555. if ((Output->Count != 1) || (StrToIntDef(Output->Strings[0], 256) > 255)) Abort();
  556. }
  557. catch (EFatal &E)
  558. {
  559. // if fatal error occurs, we need to exit ...
  560. throw;
  561. }
  562. catch (Exception &E)
  563. {
  564. // ...otherwise, we will try next variable (if any)
  565. Success = false;
  566. }
  567. if (Success)
  568. {
  569. NewReturnVar = ReturnVars[Index];
  570. break;
  571. }
  572. }
  573. if (NewReturnVar.IsEmpty())
  574. {
  575. Abort();
  576. }
  577. else
  578. {
  579. FCommandSet->ReturnVar = NewReturnVar;
  580. FTerminal->LogEvent(FORMAT("Return code variable \"%s\" selected.",
  581. (FCommandSet->ReturnVar)));
  582. }
  583. }
  584. catch (Exception &E)
  585. {
  586. FTerminal->CommandError(&E, LoadStr(DETECT_RETURNVAR_ERROR));
  587. }
  588. }
  589. //---------------------------------------------------------------------------
  590. void __fastcall TSCPFileSystem::ClearAliases()
  591. {
  592. try
  593. {
  594. FTerminal->LogEvent("Clearing all aliases.");
  595. TStrings * CommandList = FCommandSet->CreateCommandList();
  596. try
  597. {
  598. for (int Index = 0; Index < CommandList->Count; Index++)
  599. {
  600. // this command usually fails, becouse there will never be
  601. // aliases on all commands -> see last False parametr
  602. ExecCommand(fsUnalias, ARRAYOFCONST((CommandList->Strings[Index])), false);
  603. }
  604. }
  605. __finally
  606. {
  607. delete CommandList;
  608. }
  609. }
  610. catch (Exception &E)
  611. {
  612. FTerminal->CommandError(&E, LoadStr(UNALIAS_ALL_ERROR));
  613. }
  614. }
  615. //---------------------------------------------------------------------------
  616. void __fastcall TSCPFileSystem::AliasGroupList()
  617. {
  618. try
  619. {
  620. FTerminal->LogEvent("Aliasing LS to display file group.");
  621. ExecCommand(fsAliasGroupList);
  622. }
  623. catch (Exception &E)
  624. {
  625. FTerminal->CommandError(&E, LoadStr(ALIAS_GROUPLIST_ERROR));
  626. }
  627. }
  628. //---------------------------------------------------------------------------
  629. void __fastcall TSCPFileSystem::UnsetNationalVars()
  630. {
  631. try
  632. {
  633. FTerminal->LogEvent("Clearing national user variables.");
  634. for (int Index = 0; Index < NationalVarCount; Index++)
  635. {
  636. ExecCommand(fsUnset, ARRAYOFCONST((NationalVars[Index])), false);
  637. }
  638. }
  639. catch (Exception &E)
  640. {
  641. FTerminal->CommandError(&E, LoadStr(UNSET_NATIONAL_ERROR));
  642. }
  643. }
  644. //---------------------------------------------------------------------------
  645. void __fastcall TSCPFileSystem::ReadCurrentDirectory()
  646. {
  647. ExecCommand(fsCurrentDirectory);
  648. FCurrentDirectory = UnixExcludeTrailingBackslash(FOutput->Strings[0]);
  649. }
  650. //---------------------------------------------------------------------------
  651. void __fastcall TSCPFileSystem::HomeDirectory()
  652. {
  653. ExecCommand(fsHomeDirectory);
  654. }
  655. //---------------------------------------------------------------------------
  656. void __fastcall TSCPFileSystem::ChangeDirectory(const AnsiString Directory)
  657. {
  658. ExecCommand(fsChangeDirectory, ARRAYOFCONST((DelimitStr(Directory))));
  659. }
  660. //---------------------------------------------------------------------------
  661. void __fastcall TSCPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  662. {
  663. assert(FileList);
  664. TStringList * OutputCopy = NULL;
  665. try
  666. {
  667. if (FileList->Directory == FTerminal->CurrentDirectory)
  668. {
  669. FTerminal->LogEvent("Listing current directory.");
  670. ExecCommand(fsListCurrentDirectory);
  671. }
  672. else
  673. {
  674. FTerminal->LogEvent(FORMAT("Listing directory \"%s\".",
  675. (FileList->Directory)));
  676. ExecCommand(fsListDirectory, ARRAYOFCONST((DelimitStr(FileList->Directory))));
  677. }
  678. FileList->Clear();
  679. TRemoteFile * File;
  680. // If output is not empty, we have succesfully got file listing,
  681. // otherwise there was an error, in case it was "permission denied"
  682. // we try to get at least parent directory (see "else" statement below)
  683. if (FOutput->Count > 0)
  684. {
  685. // Copy LS command output, because eventual symlink analysis would
  686. // modify FTerminal->Output
  687. OutputCopy = new TStringList();
  688. OutputCopy->Assign(FOutput);
  689. // delete leading "total xxx" line
  690. // On some hosts there is not "total" but "totalt". What's the reason??
  691. // see mail from "Jan Wiklund (SysOp)" <[email protected]>
  692. if (IsTotalListingLine(OutputCopy->Strings[0]))
  693. {
  694. OutputCopy->Delete(0);
  695. }
  696. for (int Index = 0; Index < OutputCopy->Count; Index++)
  697. {
  698. File = new TRemoteFile();
  699. File->Terminal = FTerminal;
  700. File->ListingStr = OutputCopy->Strings[Index];
  701. File->ShiftTime(FTerminal->SessionData->TimeDifference);
  702. FileList->AddFile(File);
  703. }
  704. }
  705. else
  706. {
  707. // Empty file list -> probably "permision denied", we
  708. // at least get link to parent directory ("..")
  709. FTerminal->ReadFile(
  710. UnixIncludeTrailingBackslash(FTerminal->FFiles->Directory) +
  711. PARENTDIRECTORY, File);
  712. assert(File->IsParentDirectory);
  713. FileList->AddFile(File);
  714. }
  715. }
  716. __finally
  717. {
  718. delete OutputCopy;
  719. }
  720. }
  721. //---------------------------------------------------------------------------
  722. void __fastcall TSCPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  723. TRemoteFile *& File)
  724. {
  725. CustomReadFile(SymlinkFile->LinkTo, File, SymlinkFile);
  726. }
  727. //---------------------------------------------------------------------------
  728. void __fastcall TSCPFileSystem::ReadFile(const AnsiString FileName,
  729. TRemoteFile *& File)
  730. {
  731. CustomReadFile(FileName, File, NULL);
  732. }
  733. //---------------------------------------------------------------------------
  734. void __fastcall TSCPFileSystem::CustomReadFile(const AnsiString FileName,
  735. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  736. {
  737. File = NULL;
  738. ExecCommand(fsListFile, ARRAYOFCONST((DelimitStr(FileName))));
  739. if (FOutput->Count)
  740. {
  741. int LineIndex = 0;
  742. if (IsTotalListingLine(FOutput->Strings[LineIndex]) && FOutput->Count > 1)
  743. {
  744. LineIndex++;
  745. }
  746. File = new TRemoteFile(ALinkedByFile);
  747. try
  748. {
  749. File->Terminal = FTerminal;
  750. File->ListingStr = FOutput->Strings[LineIndex];
  751. }
  752. catch(...)
  753. {
  754. delete File;
  755. File = NULL;
  756. throw;
  757. }
  758. }
  759. }
  760. //---------------------------------------------------------------------------
  761. void __fastcall TSCPFileSystem::DeleteFile(const AnsiString FileName,
  762. const TRemoteFile * File, bool Recursive)
  763. {
  764. assert(Recursive || (File && File->IsSymLink));
  765. ExecCommand(fsDeleteFile, ARRAYOFCONST((DelimitStr(FileName))));
  766. }
  767. //---------------------------------------------------------------------------
  768. void __fastcall TSCPFileSystem::RenameFile(const AnsiString FileName,
  769. const AnsiString NewName)
  770. {
  771. ExecCommand(fsRenameFile, ARRAYOFCONST((DelimitStr(FileName), DelimitStr(NewName))));
  772. }
  773. //---------------------------------------------------------------------------
  774. void __fastcall TSCPFileSystem::CreateDirectory(const AnsiString DirName,
  775. const TRemoteProperties * Properties)
  776. {
  777. assert(!Properties); // not implemented yet
  778. ExecCommand(fsCreateDirectory, ARRAYOFCONST((DelimitStr(DirName))));
  779. }
  780. //---------------------------------------------------------------------------
  781. void __fastcall TSCPFileSystem::CreateLink(const AnsiString FileName,
  782. const AnsiString PointTo, bool Symbolic)
  783. {
  784. ExecCommand(fsCreateLink,
  785. ARRAYOFCONST((Symbolic ? "-s" : "", DelimitStr(PointTo), DelimitStr(FileName))));
  786. }
  787. //---------------------------------------------------------------------------
  788. void __fastcall TSCPFileSystem::ChangeFileProperties(const AnsiString FileName,
  789. const TRemoteFile * File, const TRemoteProperties * Properties)
  790. {
  791. assert(Properties);
  792. bool IsDirectory = File && File->IsDirectory;
  793. bool Recursive = Properties->Recursive && IsDirectory;
  794. AnsiString RecursiveStr = Recursive ? "-R" : "";
  795. AnsiString DelimitedName = DelimitStr(FileName);
  796. if (Properties->Valid.Contains(vpRights))
  797. {
  798. TRights Rights = Properties->Rights;
  799. // if we don't set modes recursively, we may add X at once with other
  800. // options. Otherwise we have to add X after recusive command
  801. if (!Recursive && IsDirectory && Properties->AddXToDirectories)
  802. Rights.AddExecute();
  803. ExecCommand(fsChangeMode,
  804. ARRAYOFCONST((RecursiveStr, Rights.SimplestStr, DelimitedName)));
  805. // if file is directory and we do recursive mode settings with
  806. // add-x-to-directories option on, add those X
  807. if (Recursive && IsDirectory && Properties->AddXToDirectories)
  808. {
  809. Rights.AddExecute();
  810. ExecCommand(fsChangeMode,
  811. ARRAYOFCONST(("", Rights.SimplestStr, DelimitedName)));
  812. }
  813. }
  814. if (Properties->Valid.Contains(vpGroup))
  815. {
  816. ExecCommand(fsChangeGroup,
  817. ARRAYOFCONST((RecursiveStr, Properties->Group, DelimitedName)));
  818. }
  819. if (Properties->Valid.Contains(vpOwner))
  820. {
  821. ExecCommand(fsChangeOwner,
  822. ARRAYOFCONST((RecursiveStr, DelimitStr(Properties->Owner), DelimitedName)));
  823. }
  824. }
  825. //---------------------------------------------------------------------------
  826. void __fastcall TSCPFileSystem::CustomCommandOnFile(const AnsiString FileName,
  827. const TRemoteFile * File, AnsiString Command)
  828. {
  829. assert(File);
  830. if (File->IsDirectory && !File->IsSymLink)
  831. {
  832. FTerminal->ProcessDirectory(FileName, FTerminal->CustomCommandOnFile, &Command);
  833. }
  834. else
  835. {
  836. AnsiString Cmd = Command;
  837. int LastP = 0;
  838. int P;
  839. do
  840. {
  841. P = Cmd.SubString(LastP + 1, Cmd.Length() - LastP).Pos(CustomCommandFileNamePattern);
  842. if (P)
  843. {
  844. LastP += P;
  845. if ((Cmd.Length() > LastP) && (Cmd[LastP + 1] == '!'))
  846. {
  847. LastP++;
  848. }
  849. else
  850. {
  851. Cmd.Delete(LastP, strlen(CustomCommandFileNamePattern));
  852. Cmd.Insert(FileName, LastP);
  853. LastP += FileName.Length() - strlen(CustomCommandFileNamePattern);
  854. }
  855. }
  856. }
  857. while (P);
  858. AnyCommand(Cmd);
  859. }
  860. }
  861. //---------------------------------------------------------------------------
  862. void __fastcall TSCPFileSystem::AnyCommand(const AnsiString Command)
  863. {
  864. ExecCommand(fsAnyCommand, ARRAYOFCONST((Command)));
  865. }
  866. //---------------------------------------------------------------------------
  867. // transfer protocol
  868. //---------------------------------------------------------------------------
  869. void __fastcall TSCPFileSystem::SCPResponse()
  870. {
  871. // Taken from scp.c response() and modified
  872. char Resp;
  873. FTerminal->Receive(&Resp, 1);
  874. switch (Resp)
  875. {
  876. case 0: /* ok */
  877. FTerminal->LogEvent("SCP remote side confirmation (0)");
  878. return;
  879. default:
  880. case 1: /* error */
  881. case 2: /* fatal error */
  882. // pscp adds 'Resp' to 'Msg', why?
  883. AnsiString Msg = FTerminal->ReceiveLine();
  884. AnsiString Line = AnsiString(Resp) + Msg;
  885. if (IsLastLine(Line))
  886. {
  887. /* TODO 1 : Show stderror to user? */
  888. FTerminal->ClearStdError();
  889. ReadCommandOutput(coExpectNoOutput | coRaiseExcept | coOnlyReturnCode);
  890. }
  891. else
  892. if (Resp == 1)
  893. {
  894. FTerminal->LogEvent("SCP remote side error (1):");
  895. }
  896. else
  897. {
  898. FTerminal->LogEvent("SCP remote side fatal error (2):");
  899. }
  900. if (Resp == 1)
  901. {
  902. THROW_FILE_SKIPPED(NULL, Msg);
  903. }
  904. else
  905. {
  906. THROW_SCP_ERROR(NULL, Msg);
  907. }
  908. }
  909. }
  910. //---------------------------------------------------------------------------
  911. void __fastcall TSCPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  912. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  913. int Params, TFileOperationProgressType * OperationProgress,
  914. bool & DisconnectWhenComplete)
  915. {
  916. // scp.c: source(), toremote()
  917. assert(FilesToCopy && OperationProgress);
  918. AnsiString Options = "";
  919. bool CheckExistence = UnixComparePaths(TargetDir, FTerminal->CurrentDirectory);
  920. bool CopyBatchStarted = false;
  921. bool Failed = true;
  922. if (CopyParam->PreserveRights) Options = "-p";
  923. if (FTerminal->SessionData->Scp1Compatibility) Options += " -1";
  924. SendCommand(FCommandSet->FullCommand(fsCopyToRemote,
  925. ARRAYOFCONST((Options, DelimitStr(UnixExcludeTrailingBackslash(TargetDir))))));
  926. SkipFirstLine();
  927. try
  928. {
  929. SCPResponse();
  930. CopyBatchStarted = true;
  931. for (int IFile = 0; (IFile < FilesToCopy->Count) &&
  932. !OperationProgress->Cancel; IFile++)
  933. {
  934. AnsiString FileName = FilesToCopy->Strings[IFile];
  935. bool CanProceed;
  936. AnsiString FileNameOnly =
  937. CopyParam->ChangeFileName(ExtractFileName(FileName), osLocal);
  938. if (CheckExistence)
  939. {
  940. assert(FTerminal->FFiles && FTerminal->FFiles->Loaded);
  941. TRemoteFile * File = FTerminal->FFiles->FindFile(FileNameOnly);
  942. if (File && OperationProgress->NoToAll)
  943. {
  944. CanProceed = false;
  945. }
  946. else
  947. if (File && !OperationProgress->YesToAll &&
  948. FTerminal->Configuration->ConfirmOverwriting && !(Params & cpNoConfirmation))
  949. {
  950. AnsiString QuestionFmt;
  951. if (File->IsDirectory) QuestionFmt = LoadStr(DIRECTORY_OVERWRITE);
  952. else QuestionFmt = LoadStr(FILE_OVERWRITE);
  953. int Answer;
  954. SUSPEND_OPERATION (
  955. Answer = FTerminal->DoQueryUser(FORMAT(QuestionFmt, (FileNameOnly)),
  956. qaYes | qaNo | qaAbort | qaYesToAll | qaNoToAll,
  957. qpNeverAskAgainCheck);
  958. );
  959. switch (Answer) {
  960. case qaNeverAskAgain:
  961. FTerminal->Configuration->ConfirmOverwriting = false;
  962. case qaYesToAll:
  963. OperationProgress->YesToAll = true;
  964. case qaYes:
  965. CanProceed = true;
  966. break;
  967. case qaAbort:
  968. if (!OperationProgress->Cancel) OperationProgress->Cancel = csCancel;
  969. case qaNoToAll:
  970. OperationProgress->NoToAll = true;
  971. case qaNo:
  972. CanProceed = false;
  973. break;
  974. }
  975. }
  976. else CanProceed = true;
  977. }
  978. else CanProceed = true;
  979. if (CanProceed)
  980. {
  981. if (FTerminal->SessionData->CacheDirectories)
  982. {
  983. FTerminal->DirectoryModified(TargetDir, false);
  984. if (DirectoryExists(FileName))
  985. {
  986. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  987. FileNameOnly, true);
  988. }
  989. }
  990. AnsiString OrigFileNameOnly = ExtractFileName(FileName);
  991. try
  992. {
  993. SCPSource(FileName, CopyParam, Params, OperationProgress);
  994. OperationProgress->Finish(OrigFileNameOnly, true, DisconnectWhenComplete);
  995. }
  996. catch (EScpFileSkipped &E)
  997. {
  998. SUSPEND_OPERATION (
  999. if (FTerminal->DoQueryUser(FMTLOAD(COPY_ERROR, (FileName)), E.Message,
  1000. qaOK | qaAbort, qpAllowContinueOnError) == qaAbort)
  1001. {
  1002. OperationProgress->Cancel = csCancel;
  1003. }
  1004. OperationProgress->Finish(OrigFileNameOnly, false, DisconnectWhenComplete);
  1005. if (!FTerminal->HandleException(&E)) throw;
  1006. );
  1007. }
  1008. catch (EScpSkipFile &E)
  1009. {
  1010. OperationProgress->Finish(OrigFileNameOnly, false, DisconnectWhenComplete);
  1011. // If ESkipFile occurs, just log it and continue with next file
  1012. SUSPEND_OPERATION (
  1013. if (!FTerminal->HandleException(&E)) throw;
  1014. );
  1015. }
  1016. catch (...)
  1017. {
  1018. OperationProgress->Finish(OrigFileNameOnly, false, DisconnectWhenComplete);
  1019. throw;
  1020. }
  1021. }
  1022. }
  1023. Failed = false;
  1024. }
  1025. __finally
  1026. {
  1027. // Tell remote side, that we're done.
  1028. if (FTerminal->Active)
  1029. {
  1030. try
  1031. {
  1032. if (CopyBatchStarted)
  1033. {
  1034. // What about case, remote side sends fatal error ???
  1035. // (Not sure, if it causes remote side to terminate scp)
  1036. FTerminal->SendLine("E");
  1037. SCPResponse();
  1038. };
  1039. /* TODO 1 : Show stderror to user? */
  1040. FTerminal->ClearStdError();
  1041. ReadCommandOutput(coExpectNoOutput | coWaitForLastLine | coOnlyReturnCode |
  1042. (Failed ? 0 : coRaiseExcept));
  1043. }
  1044. catch (Exception &E)
  1045. {
  1046. // Only show error message (it should always succeed, but
  1047. // some pending error maybe in queque) }
  1048. HandleExtendedException(&E, this);
  1049. }
  1050. }
  1051. }
  1052. }
  1053. //---------------------------------------------------------------------------
  1054. void __fastcall TSCPFileSystem::SCPSource(const AnsiString FileName,
  1055. const TCopyParamType * CopyParam, int Params,
  1056. TFileOperationProgressType * OperationProgress)
  1057. {
  1058. AnsiString DestFileName = CopyParam->ChangeFileName(ExtractFileName(FileName), osLocal);
  1059. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  1060. OperationProgress->SetFile(FileName);
  1061. HANDLE File;
  1062. int Attrs;
  1063. unsigned long MTime, ATime;
  1064. __int64 Size;
  1065. FTerminal->OpenLocalFile(FileName, GENERIC_READ,
  1066. &Attrs, &File, NULL, &MTime, &ATime, &Size);
  1067. if (Attrs & faDirectory)
  1068. {
  1069. SCPDirectorySource(FileName, CopyParam, Params, OperationProgress);
  1070. }
  1071. else
  1072. try
  1073. {
  1074. assert(File);
  1075. // File is regular file (not directory)
  1076. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  1077. OperationProgress->SetLocalSize(Size);
  1078. // Suppose same data size to transfer as to read
  1079. // (not true with ASCII transfer)
  1080. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1081. OperationProgress->TransferingFile = false;
  1082. // Will we use ASCII of BINARY file tranfer?
  1083. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(FileName));
  1084. FTerminal->LogEvent(
  1085. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  1086. " transfer mode selected.");
  1087. try
  1088. {
  1089. // During ASCII transfer we will load whole file to this buffer
  1090. // than convert EOL and send it at once, because before converting EOL
  1091. // we can't know its size
  1092. TFileBuffer AsciiBuf;
  1093. do
  1094. {
  1095. // Buffer for one block of data
  1096. TFileBuffer BlockBuf;
  1097. // This is crucial, if it fails during file transfer, it's fatal error
  1098. FILE_OPERATION_LOOP (FileName, FMTLOAD(READ_ERROR, (FileName)),
  1099. BlockBuf.LoadFile(File, OperationProgress->LocalBlockSize(), true);
  1100. );
  1101. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  1102. // We do ASCII transfer: convert EOL of current block
  1103. // (we don't convert whole buffer, cause it would produce
  1104. // huge memory-transfers while inserting/deleting EOL characters)
  1105. // Than we add current block to file buffer
  1106. if (OperationProgress->AsciiTransfer)
  1107. {
  1108. BlockBuf.ConvertEOL(FTerminal->Configuration->LocalEOLType,
  1109. FTerminal->SessionData->EOLType);
  1110. BlockBuf.Memory->Seek(0, soFromBeginning);
  1111. AsciiBuf.ReadStream(BlockBuf.Memory, BlockBuf.Size, true);
  1112. // We don't need it any more
  1113. BlockBuf.Memory->Clear();
  1114. // Calculate total size to sent (assume that ratio between
  1115. // size of source and size of EOL-transformed data would remain same)
  1116. // First check if file contains anything (div by zero!)
  1117. if (OperationProgress->LocalyUsed)
  1118. {
  1119. __int64 X = OperationProgress->LocalSize;
  1120. X *= AsciiBuf.Size;
  1121. X /= OperationProgress->LocalyUsed;
  1122. OperationProgress->SetTransferSize(X);
  1123. }
  1124. else
  1125. {
  1126. OperationProgress->SetTransferSize(0);
  1127. }
  1128. }
  1129. // We send file information on first pass during BINARY transfer
  1130. // and on last pass during ASCII transfer
  1131. // BINARY: We succeeded reading first buffer from file, hopefully
  1132. // we will be able to read whole, so we send file info to remote side
  1133. // This is done, because when reading fails we can't interrupt sending
  1134. // (don't know how to tell other side that it failed)
  1135. if (!OperationProgress->TransferingFile &&
  1136. (!OperationProgress->AsciiTransfer || OperationProgress->IsLocalyDone()))
  1137. {
  1138. AnsiString Buf;
  1139. if (CopyParam->PreserveTime)
  1140. {
  1141. // Send last file access and modification time
  1142. // TVarRec don't understand 'unsigned int' -> we use sprintf()
  1143. Buf.sprintf("T%lu 0 %lu 0", MTime, ATime);
  1144. FTerminal->SendLine(Buf);
  1145. SCPResponse();
  1146. }
  1147. // Send file modes (rights), filesize and file name
  1148. // TVarRec don't understand 'unsigned int' -> we use sprintf()
  1149. Buf.sprintf("C0%s %Ld %s",
  1150. CopyParam->RemoteFileRights(Attrs).Octal.data(),
  1151. (OperationProgress->AsciiTransfer ? (__int64)AsciiBuf.Size :
  1152. OperationProgress->LocalSize),
  1153. DestFileName.data());
  1154. FTerminal->SendLine(Buf);
  1155. SCPResponse();
  1156. // Indicate we started transfering file, we need to finish it
  1157. // If not, it's fatal error
  1158. OperationProgress->TransferingFile = true;
  1159. // If we're doing ASCII transfer, this is last pass
  1160. // so we send whole file
  1161. /* TODO : We can't send file above 32bit size in ASCII mode! */
  1162. if (OperationProgress->AsciiTransfer)
  1163. {
  1164. FTerminal->LogEvent(FORMAT("Sending ASCII data (%ud bytes)",
  1165. (AsciiBuf.Size)));
  1166. // Should be equal, just in case it's rounded (see above)
  1167. OperationProgress->SetTransferSize(AsciiBuf.Size);
  1168. while (!OperationProgress->IsTransferDone())
  1169. {
  1170. FTerminal->Send(
  1171. AsciiBuf.Data + (unsigned int)OperationProgress->TransferedSize,
  1172. OperationProgress->TransferBlockSize());
  1173. OperationProgress->AddTransfered(OperationProgress->TransferBlockSize());
  1174. }
  1175. }
  1176. }
  1177. // At end of BINARY transfer pass, send current block
  1178. if (!OperationProgress->AsciiTransfer)
  1179. {
  1180. if (!OperationProgress->TransferedSize)
  1181. {
  1182. FTerminal->LogEvent("Sending BINARY data (first block)");
  1183. }
  1184. FTerminal->Send(BlockBuf.Data, BlockBuf.Size);
  1185. OperationProgress->AddTransfered(BlockBuf.Size);
  1186. }
  1187. if ((OperationProgress->Cancel == csCancelTransfer) ||
  1188. (OperationProgress->Cancel == csCancel && !OperationProgress->TransferingFile))
  1189. {
  1190. throw Exception(USER_TERMINATED);
  1191. }
  1192. }
  1193. while (!OperationProgress->IsLocalyDone() || !OperationProgress->IsTransferDone());
  1194. FTerminal->SendNull();
  1195. try
  1196. {
  1197. SCPResponse();
  1198. // If one of two following exceptions occurs, is means, that remote
  1199. // side already know, that file transfer finished, even if it failed
  1200. // so we don't have to throw EFatal
  1201. }
  1202. catch (EScp &E)
  1203. {
  1204. // SCP protocol fatal error
  1205. OperationProgress->TransferingFile = false;
  1206. throw;
  1207. }
  1208. catch (EScpFileSkipped &E)
  1209. {
  1210. // SCP protocol non-fatal error
  1211. OperationProgress->TransferingFile = false;
  1212. throw;
  1213. }
  1214. // We succeded transfering file, from now we can handle exceptions
  1215. // normally -> no fatal error
  1216. OperationProgress->TransferingFile = false;
  1217. }
  1218. catch (Exception &E)
  1219. {
  1220. // Every exception during file transfer is fatal
  1221. if (OperationProgress->TransferingFile)
  1222. {
  1223. FTerminal->FatalError(&E, FMTLOAD(COPY_FATAL, (FileName)));
  1224. }
  1225. else
  1226. {
  1227. throw;
  1228. }
  1229. }
  1230. }
  1231. __finally
  1232. {
  1233. CloseHandle(File);
  1234. }
  1235. /* TODO : Delete also read-only files. */
  1236. /* TODO : Show error message on failure. */
  1237. if (Params & cpDelete) Sysutils::DeleteFile(FileName);
  1238. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory finished.", (FileName)));
  1239. }
  1240. //---------------------------------------------------------------------------
  1241. void __fastcall TSCPFileSystem::SCPDirectorySource(const AnsiString DirectoryName,
  1242. const TCopyParamType * CopyParam, int Params,
  1243. TFileOperationProgressType * OperationProgress)
  1244. {
  1245. int Attrs;
  1246. FTerminal->LogEvent(FORMAT("Entering directory \"%s\".", (DirectoryName)));
  1247. OperationProgress->SetFile(DirectoryName);
  1248. AnsiString DestFileName = CopyParam->ChangeFileName(ExtractFileName(DirectoryName), osLocal);
  1249. // Get directory attributes
  1250. FILE_OPERATION_LOOP (DirectoryName, FMTLOAD(CANT_GET_ATTRS, (DirectoryName)),
  1251. Attrs = FileGetAttr(DirectoryName);
  1252. if (Attrs == -1) EXCEPTION;
  1253. )
  1254. AnsiString Buf;
  1255. /* TODO 1: maybe send filetime */
  1256. // Send directory modes (rights), filesize and file name
  1257. Buf = FORMAT("D0%s 0 %s",
  1258. (CopyParam->RemoteFileRights(Attrs).Octal, DestFileName));
  1259. FTerminal->SendLine(Buf);
  1260. SCPResponse();
  1261. try
  1262. {
  1263. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1264. TSearchRec SearchRec;
  1265. bool FindOK;
  1266. FILE_OPERATION_LOOP (DirectoryName, FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1267. FindOK = (bool)(FindFirst(IncludeTrailingBackslash(DirectoryName) + "*.*",
  1268. FindAttrs, SearchRec) == 0);
  1269. );
  1270. while (FindOK && !OperationProgress->Cancel)
  1271. {
  1272. AnsiString FileName = IncludeTrailingBackslash(DirectoryName) + SearchRec.Name;
  1273. try
  1274. {
  1275. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  1276. {
  1277. SCPSource(FileName, CopyParam, Params, OperationProgress);
  1278. }
  1279. }
  1280. catch (EScpSkipFile &E)
  1281. {
  1282. // If ESkipFile occurs, just log it and continue with next file
  1283. SUSPEND_OPERATION (
  1284. if (FTerminal->DoQueryUser(FMTLOAD(COPY_ERROR, (FileName)), E.Message,
  1285. qaOK | qaAbort, qpAllowContinueOnError) == qaAbort)
  1286. {
  1287. OperationProgress->Cancel = csCancel;
  1288. }
  1289. if (!FTerminal->HandleException(&E)) throw;
  1290. );
  1291. }
  1292. FILE_OPERATION_LOOP (DirectoryName, FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1293. FindOK = (FindNext(SearchRec) == 0);
  1294. );
  1295. };
  1296. FindClose(SearchRec);
  1297. /* TODO : Delete also read-only directories. */
  1298. /* TODO : Show error message on failure. */
  1299. if ((Params & cpDelete) && !OperationProgress->Cancel) RemoveDir(DirectoryName);
  1300. }
  1301. __finally
  1302. {
  1303. if (FTerminal->Active)
  1304. {
  1305. // Tell remote side, that we're done.
  1306. FTerminal->LogEvent(FORMAT("Leaving directory \"%s\".", (DirectoryName)));
  1307. FTerminal->SendLine("E");
  1308. SCPResponse();
  1309. }
  1310. }
  1311. }
  1312. //---------------------------------------------------------------------------
  1313. void __fastcall TSCPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1314. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  1315. int Params, TFileOperationProgressType * OperationProgress,
  1316. bool & DisconnectWhenComplete)
  1317. {
  1318. bool CloseSCP = False;
  1319. AnsiString Options = "";
  1320. if (CopyParam->PreserveRights || CopyParam->PreserveTime) Options = "-p";
  1321. if (FTerminal->SessionData->Scp1Compatibility) Options += " -1";
  1322. FTerminal->LogEvent(FORMAT("Copying %d files/directories to local directory "
  1323. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  1324. FTerminal->LogEvent(CopyParam->LogStr);
  1325. try
  1326. {
  1327. for (int IFile = 0; (IFile < FilesToCopy->Count) &&
  1328. !OperationProgress->Cancel; IFile++)
  1329. {
  1330. AnsiString FileName = FilesToCopy->Strings[IFile];
  1331. TRemoteFile * File = (TRemoteFile *)FilesToCopy->Objects[IFile];
  1332. assert(File);
  1333. try
  1334. {
  1335. bool Success = true; // Have to be set to True (see ::SCPSink)
  1336. SendCommand(FCommandSet->FullCommand(fsCopyToLocal,
  1337. ARRAYOFCONST((Options, DelimitStr(FileName)))));
  1338. SkipFirstLine();
  1339. // Filename is used only for error messaging
  1340. SCPSink(TargetDir, FileName, CopyParam, Success, OperationProgress, Params);
  1341. // operation succeded (no exception), so it's ok that
  1342. // remote side closed SCP, but we continue with next file
  1343. if (OperationProgress->Cancel == csRemoteAbort)
  1344. {
  1345. OperationProgress->Cancel = csContinue;
  1346. }
  1347. // Move operation -> delete file/directory afterwards
  1348. // but only if copying succeded
  1349. if ((Params & cpDelete) && Success && !OperationProgress->Cancel)
  1350. {
  1351. try
  1352. {
  1353. FTerminal->ExceptionOnFail = true;
  1354. try
  1355. {
  1356. FILE_OPERATION_LOOP(FileName,
  1357. FMTLOAD(DELETE_FILE_ERROR, (FileName)),
  1358. FTerminal->DeleteFile("", File)
  1359. );
  1360. }
  1361. __finally
  1362. {
  1363. FTerminal->ExceptionOnFail = false;
  1364. }
  1365. }
  1366. catch (EFatal &E)
  1367. {
  1368. throw;
  1369. }
  1370. catch (...)
  1371. {
  1372. // If user selects skip (or abort), nothing special actualy occures
  1373. // we just run DoFinished with Success = False, so file won't
  1374. // be deselected in panel (depends on assigned event handler)
  1375. // On csCancel we would later try to close remote SCP, but it
  1376. // is closed already
  1377. if (OperationProgress->Cancel == csCancel)
  1378. {
  1379. OperationProgress->Cancel = csRemoteAbort;
  1380. }
  1381. Success = false;
  1382. }
  1383. }
  1384. OperationProgress->Finish(FileName,
  1385. (!OperationProgress->Cancel && Success), DisconnectWhenComplete);
  1386. }
  1387. catch (...)
  1388. {
  1389. OperationProgress->Finish(FileName, false, DisconnectWhenComplete);
  1390. CloseSCP = (OperationProgress->Cancel != csRemoteAbort);
  1391. throw;
  1392. }
  1393. }
  1394. }
  1395. __finally
  1396. {
  1397. // In case that copying don't causes fatal error (ie. connection is
  1398. // still active) but weren't succesful (exception or user termination)
  1399. // we need to ensure, that SCP on remote side is closed
  1400. if (FTerminal->Active && (CloseSCP ||
  1401. (OperationProgress->Cancel == csCancel) ||
  1402. (OperationProgress->Cancel == csCancelTransfer)))
  1403. {
  1404. bool LastLineRead;
  1405. // If we get LastLine, it means that remote side 'scp' is already
  1406. // terminated, so we need not to terminate it. There is also
  1407. // possibility that remote side waits for confirmation, so it will hang.
  1408. // This should not happen (hope)
  1409. AnsiString Line = FTerminal->ReceiveLine();
  1410. LastLineRead = IsLastLine(Line);
  1411. if (!LastLineRead)
  1412. {
  1413. SCPSendError((OperationProgress->Cancel ? "Terminated by user." : "Exception"), true);
  1414. }
  1415. // Just in case, remote side already sent some more data (it's probable)
  1416. // but we don't want to raise exception (user asked to terminate, it's not error)
  1417. int ECParams = coOnlyReturnCode;
  1418. if (!LastLineRead) ECParams |= coWaitForLastLine;
  1419. ReadCommandOutput(ECParams);
  1420. }
  1421. }
  1422. }
  1423. //---------------------------------------------------------------------------
  1424. void __fastcall TSCPFileSystem::SCPError(const AnsiString Message, bool Fatal)
  1425. {
  1426. SCPSendError(Message, Fatal);
  1427. THROW_FILE_SKIPPED(NULL, Message);
  1428. }
  1429. //---------------------------------------------------------------------------
  1430. void __fastcall TSCPFileSystem::SCPSendError(const AnsiString Message, bool Fatal)
  1431. {
  1432. char ErrorLevel = (char)(Fatal ? 2 : 1);
  1433. FTerminal->LogEvent(FORMAT("Sending SCP error (%d) to remote side:",
  1434. ((int)ErrorLevel)));
  1435. FTerminal->Send(&ErrorLevel, 1);
  1436. // We don't send exact error message, because some unspecified
  1437. // characters can terminate remote scp
  1438. FTerminal->SendLine("scp: error");
  1439. }
  1440. //---------------------------------------------------------------------------
  1441. void __fastcall TSCPFileSystem::SCPSink(const AnsiString TargetDir,
  1442. const AnsiString FileName, const TCopyParamType * CopyParam, bool & Success,
  1443. TFileOperationProgressType * OperationProgress, int Params)
  1444. {
  1445. struct
  1446. {
  1447. int SetTime;
  1448. FILETIME AcTime;
  1449. FILETIME WrTime;
  1450. TRights RemoteRights;
  1451. int Attrs;
  1452. bool Exists;
  1453. } FileData;
  1454. bool SkipConfirmed = false;
  1455. FileData.SetTime = 0;
  1456. FTerminal->SendNull();
  1457. while (!OperationProgress->Cancel)
  1458. {
  1459. // See (switch ... case 'T':)
  1460. if (FileData.SetTime) FileData.SetTime--;
  1461. // In case of error occured before control record arrived
  1462. OperationProgress->FileName = FileName;
  1463. try
  1464. {
  1465. // Receive control record
  1466. AnsiString Line = FTerminal->ReceiveLine();
  1467. if (Line.Length() == 0) FTerminal->FatalError(LoadStr(SCP_EMPTY_LINE));
  1468. if (IsLastLine(Line))
  1469. {
  1470. // Remote side finished copying, so remote SCP was closed
  1471. // and we don't need to terminate it manualy, see CopyToLocal()
  1472. OperationProgress->Cancel = csRemoteAbort;
  1473. /* TODO 1 : Show stderror to user? */
  1474. FTerminal->ClearStdError();
  1475. ReadCommandOutput(coExpectNoOutput | coRaiseExcept | coOnlyReturnCode);
  1476. return;
  1477. }
  1478. else
  1479. {
  1480. // First characted distinguish type of control record
  1481. char Ctrl = Line[1];
  1482. Line.Delete(1, 1);
  1483. switch (Ctrl) {
  1484. case 1:
  1485. // Error (already logged by ReceiveLine())
  1486. THROW_FILE_SKIPPED(NULL, FMTLOAD(REMOTE_ERROR, (Line)));
  1487. case 2:
  1488. // Fatal error, terminate copying
  1489. FTerminal->TerminalError(Line);
  1490. return; // Unreachable
  1491. case 'E': // Exit
  1492. FTerminal->SendNull();
  1493. return;
  1494. case 'T':
  1495. unsigned long MTime, ATime;
  1496. if (sscanf(Line.c_str(), "%ld %*d %ld %*d", &MTime, &ATime) == 2)
  1497. {
  1498. TIME_POSIX_TO_WIN(ATime, FileData.AcTime);
  1499. TIME_POSIX_TO_WIN(MTime, FileData.WrTime);
  1500. FTerminal->SendNull();
  1501. // File time is only valid until next pass
  1502. FileData.SetTime = 2;
  1503. continue;
  1504. }
  1505. else
  1506. {
  1507. SCPError(LoadStr(SCP_ILLEGAL_TIME_FORMAT), False);
  1508. }
  1509. case 'C':
  1510. case 'D':
  1511. break; // continue pass switch{}
  1512. default:
  1513. FTerminal->FatalError(FMTLOAD(SCP_INVALID_CONTROL_RECORD, (Ctrl, Line)));
  1514. }
  1515. // We reach this point only if control record was 'C' or 'D'
  1516. try
  1517. {
  1518. Line.Delete(1, 1); // Zero at beginning
  1519. FileData.RemoteRights.Octal = CutToChar(Line, ' ', True);
  1520. __int64 TSize = StrToInt64(CutToChar(Line, ' ', True));
  1521. // Security fix: ensure the file ends up where we asked for it.
  1522. // (accept only filename, not path)
  1523. AnsiString OnlyFileName = UnixExtractFileName(Line);
  1524. if (Line != OnlyFileName)
  1525. {
  1526. FTerminal->LogEvent(FORMAT("Warning: Remote host set a compound pathname '%s'", (Line)));
  1527. }
  1528. OperationProgress->SetFile(OnlyFileName);
  1529. OperationProgress->SetTransferSize(TSize);
  1530. }
  1531. catch (Exception &E)
  1532. {
  1533. SUSPEND_OPERATION (
  1534. HandleExtendedException(&E);
  1535. );
  1536. SCPError(LoadStr(SCP_ILLEGAL_FILE_DESCRIPTOR), false);
  1537. }
  1538. // last possibility to cancel transfer before it starts
  1539. if (OperationProgress->Cancel)
  1540. {
  1541. THROW_SKIP_FILE(NULL, LoadStr(USER_TERMINATED));
  1542. }
  1543. // Security fix
  1544. if (IsDots(OperationProgress->FileName))
  1545. {
  1546. FTerminal->FatalError(LoadStr(ATTEMPT_TO_WRITE_TO_PARENT_DIR));
  1547. }
  1548. AnsiString DestFileName =
  1549. IncludeTrailingBackslash(TargetDir) +
  1550. CopyParam->ChangeFileName(OperationProgress->FileName, osRemote);
  1551. FileData.Attrs = FileGetAttr(DestFileName);
  1552. // If getting attrs failes, we suppose, that file/folder doesn't exists
  1553. FileData.Exists = (FileData.Attrs != -1);
  1554. if (Ctrl == 'D')
  1555. {
  1556. if (FileData.Exists && !(FileData.Attrs & faDirectory))
  1557. {
  1558. SCPError(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFileName)), false);
  1559. }
  1560. if (!FileData.Exists)
  1561. {
  1562. FILE_OPERATION_LOOP (DestFileName, FMTLOAD(CREATE_DIR_ERROR, (DestFileName)),
  1563. if (!ForceDirectories(DestFileName)) EXCEPTION;
  1564. );
  1565. /* SCP: can we set the timestamp for directories ? */
  1566. }
  1567. /* TODO 1 : Send whole path, CopyData.SourceFileName is not enough
  1568. (just error messaging)*/
  1569. SCPSink(DestFileName, OperationProgress->FileName, CopyParam,
  1570. Success, OperationProgress, Params);
  1571. continue;
  1572. }
  1573. else
  1574. if (Ctrl == 'C')
  1575. {
  1576. HANDLE File = NULL;
  1577. TStream * FileStream = NULL;
  1578. /* TODO 1 : Turn off read-only attr */
  1579. try
  1580. {
  1581. try
  1582. {
  1583. if (FileExists(DestFileName))
  1584. {
  1585. if (OperationProgress->NoToAll)
  1586. {
  1587. EXCEPTION;
  1588. }
  1589. else if (!OperationProgress->YesToAll &&
  1590. FTerminal->Configuration->ConfirmOverwriting &&
  1591. !(Params & cpNoConfirmation))
  1592. {
  1593. int Answer;
  1594. SUSPEND_OPERATION (
  1595. Answer = FTerminal->DoQueryUser(
  1596. FMTLOAD(FILE_OVERWRITE, (OperationProgress->FileName)),
  1597. qaYes | qaNo | qaAbort | qaYesToAll | qaNoToAll,
  1598. qpNeverAskAgainCheck);
  1599. );
  1600. switch (Answer) {
  1601. case qaNeverAskAgain: FTerminal->Configuration->ConfirmOverwriting = false; break;
  1602. case qaYesToAll: OperationProgress->YesToAll = true; break;
  1603. case qaAbort: OperationProgress->Cancel = csCancel; // continue on next case
  1604. case qaNoToAll: OperationProgress->NoToAll = true;
  1605. case qaNo: SkipConfirmed = true; EXCEPTION;
  1606. }
  1607. }
  1608. }
  1609. // Create file
  1610. FILE_OPERATION_LOOP (DestFileName, FMTLOAD(CREATE_FILE_ERROR, (DestFileName)),
  1611. File = CreateFile(DestFileName.c_str(), GENERIC_WRITE, 0, NULL,
  1612. CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  1613. if (File == INVALID_HANDLE_VALUE) EXCEPTION;
  1614. );
  1615. FileStream = new THandleStream((THandle)File);
  1616. }
  1617. catch (Exception &E)
  1618. {
  1619. // In this step we can still cancel transfer, so we do it
  1620. SCPError(E.Message, false);
  1621. throw;
  1622. }
  1623. // We succeded, so we confirm transfer to remote side
  1624. FTerminal->SendNull();
  1625. // From now we need to finish file transfer, if not it's fatal error
  1626. OperationProgress->TransferingFile = true;
  1627. // Suppose same data size to transfer as to write
  1628. // (not true with ASCII transfer)
  1629. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  1630. // Will we use ASCII of BINARY file tranfer?
  1631. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(DestFileName));
  1632. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  1633. " transfer mode selected.");
  1634. try
  1635. {
  1636. // Buffer for one block of data
  1637. TFileBuffer BlockBuf;
  1638. do
  1639. {
  1640. BlockBuf.Size = OperationProgress->TransferBlockSize();
  1641. BlockBuf.Position = 0;
  1642. FTerminal->Receive(BlockBuf.Data, BlockBuf.Size);
  1643. OperationProgress->AddTransfered(BlockBuf.Size);
  1644. if (OperationProgress->AsciiTransfer)
  1645. {
  1646. unsigned int PrevBlockSize = BlockBuf.Size;
  1647. BlockBuf.ConvertEOL(FTerminal->SessionData->EOLType,
  1648. FTerminal->Configuration->LocalEOLType);
  1649. OperationProgress->SetLocalSize(
  1650. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  1651. }
  1652. // This is crucial, if it fails during file transfer, it's fatal error
  1653. FILE_OPERATION_LOOP_EX (
  1654. DestFileName, false, FMTLOAD(WRITE_ERROR, (DestFileName)),
  1655. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  1656. );
  1657. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  1658. if (OperationProgress->Cancel == csCancelTransfer)
  1659. {
  1660. throw Exception(USER_TERMINATED);
  1661. }
  1662. }
  1663. while (!OperationProgress->IsLocalyDone() || !
  1664. OperationProgress->IsTransferDone());
  1665. }
  1666. catch (Exception &E)
  1667. {
  1668. // Every exception during file transfer is fatal
  1669. FTerminal->FatalError(&E,
  1670. FMTLOAD(COPY_FATAL, (OperationProgress->FileName)));
  1671. }
  1672. OperationProgress->TransferingFile = false;
  1673. try
  1674. {
  1675. SCPResponse();
  1676. // If one of following exception occurs, we still need
  1677. // to send confirmation to other side
  1678. }
  1679. catch (EScp &E)
  1680. {
  1681. FTerminal->SendNull();
  1682. throw;
  1683. }
  1684. catch (EScpFileSkipped &E)
  1685. {
  1686. FTerminal->SendNull();
  1687. throw;
  1688. }
  1689. FTerminal->SendNull();
  1690. if (FileData.SetTime && CopyParam->PreserveTime)
  1691. {
  1692. SetFileTime(File, NULL, &FileData.AcTime, &FileData.WrTime);
  1693. }
  1694. }
  1695. __finally
  1696. {
  1697. if (File) CloseHandle(File);
  1698. if (FileStream) delete FileStream;
  1699. }
  1700. if (FileData.Attrs == -1) FileData.Attrs = faArchive;
  1701. Integer NewAttrs = CopyParam->LocalFileAttrs(FileData.RemoteRights);
  1702. if ((NewAttrs & FileData.Attrs) != NewAttrs)
  1703. {
  1704. FILE_OPERATION_LOOP (DestFileName, FMTLOAD(CANT_SET_ATTRS, (DestFileName)),
  1705. FileSetAttr(DestFileName, FileData.Attrs | NewAttrs);
  1706. );
  1707. }
  1708. }
  1709. }
  1710. }
  1711. catch (EScpFileSkipped &E)
  1712. {
  1713. if (!SkipConfirmed)
  1714. {
  1715. SUSPEND_OPERATION (
  1716. if (FTerminal->DoQueryUser(FMTLOAD(COPY_ERROR, (OperationProgress->FileName)),
  1717. E.Message, qaOK | qaAbort, qpAllowContinueOnError) == qaAbort)
  1718. {
  1719. OperationProgress->Cancel = csCancel;
  1720. }
  1721. HandleExtendedException(&E, this);
  1722. );
  1723. Success = false;
  1724. }
  1725. }
  1726. catch (EScpSkipFile &E)
  1727. {
  1728. SCPSendError(E.Message, false);
  1729. Success = false;
  1730. if (!FTerminal->HandleException(&E)) throw;
  1731. }
  1732. }
  1733. }