ScpFileSystem.cpp 99 KB

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