ScpFileSystem.cpp 98 KB

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