1
0

ScpFileSystem.cpp 91 KB

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