ScpFileSystem.cpp 98 KB

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