ScpFileSystem.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105
  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::LookupUserGroups()
  642. {
  643. ExecCommand(fsLookupUserGroups);
  644. FTerminal->FUserGroups->Clear();
  645. if (FOutput->Count > 0)
  646. {
  647. FTerminal->FUserGroups->BeginUpdate();
  648. try
  649. {
  650. AnsiString Groups = FOutput->Strings[0];
  651. while (!Groups.IsEmpty())
  652. {
  653. AnsiString NewGroup = CutToChar(Groups, ' ', False);
  654. FTerminal->FUserGroups->Add(NewGroup);
  655. }
  656. }
  657. __finally
  658. {
  659. FTerminal->FUserGroups->EndUpdate();
  660. }
  661. }
  662. }
  663. //---------------------------------------------------------------------------
  664. void __fastcall TSCPFileSystem::DetectReturnVar()
  665. {
  666. // This suppose that something was already executed (probably SkipStartupMessage())
  667. // or return code variable is already set on start up.
  668. try
  669. {
  670. // #60 17.10.01: "status" and "?" switched
  671. AnsiString ReturnVars[2] = { "status", "?" };
  672. AnsiString NewReturnVar = "";
  673. FTerminal->LogEvent("Detecting variable containing return code of last command.");
  674. for (int Index = 0; Index < 2; Index++)
  675. {
  676. bool Success = true;
  677. try
  678. {
  679. FTerminal->LogEvent(FORMAT("Trying \"$%s\".", (ReturnVars[Index])));
  680. ExecCommand(fsVarValue, ARRAYOFCONST((ReturnVars[Index])));
  681. if ((Output->Count != 1) || (StrToIntDef(Output->Strings[0], 256) > 255)) Abort();
  682. }
  683. catch (EFatal &E)
  684. {
  685. // if fatal error occurs, we need to exit ...
  686. throw;
  687. }
  688. catch (Exception &E)
  689. {
  690. // ...otherwise, we will try next variable (if any)
  691. Success = false;
  692. }
  693. if (Success)
  694. {
  695. NewReturnVar = ReturnVars[Index];
  696. break;
  697. }
  698. }
  699. if (NewReturnVar.IsEmpty())
  700. {
  701. Abort();
  702. }
  703. else
  704. {
  705. FCommandSet->ReturnVar = NewReturnVar;
  706. FTerminal->LogEvent(FORMAT("Return code variable \"%s\" selected.",
  707. (FCommandSet->ReturnVar)));
  708. }
  709. }
  710. catch (Exception &E)
  711. {
  712. FTerminal->CommandError(&E, LoadStr(DETECT_RETURNVAR_ERROR));
  713. }
  714. }
  715. //---------------------------------------------------------------------------
  716. void __fastcall TSCPFileSystem::ClearAliases()
  717. {
  718. try
  719. {
  720. FTerminal->LogEvent("Clearing all aliases.");
  721. TStrings * CommandList = FCommandSet->CreateCommandList();
  722. try
  723. {
  724. for (int Index = 0; Index < CommandList->Count; Index++)
  725. {
  726. // this command usually fails, becouse there will never be
  727. // aliases on all commands -> see last False parametr
  728. ExecCommand(fsUnalias, ARRAYOFCONST((CommandList->Strings[Index])), false);
  729. }
  730. }
  731. __finally
  732. {
  733. delete CommandList;
  734. }
  735. }
  736. catch (Exception &E)
  737. {
  738. FTerminal->CommandError(&E, LoadStr(UNALIAS_ALL_ERROR));
  739. }
  740. }
  741. //---------------------------------------------------------------------------
  742. void __fastcall TSCPFileSystem::AliasGroupList()
  743. {
  744. try
  745. {
  746. FTerminal->LogEvent("Aliasing LS to display file group.");
  747. ExecCommand(fsAliasGroupList);
  748. }
  749. catch (Exception &E)
  750. {
  751. FTerminal->CommandError(&E, LoadStr(ALIAS_GROUPLIST_ERROR));
  752. }
  753. }
  754. //---------------------------------------------------------------------------
  755. void __fastcall TSCPFileSystem::UnsetNationalVars()
  756. {
  757. try
  758. {
  759. FTerminal->LogEvent("Clearing national user variables.");
  760. for (int Index = 0; Index < NationalVarCount; Index++)
  761. {
  762. ExecCommand(fsUnset, ARRAYOFCONST((NationalVars[Index])), false);
  763. }
  764. }
  765. catch (Exception &E)
  766. {
  767. FTerminal->CommandError(&E, LoadStr(UNSET_NATIONAL_ERROR));
  768. }
  769. }
  770. //---------------------------------------------------------------------------
  771. void __fastcall TSCPFileSystem::ReadCurrentDirectory()
  772. {
  773. if (FCachedDirectoryChange.IsEmpty())
  774. {
  775. ExecCommand(fsCurrentDirectory);
  776. FCurrentDirectory = UnixExcludeTrailingBackslash(FOutput->Strings[0]);
  777. }
  778. else
  779. {
  780. FCurrentDirectory = FCachedDirectoryChange;
  781. }
  782. }
  783. //---------------------------------------------------------------------------
  784. void __fastcall TSCPFileSystem::HomeDirectory()
  785. {
  786. ExecCommand(fsHomeDirectory);
  787. }
  788. //---------------------------------------------------------------------------
  789. void __fastcall TSCPFileSystem::ChangeDirectory(const AnsiString Directory)
  790. {
  791. AnsiString ToDir;
  792. if (!Directory.IsEmpty() &&
  793. ((Directory[1] != '~') || (Directory.SubString(1, 2) == "~ ")))
  794. {
  795. ToDir = "\"" + DelimitStr(Directory) + "\"";
  796. }
  797. else
  798. {
  799. ToDir = DelimitStr(Directory);
  800. }
  801. ExecCommand(fsChangeDirectory, ARRAYOFCONST((ToDir)));
  802. FCachedDirectoryChange = "";
  803. }
  804. //---------------------------------------------------------------------------
  805. void __fastcall TSCPFileSystem::CachedChangeDirectory(const AnsiString Directory)
  806. {
  807. FCachedDirectoryChange = Directory;
  808. }
  809. //---------------------------------------------------------------------------
  810. void __fastcall TSCPFileSystem::ReadDirectory(TRemoteFileList * FileList)
  811. {
  812. assert(FileList);
  813. TStringList * OutputCopy = NULL;
  814. try
  815. {
  816. if (FileList->Directory == FTerminal->CurrentDirectory)
  817. {
  818. FTerminal->LogEvent("Listing current directory.");
  819. ExecCommand(fsListCurrentDirectory);
  820. }
  821. else
  822. {
  823. FTerminal->LogEvent(FORMAT("Listing directory \"%s\".",
  824. (FileList->Directory)));
  825. ExecCommand(fsListDirectory, ARRAYOFCONST((DelimitStr(FileList->Directory))));
  826. }
  827. FileList->Clear();
  828. TRemoteFile * File;
  829. // If output is not empty, we have succesfully got file listing,
  830. // otherwise there was an error, in case it was "permission denied"
  831. // we try to get at least parent directory (see "else" statement below)
  832. if (FOutput->Count > 0)
  833. {
  834. // Copy LS command output, because eventual symlink analysis would
  835. // modify FTerminal->Output
  836. OutputCopy = new TStringList();
  837. OutputCopy->Assign(FOutput);
  838. // delete leading "total xxx" line
  839. // On some hosts there is not "total" but "totalt". What's the reason??
  840. // see mail from "Jan Wiklund (SysOp)" <[email protected]>
  841. if (IsTotalListingLine(OutputCopy->Strings[0]))
  842. {
  843. OutputCopy->Delete(0);
  844. }
  845. for (int Index = 0; Index < OutputCopy->Count; Index++)
  846. {
  847. File = new TRemoteFile();
  848. File->Terminal = FTerminal;
  849. File->ListingStr = OutputCopy->Strings[Index];
  850. File->ShiftTime(FTerminal->SessionData->TimeDifference);
  851. FileList->AddFile(File);
  852. }
  853. }
  854. else
  855. {
  856. // Empty file list -> probably "permision denied", we
  857. // at least get link to parent directory ("..")
  858. FTerminal->ReadFile(
  859. UnixIncludeTrailingBackslash(FTerminal->FFiles->Directory) +
  860. PARENTDIRECTORY, File);
  861. assert(File->IsParentDirectory);
  862. FileList->AddFile(File);
  863. }
  864. }
  865. __finally
  866. {
  867. delete OutputCopy;
  868. }
  869. }
  870. //---------------------------------------------------------------------------
  871. void __fastcall TSCPFileSystem::ReadSymlink(TRemoteFile * SymlinkFile,
  872. TRemoteFile *& File)
  873. {
  874. CustomReadFile(SymlinkFile->LinkTo, File, SymlinkFile);
  875. }
  876. //---------------------------------------------------------------------------
  877. void __fastcall TSCPFileSystem::ReadFile(const AnsiString FileName,
  878. TRemoteFile *& File)
  879. {
  880. CustomReadFile(FileName, File, NULL);
  881. }
  882. //---------------------------------------------------------------------------
  883. void __fastcall TSCPFileSystem::CustomReadFile(const AnsiString FileName,
  884. TRemoteFile *& File, TRemoteFile * ALinkedByFile)
  885. {
  886. File = NULL;
  887. ExecCommand(fsListFile, ARRAYOFCONST((DelimitStr(FileName))));
  888. if (FOutput->Count)
  889. {
  890. int LineIndex = 0;
  891. if (IsTotalListingLine(FOutput->Strings[LineIndex]) && FOutput->Count > 1)
  892. {
  893. LineIndex++;
  894. }
  895. File = new TRemoteFile(ALinkedByFile);
  896. try
  897. {
  898. File->Terminal = FTerminal;
  899. File->ListingStr = FOutput->Strings[LineIndex];
  900. }
  901. catch(...)
  902. {
  903. delete File;
  904. File = NULL;
  905. throw;
  906. }
  907. }
  908. }
  909. //---------------------------------------------------------------------------
  910. void __fastcall TSCPFileSystem::DeleteFile(const AnsiString FileName,
  911. const TRemoteFile * File, bool Recursive)
  912. {
  913. assert(Recursive || (File && File->IsSymLink));
  914. ExecCommand(fsDeleteFile, ARRAYOFCONST((DelimitStr(FileName))));
  915. }
  916. //---------------------------------------------------------------------------
  917. void __fastcall TSCPFileSystem::RenameFile(const AnsiString FileName,
  918. const AnsiString NewName)
  919. {
  920. ExecCommand(fsRenameFile, ARRAYOFCONST((DelimitStr(FileName), DelimitStr(NewName))));
  921. }
  922. //---------------------------------------------------------------------------
  923. void __fastcall TSCPFileSystem::CreateDirectory(const AnsiString DirName,
  924. const TRemoteProperties * Properties)
  925. {
  926. assert(!Properties); // not implemented yet
  927. ExecCommand(fsCreateDirectory, ARRAYOFCONST((DelimitStr(DirName))));
  928. }
  929. //---------------------------------------------------------------------------
  930. void __fastcall TSCPFileSystem::CreateLink(const AnsiString FileName,
  931. const AnsiString PointTo, bool Symbolic)
  932. {
  933. ExecCommand(fsCreateLink,
  934. ARRAYOFCONST((Symbolic ? "-s" : "", DelimitStr(PointTo), DelimitStr(FileName))));
  935. }
  936. //---------------------------------------------------------------------------
  937. void __fastcall TSCPFileSystem::ChangeFileProperties(const AnsiString FileName,
  938. const TRemoteFile * File, const TRemoteProperties * Properties)
  939. {
  940. assert(Properties);
  941. bool IsDirectory = File && File->IsDirectory;
  942. bool Recursive = Properties->Recursive && IsDirectory;
  943. AnsiString RecursiveStr = Recursive ? "-R" : "";
  944. AnsiString DelimitedName = DelimitStr(FileName);
  945. if (Properties->Valid.Contains(vpRights))
  946. {
  947. TRights Rights = Properties->Rights;
  948. // if we don't set modes recursively, we may add X at once with other
  949. // options. Otherwise we have to add X after recusive command
  950. if (!Recursive && IsDirectory && Properties->AddXToDirectories)
  951. Rights.AddExecute();
  952. ExecCommand(fsChangeMode,
  953. ARRAYOFCONST((RecursiveStr, Rights.SimplestStr, DelimitedName)));
  954. // if file is directory and we do recursive mode settings with
  955. // add-x-to-directories option on, add those X
  956. if (Recursive && IsDirectory && Properties->AddXToDirectories)
  957. {
  958. Rights.AddExecute();
  959. ExecCommand(fsChangeMode,
  960. ARRAYOFCONST(("", Rights.SimplestStr, DelimitedName)));
  961. }
  962. }
  963. if (Properties->Valid.Contains(vpGroup))
  964. {
  965. ExecCommand(fsChangeGroup,
  966. ARRAYOFCONST((RecursiveStr, Properties->Group, DelimitedName)));
  967. }
  968. if (Properties->Valid.Contains(vpOwner))
  969. {
  970. ExecCommand(fsChangeOwner,
  971. ARRAYOFCONST((RecursiveStr, DelimitStr(Properties->Owner), DelimitedName)));
  972. }
  973. }
  974. //---------------------------------------------------------------------------
  975. void __fastcall TSCPFileSystem::CustomCommandOnFile(const AnsiString FileName,
  976. const TRemoteFile * File, AnsiString Command, int Params)
  977. {
  978. assert(File);
  979. bool Dir = File->IsDirectory && !File->IsSymLink;
  980. if (Dir && (Params & ccRecursive))
  981. {
  982. TCustomCommandParams AParams;
  983. AParams.Command = Command;
  984. AParams.Params = Params;
  985. FTerminal->ProcessDirectory(FileName, FTerminal->CustomCommandOnFile,
  986. &AParams);
  987. }
  988. if (!Dir || (Params & ccApplyToDirectories))
  989. {
  990. AnsiString Cmd = CompleteCustomCommand(Command, FileName, NULL);
  991. AnyCommand(Cmd);
  992. }
  993. }
  994. //---------------------------------------------------------------------------
  995. void __fastcall TSCPFileSystem::AnyCommand(const AnsiString Command)
  996. {
  997. ExecCommand(fsAnyCommand, ARRAYOFCONST((Command)));
  998. }
  999. //---------------------------------------------------------------------------
  1000. // transfer protocol
  1001. //---------------------------------------------------------------------------
  1002. void __fastcall TSCPFileSystem::SCPResponse(bool * GotLastLine)
  1003. {
  1004. // Taken from scp.c response() and modified
  1005. char Resp;
  1006. FTerminal->Receive(&Resp, 1);
  1007. switch (Resp)
  1008. {
  1009. case 0: /* ok */
  1010. FTerminal->LogEvent("SCP remote side confirmation (0)");
  1011. return;
  1012. default:
  1013. case 1: /* error */
  1014. case 2: /* fatal error */
  1015. // pscp adds 'Resp' to 'Msg', why?
  1016. AnsiString Msg = FTerminal->ReceiveLine();
  1017. AnsiString Line = AnsiString(Resp) + Msg;
  1018. if (IsLastLine(Line))
  1019. {
  1020. if (GotLastLine)
  1021. {
  1022. *GotLastLine = true;
  1023. }
  1024. /* TODO 1 : Show stderror to user? */
  1025. FTerminal->ClearStdError();
  1026. try
  1027. {
  1028. ReadCommandOutput(coExpectNoOutput | coRaiseExcept | coOnlyReturnCode);
  1029. }
  1030. catch(...)
  1031. {
  1032. // when ReadCommandOutput() fails than remote SCP is terminated already
  1033. *GotLastLine = true;
  1034. throw;
  1035. }
  1036. }
  1037. else
  1038. if (Resp == 1)
  1039. {
  1040. FTerminal->LogEvent("SCP remote side error (1):");
  1041. }
  1042. else
  1043. {
  1044. FTerminal->LogEvent("SCP remote side fatal error (2):");
  1045. }
  1046. if (Resp == 1)
  1047. {
  1048. THROW_FILE_SKIPPED(NULL, Msg);
  1049. }
  1050. else
  1051. {
  1052. THROW_SCP_ERROR(NULL, Msg);
  1053. }
  1054. }
  1055. }
  1056. //---------------------------------------------------------------------------
  1057. void __fastcall TSCPFileSystem::CopyToRemote(TStrings * FilesToCopy,
  1058. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  1059. int Params, TFileOperationProgressType * OperationProgress,
  1060. bool & DisconnectWhenComplete)
  1061. {
  1062. // scp.c: source(), toremote()
  1063. assert(FilesToCopy && OperationProgress);
  1064. AnsiString Options = "";
  1065. bool CheckExistence = UnixComparePaths(TargetDir, FTerminal->CurrentDirectory);
  1066. bool CopyBatchStarted = false;
  1067. bool Failed = true;
  1068. bool GotLastLine = false;
  1069. if (CopyParam->PreserveRights) Options = "-p";
  1070. if (FTerminal->SessionData->Scp1Compatibility) Options += " -1";
  1071. SendCommand(FCommandSet->FullCommand(fsCopyToRemote,
  1072. ARRAYOFCONST((Options, DelimitStr(UnixExcludeTrailingBackslash(TargetDir))))));
  1073. SkipFirstLine();
  1074. try
  1075. {
  1076. try
  1077. {
  1078. SCPResponse(&GotLastLine);
  1079. // This can happen only if SCP command is not executed and return code is 0
  1080. // It has never happened to me (return code is usually 127)
  1081. if (GotLastLine)
  1082. {
  1083. throw Exception("");
  1084. }
  1085. }
  1086. catch(Exception & E)
  1087. {
  1088. if (GotLastLine && FTerminal->Active)
  1089. {
  1090. FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
  1091. }
  1092. else
  1093. {
  1094. throw;
  1095. }
  1096. }
  1097. CopyBatchStarted = true;
  1098. for (int IFile = 0; (IFile < FilesToCopy->Count) &&
  1099. !OperationProgress->Cancel; IFile++)
  1100. {
  1101. AnsiString FileName = FilesToCopy->Strings[IFile];
  1102. bool CanProceed;
  1103. AnsiString FileNameOnly =
  1104. CopyParam->ChangeFileName(ExtractFileName(FileName), osLocal, true);
  1105. if (CheckExistence)
  1106. {
  1107. assert(FTerminal->FFiles && FTerminal->FFiles->Loaded);
  1108. TRemoteFile * File = FTerminal->FFiles->FindFile(FileNameOnly);
  1109. if (File && OperationProgress->NoToAll)
  1110. {
  1111. CanProceed = false;
  1112. }
  1113. else if (File && !OperationProgress->YesToAll &&
  1114. FTerminal->Configuration->ConfirmOverwriting && !(Params & cpNoConfirmation))
  1115. {
  1116. int Answer;
  1117. if (File->IsDirectory)
  1118. {
  1119. SUSPEND_OPERATION
  1120. (
  1121. Answer = FTerminal->DoQueryUser(
  1122. FMTLOAD(DIRECTORY_OVERWRITE, (FileNameOnly)),
  1123. qaYes | qaNo | qaAbort | qaYesToAll | qaNoToAll,
  1124. qpNeverAskAgainCheck);
  1125. );
  1126. }
  1127. else
  1128. {
  1129. unsigned long MTime;
  1130. TOverwriteFileParams FileParams;
  1131. FTerminal->OpenLocalFile(FileName, GENERIC_READ,
  1132. NULL, NULL, NULL, &MTime, NULL,
  1133. &FileParams.SourceSize);
  1134. FileParams.SourceTimestamp = UnixToDateTime(MTime);
  1135. FileParams.DestSize = File->Size;
  1136. FileParams.DestTimestamp = File->Modification;
  1137. SUSPEND_OPERATION
  1138. (
  1139. Answer = FTerminal->ConfirmFileOverwrite(
  1140. FileNameOnly, &FileParams,
  1141. qaYes | qaNo | qaAbort | qaYesToAll | qaNoToAll,
  1142. qpNeverAskAgainCheck);
  1143. );
  1144. }
  1145. switch (Answer) {
  1146. case qaNeverAskAgain:
  1147. FTerminal->Configuration->ConfirmOverwriting = false;
  1148. case qaYesToAll:
  1149. OperationProgress->YesToAll = true;
  1150. case qaYes:
  1151. CanProceed = true;
  1152. break;
  1153. case qaAbort:
  1154. if (!OperationProgress->Cancel) OperationProgress->Cancel = csCancel;
  1155. case qaNoToAll:
  1156. OperationProgress->NoToAll = true;
  1157. case qaNo:
  1158. CanProceed = false;
  1159. break;
  1160. }
  1161. }
  1162. else CanProceed = true;
  1163. }
  1164. else CanProceed = true;
  1165. if (CanProceed)
  1166. {
  1167. if (FTerminal->SessionData->CacheDirectories)
  1168. {
  1169. FTerminal->DirectoryModified(TargetDir, false);
  1170. if (DirectoryExists(FileName))
  1171. {
  1172. FTerminal->DirectoryModified(UnixIncludeTrailingBackslash(TargetDir)+
  1173. FileNameOnly, true);
  1174. }
  1175. }
  1176. AnsiString OrigFileNameOnly = ExtractFileName(FileName);
  1177. try
  1178. {
  1179. SCPSource(FileName, CopyParam, Params, OperationProgress, 0);
  1180. OperationProgress->Finish(OrigFileNameOnly, true, DisconnectWhenComplete);
  1181. }
  1182. catch (EScpFileSkipped &E)
  1183. {
  1184. SUSPEND_OPERATION (
  1185. if (FTerminal->DoQueryUser(FMTLOAD(COPY_ERROR, (FileName)), E.Message,
  1186. qaOK | qaAbort, qpAllowContinueOnError) == qaAbort)
  1187. {
  1188. OperationProgress->Cancel = csCancel;
  1189. }
  1190. OperationProgress->Finish(OrigFileNameOnly, false, DisconnectWhenComplete);
  1191. if (!FTerminal->HandleException(&E)) throw;
  1192. );
  1193. }
  1194. catch (EScpSkipFile &E)
  1195. {
  1196. OperationProgress->Finish(OrigFileNameOnly, false, DisconnectWhenComplete);
  1197. // If ESkipFile occurs, just log it and continue with next file
  1198. SUSPEND_OPERATION (
  1199. if (!FTerminal->HandleException(&E)) throw;
  1200. );
  1201. }
  1202. catch (...)
  1203. {
  1204. OperationProgress->Finish(OrigFileNameOnly, false, DisconnectWhenComplete);
  1205. throw;
  1206. }
  1207. }
  1208. }
  1209. Failed = false;
  1210. }
  1211. __finally
  1212. {
  1213. // Tell remote side, that we're done.
  1214. if (FTerminal->Active)
  1215. {
  1216. try
  1217. {
  1218. if (!GotLastLine)
  1219. {
  1220. if (CopyBatchStarted)
  1221. {
  1222. // What about case, remote side sends fatal error ???
  1223. // (Not sure, if it causes remote side to terminate scp)
  1224. FTerminal->SendLine("E");
  1225. SCPResponse();
  1226. };
  1227. /* TODO 1 : Show stderror to user? */
  1228. FTerminal->ClearStdError();
  1229. ReadCommandOutput(coExpectNoOutput | coWaitForLastLine | coOnlyReturnCode |
  1230. (Failed ? 0 : coRaiseExcept));
  1231. }
  1232. }
  1233. catch (Exception &E)
  1234. {
  1235. // Only show error message (it should always succeed, but
  1236. // some pending error maybe in queque) }
  1237. HandleExtendedException(&E, this);
  1238. }
  1239. }
  1240. }
  1241. }
  1242. //---------------------------------------------------------------------------
  1243. void __fastcall TSCPFileSystem::SCPSource(const AnsiString FileName,
  1244. const TCopyParamType * CopyParam, int Params,
  1245. TFileOperationProgressType * OperationProgress, int Level)
  1246. {
  1247. AnsiString DestFileName = CopyParam->ChangeFileName(
  1248. ExtractFileName(FileName), osLocal, Level == 0);
  1249. FTerminal->LogEvent(FORMAT("File: \"%s\"", (FileName)));
  1250. OperationProgress->SetFile(FileName);
  1251. HANDLE File;
  1252. int Attrs;
  1253. unsigned long MTime, ATime;
  1254. __int64 Size;
  1255. FTerminal->OpenLocalFile(FileName, GENERIC_READ,
  1256. &Attrs, &File, NULL, &MTime, &ATime, &Size);
  1257. if (Attrs & faDirectory)
  1258. {
  1259. SCPDirectorySource(FileName, CopyParam, Params, OperationProgress, Level);
  1260. }
  1261. else
  1262. try
  1263. {
  1264. assert(File);
  1265. // File is regular file (not directory)
  1266. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory started.", (FileName)));
  1267. OperationProgress->SetLocalSize(Size);
  1268. // Suppose same data size to transfer as to read
  1269. // (not true with ASCII transfer)
  1270. OperationProgress->SetTransferSize(OperationProgress->LocalSize);
  1271. OperationProgress->TransferingFile = false;
  1272. // Will we use ASCII of BINARY file tranfer?
  1273. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(FileName));
  1274. FTerminal->LogEvent(
  1275. AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  1276. " transfer mode selected.");
  1277. try
  1278. {
  1279. // During ASCII transfer we will load whole file to this buffer
  1280. // than convert EOL and send it at once, because before converting EOL
  1281. // we can't know its size
  1282. TFileBuffer AsciiBuf;
  1283. do
  1284. {
  1285. // Buffer for one block of data
  1286. TFileBuffer BlockBuf;
  1287. // This is crucial, if it fails during file transfer, it's fatal error
  1288. FILE_OPERATION_LOOP (FMTLOAD(READ_ERROR, (FileName)),
  1289. BlockBuf.LoadFile(File, OperationProgress->LocalBlockSize(), true);
  1290. );
  1291. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  1292. // We do ASCII transfer: convert EOL of current block
  1293. // (we don't convert whole buffer, cause it would produce
  1294. // huge memory-transfers while inserting/deleting EOL characters)
  1295. // Than we add current block to file buffer
  1296. if (OperationProgress->AsciiTransfer)
  1297. {
  1298. BlockBuf.Convert(FTerminal->Configuration->LocalEOLType,
  1299. FTerminal->SessionData->EOLType, cpRemoveCtrlZ);
  1300. BlockBuf.Memory->Seek(0, soFromBeginning);
  1301. AsciiBuf.ReadStream(BlockBuf.Memory, BlockBuf.Size, true);
  1302. // We don't need it any more
  1303. BlockBuf.Memory->Clear();
  1304. // Calculate total size to sent (assume that ratio between
  1305. // size of source and size of EOL-transformed data would remain same)
  1306. // First check if file contains anything (div by zero!)
  1307. if (OperationProgress->LocalyUsed)
  1308. {
  1309. __int64 X = OperationProgress->LocalSize;
  1310. X *= AsciiBuf.Size;
  1311. X /= OperationProgress->LocalyUsed;
  1312. OperationProgress->SetTransferSize(X);
  1313. }
  1314. else
  1315. {
  1316. OperationProgress->SetTransferSize(0);
  1317. }
  1318. }
  1319. // We send file information on first pass during BINARY transfer
  1320. // and on last pass during ASCII transfer
  1321. // BINARY: We succeeded reading first buffer from file, hopefully
  1322. // we will be able to read whole, so we send file info to remote side
  1323. // This is done, because when reading fails we can't interrupt sending
  1324. // (don't know how to tell other side that it failed)
  1325. if (!OperationProgress->TransferingFile &&
  1326. (!OperationProgress->AsciiTransfer || OperationProgress->IsLocalyDone()))
  1327. {
  1328. AnsiString Buf;
  1329. if (CopyParam->PreserveTime)
  1330. {
  1331. // Send last file access and modification time
  1332. // TVarRec don't understand 'unsigned int' -> we use sprintf()
  1333. Buf.sprintf("T%lu 0 %lu 0", MTime, ATime);
  1334. FTerminal->SendLine(Buf);
  1335. SCPResponse();
  1336. }
  1337. // Send file modes (rights), filesize and file name
  1338. // TVarRec don't understand 'unsigned int' -> we use sprintf()
  1339. Buf.sprintf("C0%s %Ld %s",
  1340. CopyParam->RemoteFileRights(Attrs).Octal.data(),
  1341. (OperationProgress->AsciiTransfer ? (__int64)AsciiBuf.Size :
  1342. OperationProgress->LocalSize),
  1343. DestFileName.data());
  1344. FTerminal->SendLine(Buf);
  1345. SCPResponse();
  1346. // Indicate we started transfering file, we need to finish it
  1347. // If not, it's fatal error
  1348. OperationProgress->TransferingFile = true;
  1349. // If we're doing ASCII transfer, this is last pass
  1350. // so we send whole file
  1351. /* TODO : We can't send file above 32bit size in ASCII mode! */
  1352. if (OperationProgress->AsciiTransfer)
  1353. {
  1354. FTerminal->LogEvent(FORMAT("Sending ASCII data (%ud bytes)",
  1355. (AsciiBuf.Size)));
  1356. // Should be equal, just in case it's rounded (see above)
  1357. OperationProgress->SetTransferSize(AsciiBuf.Size);
  1358. while (!OperationProgress->IsTransferDone())
  1359. {
  1360. FTerminal->Send(
  1361. AsciiBuf.Data + (unsigned int)OperationProgress->TransferedSize,
  1362. OperationProgress->TransferBlockSize());
  1363. OperationProgress->AddTransfered(OperationProgress->TransferBlockSize());
  1364. }
  1365. }
  1366. }
  1367. // At end of BINARY transfer pass, send current block
  1368. if (!OperationProgress->AsciiTransfer)
  1369. {
  1370. if (!OperationProgress->TransferedSize)
  1371. {
  1372. FTerminal->LogEvent("Sending BINARY data (first block)");
  1373. }
  1374. FTerminal->Send(BlockBuf.Data, BlockBuf.Size);
  1375. OperationProgress->AddTransfered(BlockBuf.Size);
  1376. }
  1377. if ((OperationProgress->Cancel == csCancelTransfer) ||
  1378. (OperationProgress->Cancel == csCancel && !OperationProgress->TransferingFile))
  1379. {
  1380. throw Exception(USER_TERMINATED);
  1381. }
  1382. }
  1383. while (!OperationProgress->IsLocalyDone() || !OperationProgress->IsTransferDone());
  1384. FTerminal->SendNull();
  1385. try
  1386. {
  1387. SCPResponse();
  1388. // If one of two following exceptions occurs, is means, that remote
  1389. // side already know, that file transfer finished, even if it failed
  1390. // so we don't have to throw EFatal
  1391. }
  1392. catch (EScp &E)
  1393. {
  1394. // SCP protocol fatal error
  1395. OperationProgress->TransferingFile = false;
  1396. throw;
  1397. }
  1398. catch (EScpFileSkipped &E)
  1399. {
  1400. // SCP protocol non-fatal error
  1401. OperationProgress->TransferingFile = false;
  1402. throw;
  1403. }
  1404. // We succeded transfering file, from now we can handle exceptions
  1405. // normally -> no fatal error
  1406. OperationProgress->TransferingFile = false;
  1407. }
  1408. catch (Exception &E)
  1409. {
  1410. // Every exception during file transfer is fatal
  1411. if (OperationProgress->TransferingFile)
  1412. {
  1413. FTerminal->FatalError(&E, FMTLOAD(COPY_FATAL, (FileName)));
  1414. }
  1415. else
  1416. {
  1417. throw;
  1418. }
  1419. }
  1420. }
  1421. __finally
  1422. {
  1423. CloseHandle(File);
  1424. }
  1425. /* TODO : Delete also read-only files. */
  1426. /* TODO : Show error message on failure. */
  1427. if (Params & cpDelete) Sysutils::DeleteFile(FileName);
  1428. FTerminal->LogEvent(FORMAT("Copying \"%s\" to remote directory finished.", (FileName)));
  1429. }
  1430. //---------------------------------------------------------------------------
  1431. void __fastcall TSCPFileSystem::SCPDirectorySource(const AnsiString DirectoryName,
  1432. const TCopyParamType * CopyParam, int Params,
  1433. TFileOperationProgressType * OperationProgress, int Level)
  1434. {
  1435. int Attrs;
  1436. FTerminal->LogEvent(FORMAT("Entering directory \"%s\".", (DirectoryName)));
  1437. OperationProgress->SetFile(DirectoryName);
  1438. AnsiString DestFileName = CopyParam->ChangeFileName(
  1439. ExtractFileName(DirectoryName), osLocal, Level == 0);
  1440. // Get directory attributes
  1441. FILE_OPERATION_LOOP (FMTLOAD(CANT_GET_ATTRS, (DirectoryName)),
  1442. Attrs = FileGetAttr(DirectoryName);
  1443. if (Attrs == -1) EXCEPTION;
  1444. )
  1445. AnsiString Buf;
  1446. /* TODO 1: maybe send filetime */
  1447. // Send directory modes (rights), filesize and file name
  1448. Buf = FORMAT("D0%s 0 %s",
  1449. (CopyParam->RemoteFileRights(Attrs).Octal, DestFileName));
  1450. FTerminal->SendLine(Buf);
  1451. SCPResponse();
  1452. try
  1453. {
  1454. int FindAttrs = faReadOnly | faHidden | faSysFile | faDirectory | faArchive;
  1455. TSearchRec SearchRec;
  1456. bool FindOK;
  1457. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1458. FindOK = (bool)(FindFirst(IncludeTrailingBackslash(DirectoryName) + "*.*",
  1459. FindAttrs, SearchRec) == 0);
  1460. );
  1461. while (FindOK && !OperationProgress->Cancel)
  1462. {
  1463. AnsiString FileName = IncludeTrailingBackslash(DirectoryName) + SearchRec.Name;
  1464. try
  1465. {
  1466. if ((SearchRec.Name != ".") && (SearchRec.Name != ".."))
  1467. {
  1468. SCPSource(FileName, CopyParam, Params, OperationProgress, Level + 1);
  1469. }
  1470. }
  1471. catch (EScpSkipFile &E)
  1472. {
  1473. // If ESkipFile occurs, just log it and continue with next file
  1474. SUSPEND_OPERATION (
  1475. if (FTerminal->DoQueryUser(FMTLOAD(COPY_ERROR, (FileName)), E.Message,
  1476. qaOK | qaAbort, qpAllowContinueOnError) == qaAbort)
  1477. {
  1478. OperationProgress->Cancel = csCancel;
  1479. }
  1480. if (!FTerminal->HandleException(&E)) throw;
  1481. );
  1482. }
  1483. FILE_OPERATION_LOOP (FMTLOAD(LIST_DIR_ERROR, (DirectoryName)),
  1484. FindOK = (FindNext(SearchRec) == 0);
  1485. );
  1486. };
  1487. FindClose(SearchRec);
  1488. /* TODO : Delete also read-only directories. */
  1489. /* TODO : Show error message on failure. */
  1490. if ((Params & cpDelete) && !OperationProgress->Cancel) RemoveDir(DirectoryName);
  1491. }
  1492. __finally
  1493. {
  1494. if (FTerminal->Active)
  1495. {
  1496. // Tell remote side, that we're done.
  1497. FTerminal->LogEvent(FORMAT("Leaving directory \"%s\".", (DirectoryName)));
  1498. FTerminal->SendLine("E");
  1499. SCPResponse();
  1500. }
  1501. }
  1502. }
  1503. //---------------------------------------------------------------------------
  1504. void __fastcall TSCPFileSystem::CopyToLocal(TStrings * FilesToCopy,
  1505. const AnsiString TargetDir, const TCopyParamType * CopyParam,
  1506. int Params, TFileOperationProgressType * OperationProgress,
  1507. bool & DisconnectWhenComplete)
  1508. {
  1509. bool CloseSCP = False;
  1510. AnsiString Options = "";
  1511. if (CopyParam->PreserveRights || CopyParam->PreserveTime) Options = "-p";
  1512. if (FTerminal->SessionData->Scp1Compatibility) Options += " -1";
  1513. FTerminal->LogEvent(FORMAT("Copying %d files/directories to local directory "
  1514. "\"%s\"", (FilesToCopy->Count, TargetDir)));
  1515. FTerminal->LogEvent(CopyParam->LogStr);
  1516. try
  1517. {
  1518. for (int IFile = 0; (IFile < FilesToCopy->Count) &&
  1519. !OperationProgress->Cancel; IFile++)
  1520. {
  1521. AnsiString FileName = FilesToCopy->Strings[IFile];
  1522. TRemoteFile * File = (TRemoteFile *)FilesToCopy->Objects[IFile];
  1523. assert(File);
  1524. try
  1525. {
  1526. bool Success = true; // Have to be set to True (see ::SCPSink)
  1527. SendCommand(FCommandSet->FullCommand(fsCopyToLocal,
  1528. ARRAYOFCONST((Options, DelimitStr(FileName)))));
  1529. SkipFirstLine();
  1530. // Filename is used only for error messaging
  1531. SCPSink(TargetDir, FileName, CopyParam, Success, OperationProgress,
  1532. Params, 0);
  1533. // operation succeded (no exception), so it's ok that
  1534. // remote side closed SCP, but we continue with next file
  1535. if (OperationProgress->Cancel == csRemoteAbort)
  1536. {
  1537. OperationProgress->Cancel = csContinue;
  1538. }
  1539. // Move operation -> delete file/directory afterwards
  1540. // but only if copying succeded
  1541. if ((Params & cpDelete) && Success && !OperationProgress->Cancel)
  1542. {
  1543. try
  1544. {
  1545. FTerminal->ExceptionOnFail = true;
  1546. try
  1547. {
  1548. FILE_OPERATION_LOOP(FMTLOAD(DELETE_FILE_ERROR, (FileName)),
  1549. FTerminal->DeleteFile("", File)
  1550. );
  1551. }
  1552. __finally
  1553. {
  1554. FTerminal->ExceptionOnFail = false;
  1555. }
  1556. }
  1557. catch (EFatal &E)
  1558. {
  1559. throw;
  1560. }
  1561. catch (...)
  1562. {
  1563. // If user selects skip (or abort), nothing special actualy occures
  1564. // we just run DoFinished with Success = False, so file won't
  1565. // be deselected in panel (depends on assigned event handler)
  1566. // On csCancel we would later try to close remote SCP, but it
  1567. // is closed already
  1568. if (OperationProgress->Cancel == csCancel)
  1569. {
  1570. OperationProgress->Cancel = csRemoteAbort;
  1571. }
  1572. Success = false;
  1573. }
  1574. }
  1575. OperationProgress->Finish(FileName,
  1576. (!OperationProgress->Cancel && Success), DisconnectWhenComplete);
  1577. }
  1578. catch (...)
  1579. {
  1580. OperationProgress->Finish(FileName, false, DisconnectWhenComplete);
  1581. CloseSCP = (OperationProgress->Cancel != csRemoteAbort);
  1582. throw;
  1583. }
  1584. }
  1585. }
  1586. __finally
  1587. {
  1588. // In case that copying don't causes fatal error (ie. connection is
  1589. // still active) but weren't succesful (exception or user termination)
  1590. // we need to ensure, that SCP on remote side is closed
  1591. if (FTerminal->Active && (CloseSCP ||
  1592. (OperationProgress->Cancel == csCancel) ||
  1593. (OperationProgress->Cancel == csCancelTransfer)))
  1594. {
  1595. bool LastLineRead;
  1596. // If we get LastLine, it means that remote side 'scp' is already
  1597. // terminated, so we need not to terminate it. There is also
  1598. // possibility that remote side waits for confirmation, so it will hang.
  1599. // This should not happen (hope)
  1600. AnsiString Line = FTerminal->ReceiveLine();
  1601. LastLineRead = IsLastLine(Line);
  1602. if (!LastLineRead)
  1603. {
  1604. SCPSendError((OperationProgress->Cancel ? "Terminated by user." : "Exception"), true);
  1605. }
  1606. // Just in case, remote side already sent some more data (it's probable)
  1607. // but we don't want to raise exception (user asked to terminate, it's not error)
  1608. int ECParams = coOnlyReturnCode;
  1609. if (!LastLineRead) ECParams |= coWaitForLastLine;
  1610. ReadCommandOutput(ECParams);
  1611. }
  1612. }
  1613. }
  1614. //---------------------------------------------------------------------------
  1615. void __fastcall TSCPFileSystem::SCPError(const AnsiString Message, bool Fatal)
  1616. {
  1617. SCPSendError(Message, Fatal);
  1618. THROW_FILE_SKIPPED(NULL, Message);
  1619. }
  1620. //---------------------------------------------------------------------------
  1621. void __fastcall TSCPFileSystem::SCPSendError(const AnsiString Message, bool Fatal)
  1622. {
  1623. char ErrorLevel = (char)(Fatal ? 2 : 1);
  1624. FTerminal->LogEvent(FORMAT("Sending SCP error (%d) to remote side:",
  1625. ((int)ErrorLevel)));
  1626. FTerminal->Send(&ErrorLevel, 1);
  1627. // We don't send exact error message, because some unspecified
  1628. // characters can terminate remote scp
  1629. FTerminal->SendLine("scp: error");
  1630. }
  1631. //---------------------------------------------------------------------------
  1632. void __fastcall TSCPFileSystem::SCPSink(const AnsiString TargetDir,
  1633. const AnsiString FileName, const TCopyParamType * CopyParam, bool & Success,
  1634. TFileOperationProgressType * OperationProgress, int Params,
  1635. int Level)
  1636. {
  1637. struct
  1638. {
  1639. int SetTime;
  1640. FILETIME AcTime;
  1641. FILETIME WrTime;
  1642. TRights RemoteRights;
  1643. int Attrs;
  1644. bool Exists;
  1645. } FileData;
  1646. TDateTime SourceTimestamp;
  1647. bool SkipConfirmed = false;
  1648. bool Initialized = (Level > 0);
  1649. FileData.SetTime = 0;
  1650. FTerminal->SendNull();
  1651. while (!OperationProgress->Cancel)
  1652. {
  1653. // See (switch ... case 'T':)
  1654. if (FileData.SetTime) FileData.SetTime--;
  1655. // In case of error occured before control record arrived
  1656. OperationProgress->FileName = FileName;
  1657. try
  1658. {
  1659. // Receive control record
  1660. AnsiString Line = FTerminal->ReceiveLine();
  1661. if (Line.Length() == 0) FTerminal->FatalError(LoadStr(SCP_EMPTY_LINE));
  1662. if (IsLastLine(Line))
  1663. {
  1664. // Remote side finished copying, so remote SCP was closed
  1665. // and we don't need to terminate it manualy, see CopyToLocal()
  1666. OperationProgress->Cancel = csRemoteAbort;
  1667. /* TODO 1 : Show stderror to user? */
  1668. FTerminal->ClearStdError();
  1669. try
  1670. {
  1671. // coIgnoreWarnings should allow batch transfer to continue when
  1672. // download of one the files failes (user denies overwritting
  1673. // of target local file, no read permissions...)
  1674. ReadCommandOutput(coExpectNoOutput | coRaiseExcept |
  1675. coOnlyReturnCode | coIgnoreWarnings);
  1676. if (!Initialized)
  1677. {
  1678. throw Exception("");
  1679. }
  1680. }
  1681. catch(Exception & E)
  1682. {
  1683. if (!Initialized && FTerminal->Active)
  1684. {
  1685. FTerminal->TerminalError(&E, LoadStr(SCP_INIT_ERROR));
  1686. }
  1687. else
  1688. {
  1689. throw;
  1690. }
  1691. }
  1692. return;
  1693. }
  1694. else
  1695. {
  1696. Initialized = true;
  1697. // First characted distinguish type of control record
  1698. char Ctrl = Line[1];
  1699. Line.Delete(1, 1);
  1700. switch (Ctrl) {
  1701. case 1:
  1702. // Error (already logged by ReceiveLine())
  1703. THROW_FILE_SKIPPED(NULL, FMTLOAD(REMOTE_ERROR, (Line)));
  1704. case 2:
  1705. // Fatal error, terminate copying
  1706. FTerminal->TerminalError(Line);
  1707. return; // Unreachable
  1708. case 'E': // Exit
  1709. FTerminal->SendNull();
  1710. return;
  1711. case 'T':
  1712. unsigned long MTime, ATime;
  1713. if (sscanf(Line.c_str(), "%ld %*d %ld %*d", &MTime, &ATime) == 2)
  1714. {
  1715. TIME_POSIX_TO_WIN(ATime, FileData.AcTime);
  1716. TIME_POSIX_TO_WIN(MTime, FileData.WrTime);
  1717. SourceTimestamp = UnixToDateTime(MTime);
  1718. FTerminal->SendNull();
  1719. // File time is only valid until next pass
  1720. FileData.SetTime = 2;
  1721. continue;
  1722. }
  1723. else
  1724. {
  1725. SCPError(LoadStr(SCP_ILLEGAL_TIME_FORMAT), False);
  1726. }
  1727. case 'C':
  1728. case 'D':
  1729. break; // continue pass switch{}
  1730. default:
  1731. FTerminal->FatalError(FMTLOAD(SCP_INVALID_CONTROL_RECORD, (Ctrl, Line)));
  1732. }
  1733. // We reach this point only if control record was 'C' or 'D'
  1734. try
  1735. {
  1736. Line.Delete(1, 1); // Zero at beginning
  1737. FileData.RemoteRights.Octal = CutToChar(Line, ' ', True);
  1738. __int64 TSize = StrToInt64(CutToChar(Line, ' ', True));
  1739. // Security fix: ensure the file ends up where we asked for it.
  1740. // (accept only filename, not path)
  1741. AnsiString OnlyFileName = UnixExtractFileName(Line);
  1742. if (Line != OnlyFileName)
  1743. {
  1744. FTerminal->LogEvent(FORMAT("Warning: Remote host set a compound pathname '%s'", (Line)));
  1745. }
  1746. OperationProgress->SetFile(OnlyFileName);
  1747. OperationProgress->SetTransferSize(TSize);
  1748. }
  1749. catch (Exception &E)
  1750. {
  1751. SUSPEND_OPERATION (
  1752. HandleExtendedException(&E);
  1753. );
  1754. SCPError(LoadStr(SCP_ILLEGAL_FILE_DESCRIPTOR), false);
  1755. }
  1756. // last possibility to cancel transfer before it starts
  1757. if (OperationProgress->Cancel)
  1758. {
  1759. THROW_SKIP_FILE(NULL, LoadStr(USER_TERMINATED));
  1760. }
  1761. // Security fix
  1762. if (IsDots(OperationProgress->FileName))
  1763. {
  1764. FTerminal->FatalError(LoadStr(ATTEMPT_TO_WRITE_TO_PARENT_DIR));
  1765. }
  1766. AnsiString DestFileName =
  1767. IncludeTrailingBackslash(TargetDir) +
  1768. CopyParam->ChangeFileName(OperationProgress->FileName, osRemote,
  1769. Level == 0);
  1770. FileData.Attrs = FileGetAttr(DestFileName);
  1771. // If getting attrs failes, we suppose, that file/folder doesn't exists
  1772. FileData.Exists = (FileData.Attrs != -1);
  1773. if (Ctrl == 'D')
  1774. {
  1775. if (FileData.Exists && !(FileData.Attrs & faDirectory))
  1776. {
  1777. SCPError(FMTLOAD(NOT_DIRECTORY_ERROR, (DestFileName)), false);
  1778. }
  1779. if (!FileData.Exists)
  1780. {
  1781. FILE_OPERATION_LOOP (FMTLOAD(CREATE_DIR_ERROR, (DestFileName)),
  1782. if (!ForceDirectories(DestFileName)) EXCEPTION;
  1783. );
  1784. /* SCP: can we set the timestamp for directories ? */
  1785. }
  1786. /* TODO 1 : Send whole path, CopyData.SourceFileName is not enough
  1787. (just error messaging)*/
  1788. SCPSink(DestFileName, OperationProgress->FileName, CopyParam,
  1789. Success, OperationProgress, Params, Level + 1);
  1790. continue;
  1791. }
  1792. else
  1793. if (Ctrl == 'C')
  1794. {
  1795. HANDLE File = NULL;
  1796. TStream * FileStream = NULL;
  1797. /* TODO 1 : Turn off read-only attr */
  1798. try
  1799. {
  1800. try
  1801. {
  1802. if (FileExists(DestFileName))
  1803. {
  1804. if (OperationProgress->NoToAll)
  1805. {
  1806. EXCEPTION;
  1807. }
  1808. else if (!OperationProgress->YesToAll &&
  1809. FTerminal->Configuration->ConfirmOverwriting &&
  1810. !(Params & cpNoConfirmation))
  1811. {
  1812. int Answer;
  1813. unsigned long MTime;
  1814. TOverwriteFileParams FileParams;
  1815. FileParams.SourceSize = OperationProgress->TransferSize;
  1816. FileParams.SourceTimestamp = SourceTimestamp;
  1817. FTerminal->OpenLocalFile(DestFileName, GENERIC_READ,
  1818. NULL, NULL, NULL, &MTime, NULL,
  1819. &FileParams.DestSize);
  1820. FileParams.DestTimestamp = UnixToDateTime(MTime);
  1821. SUSPEND_OPERATION (
  1822. Answer = FTerminal->ConfirmFileOverwrite(
  1823. OperationProgress->FileName, &FileParams,
  1824. qaYes | qaNo | qaAbort | qaYesToAll | qaNoToAll,
  1825. qpNeverAskAgainCheck);
  1826. );
  1827. switch (Answer) {
  1828. case qaNeverAskAgain: FTerminal->Configuration->ConfirmOverwriting = false; break;
  1829. case qaYesToAll: OperationProgress->YesToAll = true; break;
  1830. case qaAbort: OperationProgress->Cancel = csCancel; // continue on next case
  1831. case qaNoToAll: OperationProgress->NoToAll = true;
  1832. case qaNo: SkipConfirmed = true; EXCEPTION;
  1833. }
  1834. }
  1835. }
  1836. if (!FTerminal->CreateLocalFile(DestFileName, OperationProgress, &File))
  1837. {
  1838. SkipConfirmed = true;
  1839. EXCEPTION;
  1840. }
  1841. FileStream = new THandleStream((THandle)File);
  1842. }
  1843. catch (Exception &E)
  1844. {
  1845. // In this step we can still cancel transfer, so we do it
  1846. SCPError(E.Message, false);
  1847. throw;
  1848. }
  1849. // We succeded, so we confirm transfer to remote side
  1850. FTerminal->SendNull();
  1851. // From now we need to finish file transfer, if not it's fatal error
  1852. OperationProgress->TransferingFile = true;
  1853. // Suppose same data size to transfer as to write
  1854. // (not true with ASCII transfer)
  1855. OperationProgress->SetLocalSize(OperationProgress->TransferSize);
  1856. // Will we use ASCII of BINARY file tranfer?
  1857. OperationProgress->SetAsciiTransfer(CopyParam->UseAsciiTransfer(DestFileName));
  1858. FTerminal->LogEvent(AnsiString((OperationProgress->AsciiTransfer ? "Ascii" : "Binary")) +
  1859. " transfer mode selected.");
  1860. try
  1861. {
  1862. // Buffer for one block of data
  1863. TFileBuffer BlockBuf;
  1864. do
  1865. {
  1866. BlockBuf.Size = OperationProgress->TransferBlockSize();
  1867. BlockBuf.Position = 0;
  1868. FTerminal->Receive(BlockBuf.Data, BlockBuf.Size);
  1869. OperationProgress->AddTransfered(BlockBuf.Size);
  1870. if (OperationProgress->AsciiTransfer)
  1871. {
  1872. unsigned int PrevBlockSize = BlockBuf.Size;
  1873. BlockBuf.Convert(FTerminal->SessionData->EOLType,
  1874. FTerminal->Configuration->LocalEOLType, 0);
  1875. OperationProgress->SetLocalSize(
  1876. OperationProgress->LocalSize - PrevBlockSize + BlockBuf.Size);
  1877. }
  1878. // This is crucial, if it fails during file transfer, it's fatal error
  1879. FILE_OPERATION_LOOP_EX (false, FMTLOAD(WRITE_ERROR, (DestFileName)),
  1880. BlockBuf.WriteToStream(FileStream, BlockBuf.Size);
  1881. );
  1882. OperationProgress->AddLocalyUsed(BlockBuf.Size);
  1883. if (OperationProgress->Cancel == csCancelTransfer)
  1884. {
  1885. throw Exception(USER_TERMINATED);
  1886. }
  1887. }
  1888. while (!OperationProgress->IsLocalyDone() || !
  1889. OperationProgress->IsTransferDone());
  1890. }
  1891. catch (Exception &E)
  1892. {
  1893. // Every exception during file transfer is fatal
  1894. FTerminal->FatalError(&E,
  1895. FMTLOAD(COPY_FATAL, (OperationProgress->FileName)));
  1896. }
  1897. OperationProgress->TransferingFile = false;
  1898. try
  1899. {
  1900. SCPResponse();
  1901. // If one of following exception occurs, we still need
  1902. // to send confirmation to other side
  1903. }
  1904. catch (EScp &E)
  1905. {
  1906. FTerminal->SendNull();
  1907. throw;
  1908. }
  1909. catch (EScpFileSkipped &E)
  1910. {
  1911. FTerminal->SendNull();
  1912. throw;
  1913. }
  1914. FTerminal->SendNull();
  1915. if (FileData.SetTime && CopyParam->PreserveTime)
  1916. {
  1917. SetFileTime(File, NULL, &FileData.AcTime, &FileData.WrTime);
  1918. }
  1919. }
  1920. __finally
  1921. {
  1922. if (File) CloseHandle(File);
  1923. if (FileStream) delete FileStream;
  1924. }
  1925. if (FileData.Attrs == -1) FileData.Attrs = faArchive;
  1926. int NewAttrs = CopyParam->LocalFileAttrs(FileData.RemoteRights);
  1927. if ((NewAttrs & FileData.Attrs) != NewAttrs)
  1928. {
  1929. FILE_OPERATION_LOOP (FMTLOAD(CANT_SET_ATTRS, (DestFileName)),
  1930. FileSetAttr(DestFileName, FileData.Attrs | NewAttrs);
  1931. );
  1932. }
  1933. }
  1934. }
  1935. }
  1936. catch (EScpFileSkipped &E)
  1937. {
  1938. if (!SkipConfirmed)
  1939. {
  1940. SUSPEND_OPERATION (
  1941. if (FTerminal->DoQueryUser(FMTLOAD(COPY_ERROR, (OperationProgress->FileName)),
  1942. E.Message, qaOK | qaAbort, qpAllowContinueOnError) == qaAbort)
  1943. {
  1944. OperationProgress->Cancel = csCancel;
  1945. }
  1946. HandleExtendedException(&E, this);
  1947. );
  1948. Success = false;
  1949. }
  1950. }
  1951. catch (EScpSkipFile &E)
  1952. {
  1953. SCPSendError(E.Message, false);
  1954. Success = false;
  1955. if (!FTerminal->HandleException(&E)) throw;
  1956. }
  1957. }
  1958. }