ScpFileSystem.cpp 91 KB

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