ScpFileSystem.cpp 79 KB

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