ScpFileSystem.cpp 98 KB

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