ScpFileSystem.cpp 81 KB

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