ScpFileSystem.cpp 98 KB

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