ScpFileSystem.cpp 91 KB

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