ScpFileSystem.cpp 98 KB

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