ScpFileSystem.cpp 84 KB

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