ScpFileSystem.cpp 70 KB

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