ScpFileSystem.cpp 91 KB

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