ScpFileSystem.cpp 91 KB

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