ScpFileSystem.cpp 98 KB

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