ScpFileSystem.cpp 91 KB

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