ScpFileSystem.cpp 89 KB

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