ScpFileSystem.cpp 90 KB

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