1
0

ScpFileSystem.cpp 92 KB

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