ScpFileSystem.cpp 98 KB

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