ScpFileSystem.cpp 92 KB

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